-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathSimulation.java
1173 lines (1011 loc) · 32.1 KB
/
Simulation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2009, Swedish Institute of Computer Science. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. 2. Redistributions in
* binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution. 3. Neither the name of the
* Institute nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.contikios.cooja;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import java.util.Vector;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.jdom.Element;
import org.contikios.cooja.dialogs.CreateSimDialog;
/**
* A simulation consists of a number of motes and mote types.
*
* A simulation is observable:
* changed simulation state, added or deleted motes etc are observed.
* To track mote changes, observe the mote (interfaces) itself.
*
* @author Fredrik Osterlind
*/
public class Simulation extends Observable implements Runnable {
public static final long MICROSECOND = 1L;
public static final long MILLISECOND = 1000*MICROSECOND;
/*private static long EVENT_COUNTER = 0;*/
private Vector<Mote> motes = new Vector<Mote>();
private Vector<Mote> motesUninit = new Vector<Mote>();
private Vector<MoteType> moteTypes = new Vector<MoteType>();
/* If true, run simulation at full speed */
private boolean speedLimitNone = true;
/* Limit simulation speed to maxSpeed; if maxSpeed is 1.0 simulation is run at real-time speed */
private double speedLimit;
/* Used to restrict simulation speed */
private long speedLimitLastSimtime;
private long speedLimitLastRealtime;
private long lastStartTime;
private long currentSimulationTime = 0;
private String title = null;
private RadioMedium currentRadioMedium = null;
private static Logger logger = Logger.getLogger(Simulation.class);
private boolean isRunning = false;
private boolean stopSimulation = false;
private Thread simulationThread = null;
private Cooja cooja = null;
private long randomSeed = 123456;
private boolean randomSeedGenerated = false;
private long maxMoteStartupDelay = 1000*MILLISECOND;
private SafeRandom randomGenerator;
private boolean hasMillisecondObservers = false;
private MillisecondObservable millisecondObservable = new MillisecondObservable();
private class MillisecondObservable extends Observable {
private void newMillisecond(long time) {
setChanged();
notifyObservers(time);
}
}
/* Event queue */
private EventQueue eventQueue = new EventQueue();
/* Poll requests */
private boolean hasPollRequests = false;
private ArrayDeque<Runnable> pollRequests = new ArrayDeque<Runnable>();
/**
* Request poll from simulation thread.
* Poll requests are prioritized over simulation events, and are
* executed between each simulation event.
*
* @param r Simulation thread action
*/
public void invokeSimulationThread(Runnable r) {
synchronized (pollRequests) {
pollRequests.addLast(r);
hasPollRequests = true;
}
}
private Runnable popSimulationInvokes() {
Runnable r;
synchronized (pollRequests) {
r = pollRequests.pop();
hasPollRequests = !pollRequests.isEmpty();
}
return r;
}
/**
* Add millisecond observer.
* This observer is notified once every simulated millisecond.
*
* @see #deleteMillisecondObserver(Observer)
* @param newObserver Observer
*/
public void addMillisecondObserver(Observer newObserver) {
millisecondObservable.addObserver(newObserver);
hasMillisecondObservers = true;
invokeSimulationThread(new Runnable() {
public void run() {
if (!millisecondEvent.isScheduled()) {
scheduleEvent(
millisecondEvent,
currentSimulationTime - (currentSimulationTime % MILLISECOND) + MILLISECOND);
}
}
});
}
/**
* Delete millisecond observer.
*
* @see #addMillisecondObserver(Observer)
* @param observer Observer to delete
*/
public void deleteMillisecondObserver(Observer observer) {
millisecondObservable.deleteObserver(observer);
hasMillisecondObservers = millisecondObservable.countObservers() > 0;
}
/**
* @return True iff current thread is the simulation thread
*/
public boolean isSimulationThread() {
return simulationThread == Thread.currentThread();
}
/**
* Schedule simulation event for given time.
* Already scheduled events must be removed before they are rescheduled.
*
* If the simulation is running, this method may only be called from the simulation thread.
*
* @see #invokeSimulationThread(Runnable)
*
* @param e Event
* @param time Execution time
*/
public void scheduleEvent(final TimeEvent e, final long time) {
if (isRunning) {
/* TODO Strict scheduling from simulation thread */
assert isSimulationThread() : "Scheduling event from non-simulation thread: " + e;
}
eventQueue.addEvent(e, time);
}
private TimeEvent delayEvent = new TimeEvent(0) {
public void execute(long t) {
if (speedLimitNone) {
/* As fast as possible: no need to reschedule delay event */
return;
}
long diffSimtime = (getSimulationTime() - speedLimitLastSimtime)/1000; /* ms */
long diffRealtime = System.currentTimeMillis() - speedLimitLastRealtime; /* ms */
long expectedDiffRealtime = (long) (diffSimtime/speedLimit);
long sleep = expectedDiffRealtime - diffRealtime;
if (sleep >= 0) {
/* Slow down simulation */
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
}
scheduleEvent(this, t+MILLISECOND);
} else {
/* Reduce slow-down: execute this delay event less often */
scheduleEvent(this, t-sleep*MILLISECOND);
}
/* Update counters every second */
if (diffRealtime > 1000) {
speedLimitLastRealtime = System.currentTimeMillis();
speedLimitLastSimtime = getSimulationTime();
}
}
public String toString() {
return "DELAY";
}
};
private TimeEvent millisecondEvent = new TimeEvent(0) {
public void execute(long t) {
if (!hasMillisecondObservers) {
return;
}
millisecondObservable.newMillisecond(getSimulationTime());
scheduleEvent(this, t+MILLISECOND);
}
public String toString() {
return "MILLISECOND: " + millisecondObservable.countObservers();
}
};
public void clearEvents() {
eventQueue.removeAll();
pollRequests.clear();
}
public void run() {
lastStartTime = System.currentTimeMillis();
logger.info("Simulation main loop started, system time: " + lastStartTime);
isRunning = true;
speedLimitLastRealtime = System.currentTimeMillis();
speedLimitLastSimtime = getSimulationTime();
/* Simulation starting */
this.setChanged();
this.notifyObservers(this);
TimeEvent nextEvent = null;
try {
while (isRunning) {
/* Handle all poll requests */
while (hasPollRequests) {
popSimulationInvokes().run();
}
/* Handle one simulation event, and update simulation time */
nextEvent = eventQueue.popFirst();
if (nextEvent == null) {
throw new RuntimeException("No more events");
}
if (nextEvent.time < currentSimulationTime) {
throw new RuntimeException("Next event is in the past: " + nextEvent.time + " < " + currentSimulationTime + ": " + nextEvent);
}
currentSimulationTime = nextEvent.time;
/*logger.info("Executing event #" + EVENT_COUNTER++ + " @ " + currentSimulationTime + ": " + nextEvent);*/
nextEvent.execute(currentSimulationTime);
if (stopSimulation) {
isRunning = false;
}
}
} catch (RuntimeException e) {
if ("MSPSim requested simulation stop".equals(e.getMessage())) {
/* XXX Should be*/
logger.info("Simulation stopped due to MSPSim breakpoint");
} else {
logger.fatal("Simulation stopped due to error: " + e.getMessage(), e);
if (!Cooja.isVisualized()) {
/* Quit simulator if in test mode */
System.exit(1);
} else {
String title = "Simulation error";
if (nextEvent instanceof MoteTimeEvent) {
title += ": " + ((MoteTimeEvent)nextEvent).getMote();
}
Cooja.showErrorDialog(Cooja.getTopParentContainer(), title, e, false);
}
}
}
isRunning = false;
simulationThread = null;
stopSimulation = false;
this.setChanged();
this.notifyObservers(this);
logger.info("Simulation main loop stopped, system time: " + System.currentTimeMillis() +
"\tDuration: " + (System.currentTimeMillis() - lastStartTime) +
" ms" +
"\tSimulated time " + getSimulationTimeMillis() +
" ms\tRatio " +
((double)getSimulationTimeMillis() /
(double)(System.currentTimeMillis() - lastStartTime)));
}
/**
* Creates a new simulation
*/
public Simulation(Cooja cooja) {
this.cooja = cooja;
randomGenerator = new SafeRandom(this);
}
/**
* Starts this simulation (notifies observers).
*/
public void startSimulation() {
if (!isRunning()) {
isRunning = true;
simulationThread = new Thread(this);
simulationThread.setPriority(Thread.MIN_PRIORITY);
simulationThread.start();
}
}
/**
* Stop simulation
*
* @param block Block until simulation has stopped, with timeout (100ms)
*
* @see #stopSimulation()
*/
public void stopSimulation(boolean block) {
if (!isRunning()) {
return;
}
stopSimulation = true;
if (block) {
if (Thread.currentThread() == simulationThread) {
return;
}
/* Wait until simulation stops */
try {
Thread simThread = simulationThread;
if (simThread != null) {
simThread.join(100);
}
} catch (InterruptedException e) {
}
}
}
/**
* Stop simulation (blocks).
* Calls stopSimulation(true).
*
* @see #stopSimulation(boolean)
*/
public void stopSimulation() {
stopSimulation(true);
}
/**
* Starts simulation if stopped, executes one millisecond, and finally stops
* simulation again.
*/
public void stepMillisecondSimulation() {
if (isRunning()) {
return;
}
TimeEvent stopEvent = new TimeEvent(0) {
public void execute(long t) {
/* Stop simulation */
stopSimulation();
}
};
scheduleEvent(stopEvent, getSimulationTime()+Simulation.MILLISECOND);
startSimulation();
}
public Cooja getCooja() {
return cooja;
}
/**
* @return Random seed
*/
public long getRandomSeed() {
return randomSeed;
}
/**
* @return Random seed (converted to a string)
*/
public String getRandomSeedString() {
return Long.toString(randomSeed);
}
/**
* @param randomSeed Random seed
*/
public void setRandomSeed(long randomSeed) {
this.randomSeed = randomSeed;
randomGenerator.setSeed(randomSeed);
logger.info("Simulation random seed: " + randomSeed);
}
/**
* @param generated Autogenerated random seed at simulation load
*/
public void setRandomSeedGenerated(boolean generated) {
this.randomSeedGenerated = generated;
}
/**
* @return Autogenerated random seed at simulation load
*/
public boolean getRandomSeedGenerated() {
return randomSeedGenerated;
}
public Random getRandomGenerator() {
return randomGenerator;
}
/**
* @return Maximum mote startup delay
*/
public long getDelayedMoteStartupTime() {
return maxMoteStartupDelay;
}
/**
* @param maxMoteStartupDelay Maximum mote startup delay
*/
public void setDelayedMoteStartupTime(long maxMoteStartupDelay) {
this.maxMoteStartupDelay = Math.max(0, maxMoteStartupDelay);
}
private SimEventCentral eventCentral = new SimEventCentral(this);
public SimEventCentral getEventCentral() {
return eventCentral;
}
/**
* Returns the current simulation config represented by XML elements. This
* config also includes the current radio medium, all mote types and motes.
*
* @return Current simulation config
*/
public Collection<Element> getConfigXML() {
ArrayList<Element> config = new ArrayList<Element>();
Element element;
// Title
element = new Element("title");
element.setText(title);
config.add(element);
/* Max simulation speed */
if (!speedLimitNone) {
element = new Element("speedlimit");
element.setText("" + getSpeedLimit());
config.add(element);
}
// Random seed
element = new Element("randomseed");
if (randomSeedGenerated) {
element.setText("generated");
} else {
element.setText(Long.toString(getRandomSeed()));
}
config.add(element);
// Max mote startup delay
element = new Element("motedelay_us");
element.setText(Long.toString(maxMoteStartupDelay));
config.add(element);
// Radio Medium
element = new Element("radiomedium");
element.setText(currentRadioMedium.getClass().getName());
Collection<Element> radioMediumXML = currentRadioMedium.getConfigXML();
if (radioMediumXML != null) {
element.addContent(radioMediumXML);
}
config.add(element);
/* Event central */
element = new Element("events");
element.addContent(eventCentral.getConfigXML());
config.add(element);
// Mote types
for (MoteType moteType : getMoteTypes()) {
element = new Element("motetype");
element.setText(moteType.getClass().getName());
Collection<Element> moteTypeXML = moteType.getConfigXML(this);
if (moteTypeXML != null) {
element.addContent(moteTypeXML);
}
config.add(element);
}
// Motes
for (Mote mote : motes) {
element = new Element("mote");
Collection<Element> moteConfig = mote.getConfigXML();
if (moteConfig == null) {
moteConfig = new ArrayList<Element>();
}
/* Add mote type identifier */
Element typeIdentifier = new Element("motetype_identifier");
typeIdentifier.setText(mote.getType().getIdentifier());
moteConfig.add(typeIdentifier);
element.addContent(moteConfig);
config.add(element);
}
return config;
}
/* indicator to components setting up that they need to respect the fast setup mode */
private boolean quick = false;
public boolean isQuickSetup() {
return quick;
}
public void setQuickSetup(boolean q) {
quick = q;
}
/**
* Sets the current simulation config depending on the given configuration.
*
* @param configXML Simulation configuration
* @param visAvailable True if simulation is allowed to show visualizers
* @param manualRandomSeed Simulation random seed. May be null, in which case the configuration is used
* @return True if simulation was configured successfully
* @throws Exception If configuration could not be loaded
*/
public boolean setConfigXML(Collection<Element> configXML,
boolean visAvailable, boolean quick, Long manualRandomSeed) throws Exception {
setQuickSetup(quick);
// Parse elements
for (Element element : configXML) {
// Title
if (element.getName().equals("title")) {
title = element.getText();
}
/* Max simulation speed */
if (element.getName().equals("speedlimit")) {
String text = element.getText();
if (text.equals("null")) {
setSpeedLimit(null);
} else {
setSpeedLimit(Double.parseDouble(text));
}
}
// Random seed
if (element.getName().equals("randomseed")) {
long newSeed;
if (element.getText().equals("generated")) {
randomSeedGenerated = true;
newSeed = new Random().nextLong();
} else {
newSeed = Long.parseLong(element.getText());
}
if (manualRandomSeed != null) {
newSeed = manualRandomSeed;
}
setRandomSeed(newSeed);
}
// Max mote startup delay
if (element.getName().equals("motedelay")) {
maxMoteStartupDelay = Integer.parseInt(element.getText())*MILLISECOND;
}
if (element.getName().equals("motedelay_us")) {
maxMoteStartupDelay = Integer.parseInt(element.getText());
}
// Radio medium
if (element.getName().equals("radiomedium")) {
String radioMediumClassName = element.getText().trim();
/* Backwards compatibility: se.sics -> org.contikios */
if (radioMediumClassName.startsWith("se.sics")) {
radioMediumClassName = radioMediumClassName.replaceFirst("se\\.sics", "org.contikios");
}
Class<? extends RadioMedium> radioMediumClass = cooja.tryLoadClass(
this, RadioMedium.class, radioMediumClassName);
if (radioMediumClass != null) {
// Create radio medium specified in config
try {
currentRadioMedium = RadioMedium.generateRadioMedium(radioMediumClass, this);
} catch (Exception e) {
currentRadioMedium = null;
logger.warn("Could not load radio medium class: " + radioMediumClassName);
}
}
// Show configure simulation dialog
boolean createdOK = false;
if (visAvailable && !quick) {
createdOK = CreateSimDialog.showDialog(Cooja.getTopParentContainer(), this);
} else {
createdOK = true;
}
if (!createdOK) {
logger.debug("Simulation not created, aborting");
throw new Exception("Load aborted by user");
}
// Check if radio medium specific config should be applied
if (radioMediumClassName.equals(currentRadioMedium.getClass().getName())) {
currentRadioMedium.setConfigXML(element.getChildren(), visAvailable);
} else {
logger.info("Radio Medium changed - ignoring radio medium specific config");
}
}
/* Event central */
if (element.getName().equals("events")) {
eventCentral.setConfigXML(this, element.getChildren(), visAvailable);
}
// Mote type
if (element.getName().equals("motetype")) {
String moteTypeClassName = element.getText().trim();
/* Backwards compatibility: se.sics -> org.contikios */
if (moteTypeClassName.startsWith("se.sics")) {
moteTypeClassName = moteTypeClassName.replaceFirst("se\\.sics", "org.contikios");
}
/* Try to recreate simulation using a different mote type */
if (visAvailable && !quick) {
String[] availableMoteTypes = getCooja().getProjectConfig().getStringArrayValue("org.contikios.cooja.Cooja.MOTETYPES");
String newClass = (String) JOptionPane.showInputDialog(
Cooja.getTopParentContainer(),
"The simulation is about to load '" + moteTypeClassName + "'\n" +
"You may try to load the simulation using a different mote type.\n",
"Loading mote type",
JOptionPane.QUESTION_MESSAGE,
null,
availableMoteTypes,
moteTypeClassName
);
if (newClass == null) {
throw new MoteType.MoteTypeCreationException("No mote type class selected");
}
if (!newClass.equals(moteTypeClassName)) {
logger.warn("Changing mote type class: " + moteTypeClassName + " -> " + newClass);
moteTypeClassName = newClass;
}
}
Class<? extends MoteType> moteTypeClass = cooja.tryLoadClass(this,
MoteType.class, moteTypeClassName);
if (moteTypeClass == null) {
logger.fatal("Could not load mote type class: " + moteTypeClassName);
throw new MoteType.MoteTypeCreationException("Could not load mote type class: " + moteTypeClassName);
}
MoteType moteType = moteTypeClass.getConstructor((Class[]) null).newInstance();
boolean createdOK = moteType.setConfigXML(this, element.getChildren(),
visAvailable);
if (createdOK) {
addMoteType(moteType);
} else {
logger
.fatal("Mote type was not created: " + element.getText().trim());
throw new Exception("All mote types were not recreated");
}
}
/* Mote */
if (element.getName().equals("mote")) {
/* Read mote type identifier */
MoteType moteType = null;
for (Element subElement: (Collection<Element>) element.getChildren()) {
if (subElement.getName().equals("motetype_identifier")) {
moteType = getMoteType(subElement.getText());
if (moteType == null) {
throw new Exception("No mote type '" + subElement.getText() + "' for mote");
}
break;
}
}
if (moteType == null) {
throw new Exception("No mote type specified for mote");
}
/* Create mote using mote type */
Mote mote = moteType.generateMote(this);
if (mote.setConfigXML(this, element.getChildren(), visAvailable)) {
if (getMoteWithID(mote.getID()) != null) {
logger.warn("Ignoring duplicate mote ID: " + mote.getID());
} else {
addMote(mote);
}
} else {
logger.fatal("Mote was not created: " + element.getText().trim());
throw new Exception("All motes were not recreated");
}
}
}
if (currentRadioMedium != null) {
currentRadioMedium.simulationFinishedLoading();
}
setChanged();
notifyObservers(this);
/* Execute simulation thread events now, before simulation starts */
while (hasPollRequests) {
popSimulationInvokes().run();
}
return true;
}
/**
* Removes a mote from this simulation
*
* @param mote
* Mote to remove
*/
public void removeMote(final Mote mote) {
/* Simulation is running, remove mote in simulation loop */
Runnable removeMote = new Runnable() {
public void run() {
motes.remove(mote);
motesUninit.remove(mote);
currentRadioMedium.unregisterMote(mote, Simulation.this);
/* Dispose mote interface resources */
mote.removed();
for (MoteInterface i: mote.getInterfaces().getInterfaces()) {
i.removed();
}
setChanged();
notifyObservers(mote);
/* Loop through all scheduled events.
* Delete all events associated with deleted mote. */
TimeEvent ev = eventQueue.peekFirst();
while (ev != null) {
if (ev instanceof MoteTimeEvent) {
if (((MoteTimeEvent)ev).getMote() == mote) {
ev.remove();
}
}
ev = ev.nextEvent;
}
}
};
if (!isRunning()) {
/* Simulation is stopped, remove mote immediately */
removeMote.run();
} else {
/* Remove mote from simulation thread */
invokeSimulationThread(removeMote);
}
getCooja().closeMotePlugins(mote);
}
/**
* Called to free resources used by the simulation.
* This method is called just before the simulation is removed.
*/
public void removed() {
/* Remove radio medium */
if (currentRadioMedium != null) {
currentRadioMedium.removed();
}
/* Remove all motes */
Mote[] motes = getMotes();
for (Mote m: motes) {
removeMote(m);
}
}
/**
* Adds a mote to this simulation
*
* @param mote
* Mote to add
*/
public void addMote(final Mote mote) {
Runnable addMote = new Runnable() {
public void run() {
if (mote.getInterfaces().getClock() != null) {
if (maxMoteStartupDelay > 0) {
mote.getInterfaces().getClock().setDrift(
- getSimulationTime()
- randomGenerator.nextInt((int)maxMoteStartupDelay)
);
} else {
mote.getInterfaces().getClock().setDrift(-getSimulationTime());
}
}
motes.add(mote);
motesUninit.remove(mote);
currentRadioMedium.registerMote(mote, Simulation.this);
/* Notify mote interfaces that node was added */
for (MoteInterface i: mote.getInterfaces().getInterfaces()) {
i.added();
}
setChanged();
notifyObservers(mote);
cooja.updateGUIComponentState();
}
};
//Add to list of uninitialized motes
motesUninit.add(mote);
if (!isRunning()) {
/* Simulation is stopped, add mote immediately */
addMote.run();
} else {
/* Add mote from simulation thread */
invokeSimulationThread(addMote);
}
}
/**
* Returns simulation mote at given list position.
*
* @param pos Internal list position of mote
* @return Mote
* @see #getMotesCount()
* @see #getMoteWithID(int)
*/
public Mote getMote(int pos) {
return motes.get(pos);
}
/**
* Returns simulation with with given ID.
*
* @param id ID
* @return Mote or null
* @see Mote#getID()
*/
public Mote getMoteWithID(int id) {
for (Mote m: motes) {
if (m.getID() == id) {
return m;
}
}
return null;
}
/**
* Returns uninitialised simulation mote with with given ID.
*
* @param id ID
* @return Mote or null
* @see Mote#getID()
*/
public Mote getMoteWithIDUninit(int id) {
for (Mote m: motesUninit) {
if (m.getID() == id) {
return m;
}
}
return null;
}
/**
* Returns number of motes in this simulation.
*
* @return Number of motes
*/
public int getMotesCount() {
return motes.size();
}
/**
* Returns all motes in this simulation.
*
* @return Motes
*/
public Mote[] getMotes() {
Mote[] arr = new Mote[motes.size()];
motes.toArray(arr);
return arr;
}
/**
* Returns uninitialised motes
*
* @return Motes
*/
public Mote[] getMotesUninit() {
return motesUninit.toArray(new Mote[motesUninit.size()]);
}
/**
* Returns all mote types in simulation.
*
* @return All mote types
*/
public MoteType[] getMoteTypes() {
MoteType[] types = new MoteType[moteTypes.size()];
moteTypes.toArray(types);
return types;
}
/**
* Returns mote type with given identifier.
*
* @param identifier
* Mote type identifier
* @return Mote type or null if not found
*/
public MoteType getMoteType(String identifier) {
for (MoteType moteType : getMoteTypes()) {
if (moteType.getIdentifier().equals(identifier)) {
return moteType;
}
}
return null;
}
/**
* Adds given mote type to simulation.
*
* @param newMoteType Mote type
*/
public void addMoteType(MoteType newMoteType) {
moteTypes.add(newMoteType);
this.setChanged();
this.notifyObservers(this);
}
/**
* Remove given mote type from simulation.
*
* @param type Mote type
*/
public void removeMoteType(MoteType type) {
if (!moteTypes.contains(type)) {
logger.fatal("Mote type is not registered: " + type);
return;
}