-
Notifications
You must be signed in to change notification settings - Fork 5
/
orchestrator.cc
1765 lines (1496 loc) · 50.7 KB
/
orchestrator.cc
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
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* NIST-developed software is provided by NIST as a public service. You may use,
* copy and distribute copies of the software in any medium, provided that you
* keep intact this entire notice. You may improve,modify and create derivative
* works of the software or any portion of the software, and you may copy and
* distribute such modifications or works. Modified works should carry a notice
* stating that you changed the software and should note the date and nature of
* any such change. Please explicitly acknowledge the National Institute of
* Standards and Technology as the source of the software.
*
* NIST-developed software is expressly provided "AS IS." NIST MAKES NO
* WARRANTY OF ANY KIND, EXPRESS, IMPLIED, IN FACT OR ARISING BY OPERATION OF
* LAW, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST NEITHER REPRESENTS NOR WARRANTS THAT THE
* OPERATION OF THE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE, OR THAT
* ANY DEFECTS WILL BE CORRECTED. NIST DOES NOT WARRANT OR MAKE ANY
* REPRESENTATIONS REGARDING THE USE OF THE SOFTWARE OR THE RESULTS THEREOF,
* INCLUDING BUT NOT LIMITED TO THE CORRECTNESS, ACCURACY, RELIABILITY,
* OR USEFULNESS OF THE SOFTWARE.
*
* You are solely responsible for determining the appropriateness of using and
* distributing the software and you assume all risks associated with its use,
* including but not limited to the risks and costs of program errors,
* compliance with applicable laws, damage to or loss of data, programs or
* equipment, and the unavailability or interruption of operation. This
* software is not intended to be used in any situation where a failure could
* cause risk of injury or damage to property. The software developed by NIST
* employees is not subject to copyright protection within the United States.
*
* Author: Evan Black <evan.black@nist.gov>
*/
#include "orchestrator.h"
#include "building-configuration.h"
#include "color.h"
#include "log-stream.h"
#include "logical-link.h"
#include "netsimulyzer-version.h"
#include "node-configuration.h"
#include "optional.h"
#include "xy-series.h"
#include <ns3/abort.h>
#include <ns3/boolean.h>
#include <ns3/double.h>
#include <ns3/enum.h>
#include <ns3/log.h>
#include <ns3/mobility-model.h>
#include <ns3/node.h>
#include <ns3/object-base.h>
#include <ns3/point-to-point-channel.h>
#include <ns3/point-to-point-net-device.h>
#include <ns3/pointer.h>
#include <ns3/ptr.h>
#include <ns3/rectangle.h>
#include <ns3/string.h>
#include <ns3/uinteger.h>
#include <ns3/vector.h>
#include <atomic>
#include <csignal>
#include <map>
#include <string>
#include <vector>
namespace
{
#ifdef NETSIMULYZER_CRASH_HANDLER
// Weak pointers to all Orchestrators for crash handling
std::vector<ns3::netsimulyzer::Orchestrator*> orchestrators{};
volatile std::atomic_int crashCount{0};
void
netsimulyzerCrashHandler(int signal)
{
// Just incase we get a signal during this handler
if (crashCount > 0)
{
std::abort();
}
++crashCount;
// Reset signal handlers to their defaults
// so we avoid a loop this way too
//
// It is implementation defined if this happens before
// the handler is invoked anyway
std::signal(SIGSEGV, SIG_DFL);
std::signal(SIGTERM, SIG_DFL);
std::signal(SIGINT, SIG_DFL);
// if we don't have any Orchestrators registered,
// don't make noise on the console, since the module
// wasn't used
if (orchestrators.empty())
{
return;
}
switch (signal)
{
case SIGSEGV:
std::cout << "SIGSEGV ";
break;
case SIGTERM:
std::cout << "SIGTERM ";
break;
case SIGINT:
std::cout << "SIGINT ";
break;
default:
break;
}
// _Tecnically_ UB here, but there's no way to print from a signal handler
// without it
std::cout << "caught, attempting to write NetSimulyzer output file(s)\n";
for (const auto oPtr : orchestrators)
{
oPtr->Flush();
}
// allow default handler to complete exit
}
// Cheap trick to get these registered at program start
auto unusedSegvHandler [[maybe_unused]] = std::signal(SIGSEGV, netsimulyzerCrashHandler);
auto unusedTermHandler [[maybe_unused]] = std::signal(SIGTERM, netsimulyzerCrashHandler);
auto unusedIntHandler [[maybe_unused]] = std::signal(SIGINT, netsimulyzerCrashHandler);
#endif
std::string
ScaleToString(int scale)
{
switch (scale)
{
case ns3::netsimulyzer::ValueAxis::Scale::Linear:
return "linear";
case ns3::netsimulyzer::ValueAxis::Scale::Logarithmic:
return "logarithmic";
default:
NS_ABORT_MSG("Unhandled ns3::netsimulyzer::ValueAxis::Scale: " << scale);
}
}
std::string
BoundModeToString(int mode)
{
switch (mode)
{
case ns3::netsimulyzer::ValueAxis::BoundMode::Fixed:
return "fixed";
case ns3::netsimulyzer::ValueAxis::BoundMode::HighestValue:
return "highest value";
default:
NS_ABORT_MSG("Unhandled ns3::netsimulyzer::ValueAxis::BoundMode: " << mode);
}
}
nlohmann::json
colorToObject(const ns3::netsimulyzer::Color3& color)
{
nlohmann::json object;
object["red"] = color.red;
object["green"] = color.green;
object["blue"] = color.blue;
return object;
}
nlohmann::json
pointToObject(double x, double y)
{
nlohmann::json object;
object["x"] = x;
object["y"] = y;
return object;
}
nlohmann::json
makeAxisAttributes(ns3::Ptr<ns3::netsimulyzer::ValueAxis> axis)
{
nlohmann::json element;
ns3::StringValue name;
axis->GetAttribute("Name", name);
element["name"] = name.Get();
ns3::DoubleValue min;
axis->GetAttribute("Minimum", min);
element["min"] = min.Get();
ns3::DoubleValue max;
axis->GetAttribute("Maximum", max);
element["max"] = max.Get();
#ifndef NETSIMULYZER_PRE_NS3_41_ENUM_VALUE
ns3::EnumValue<ns3::netsimulyzer::ValueAxis::Scale> scaleMode;
#else
ns3::EnumValue scaleMode;
#endif
axis->GetAttribute("Scale", scaleMode);
element["scale"] = ScaleToString(scaleMode.Get());
#ifndef NETSIMULYZER_PRE_NS3_41_ENUM_VALUE
ns3::EnumValue<ns3::netsimulyzer::ValueAxis::BoundMode> boundMode;
#else
ns3::EnumValue boundMode;
#endif
axis->GetAttribute("BoundMode", boundMode);
element["bound-mode"] = BoundModeToString(boundMode.Get());
return element;
}
nlohmann::json
makeAxisAttributes(ns3::Ptr<ns3::netsimulyzer::CategoryAxis> axis)
{
nlohmann::json element;
ns3::StringValue name;
axis->GetAttribute("Name", name);
element["name"] = name.Get();
const auto& values = axis->GetValues();
auto jsonValues = nlohmann::json::array();
for (const auto& value : values)
{
auto object = nlohmann::json::object();
object["id"] = value.first;
object["value"] = value.second;
jsonValues.emplace_back(object);
}
element["values"] = jsonValues;
return element;
}
ns3::netsimulyzer::Color3
NextTrailColor(void)
{
using namespace ns3::netsimulyzer;
static auto colorIter = COLOR_PALETTE.begin();
const auto& color = colorIter->Get();
colorIter++;
if (colorIter == COLOR_PALETTE.end())
colorIter = COLOR_PALETTE.begin();
return color;
}
} // namespace
namespace ns3
{
NS_LOG_COMPONENT_DEFINE("Orchestrator");
namespace netsimulyzer
{
NS_OBJECT_ENSURE_REGISTERED(Orchestrator);
Orchestrator::Orchestrator(const std::string& output_path)
: m_outputPath(output_path)
{
NS_LOG_FUNCTION(this << output_path);
m_file.open(output_path);
NS_ABORT_MSG_IF(!m_file, "Failed to open output file");
Simulator::ScheduleNow(&Orchestrator::SetupSimulation, this);
#ifdef NETSIMULYZER_CRASH_HANDLER
orchestrators.emplace_back(this);
#endif
Init();
}
Orchestrator::Orchestrator(Orchestrator::MemoryOutputMode mode)
{
Init();
}
ns3::TypeId
Orchestrator::GetTypeId(void)
{
// clang-format off
static TypeId tid =
TypeId ("ns3::netsimulyzer::Orchestrator")
.SetParent<ns3::Object> ()
.SetGroupName ("netsimulyzer")
.AddAttribute ("TimeStep",
"Number of milliseconds a single step in the application will represent",
OptionalValue<int> (),
MakeOptionalAccessor<int> (&Orchestrator::GetTimeStepCompat,
&Orchestrator::SetTimeStepCompat),
MakeOptionalChecker<int> (),
TypeId::DEPRECATED,
"Please use `SetTimeStep()` instead")
.AddAttribute ("MobilityPollInterval", "How often to poll Nodes for their position",
TimeValue (MilliSeconds (100)),
MakeTimeAccessor (&Orchestrator::m_mobilityPollInterval),
MakeTimeChecker ())
.AddAttribute ("PollMobility", "Flag to toggle polling for Node positions",
BooleanValue (true), MakeBooleanAccessor (&Orchestrator::GetPollMobility,
&Orchestrator::SetPollMobility),
MakeBooleanChecker ())
.AddAttribute ("StartTime", "Beginning of the window to write trace information",
TimeValue (), MakeTimeAccessor (&Orchestrator::m_startTime),
MakeTimeChecker ())
.AddAttribute ("StopTime", "End of the window to write trace information", TimeValue (Time::Max()),
MakeTimeAccessor (&Orchestrator::m_stopTime), MakeTimeChecker ());
return tid;
// clang-format on
}
void
Orchestrator::SetTimeStep(Time step, Time::Unit granularity)
{
NS_LOG_FUNCTION(this << step << granularity);
NS_ABORT_MSG_IF(granularity != Time::Unit::MS && granularity != Time::Unit::US &&
granularity != Time::Unit::NS,
"'granularity' Passed to `Orchestrator::SetTimeStep` Must be either "
"`Time::Unit::MS`,'Time::Unit::US`, or `Time::Unit::NS`");
m_timeStep = step;
m_timeStepGranularity = granularity;
}
void
Orchestrator::ClearTimeStep(void)
{
NS_LOG_FUNCTION(this);
m_timeStep.reset();
m_timeStepGranularity.reset();
}
std::optional<Orchestrator::TimeStepPair>
Orchestrator::GetTimeStep() const
{
NS_LOG_FUNCTION(this);
if (m_timeStep && m_timeStepGranularity)
return TimeStepPair{m_timeStep.value(), m_timeStepGranularity.value()};
return {};
}
const nlohmann::json&
Orchestrator::GetJson() const
{
return m_document;
}
void
Orchestrator::SetupSimulation(void)
{
NS_LOG_FUNCTION(this);
// Header
auto version = nlohmann::json{};
version["major"] = VERSION_MAJOR;
version["minor"] = VERSION_MINOR;
version["patch"] = VERSION_PATCH;
version["suffix"] = VERSION_SUFFIX;
m_document["configuration"]["module-version"] = version;
if (m_timeStep && m_timeStepGranularity)
{
auto object = nlohmann::json::object();
object["increment"] = m_timeStep->GetNanoSeconds();
switch (m_timeStepGranularity.value())
{
default:
[[fallthrough]];
case Time::MS:
object["granularity"] = "milliseconds";
break;
case Time::US:
object["granularity"] = "microseconds";
break;
case Time::NS:
object["granularity"] = "nanoseconds";
break;
}
m_document["configuration"]["time-step"] = object;
}
// Nodes
std::multimap<unsigned int, unsigned int> deviceLinkMap;
auto nodes = nlohmann::json::array();
for (const auto& config : m_nodes)
{
const auto node = config->GetObject<Node>();
nlohmann::json element;
element["type"] = "node";
const auto nodeId = node->GetId();
element["id"] = nodeId;
StringValue name;
config->GetAttribute("Name", name);
if (name.Get().empty())
{
element["name"] = "Node: " + std::to_string(nodeId);
}
else
{
element["name"] = name.Get();
}
BooleanValue labelEnabled;
config->GetAttribute("EnableLabel", labelEnabled);
element["label-enabled"] = labelEnabled.Get();
StringValue model;
config->GetAttribute("Model", model);
element["model"] = model.Get();
DoubleValue scale;
config->GetAttribute("Scale", scale);
Vector3DValue scaleAxes;
config->GetAttribute("ScaleAxes", scaleAxes);
auto outputScale = nlohmann::json::object();
outputScale["x"] = scale.Get() * scaleAxes.Get().x;
outputScale["y"] = scale.Get() * scaleAxes.Get().y;
outputScale["z"] = scale.Get() * scaleAxes.Get().z;
element["scale"] = outputScale;
auto targetScale = nlohmann::json::object();
BooleanValue keepRatio;
config->GetAttribute("KeepRatio", keepRatio);
targetScale["keep-ratio"] = keepRatio.Get();
OptionalValue<double> height;
config->GetAttribute("Height", height);
if (height)
targetScale["height"] = height.GetValue();
OptionalValue<double> width;
config->GetAttribute("Width", width);
if (width)
targetScale["width"] = width.GetValue();
OptionalValue<double> depth;
config->GetAttribute("Depth", depth);
if (depth)
targetScale["depth"] = depth.GetValue();
element["target-scale"] = targetScale;
OptionalValue<Color3> baseColor;
config->GetAttribute("BaseColor", baseColor);
if (baseColor)
element["base-color"] = colorToObject(baseColor.GetValue());
OptionalValue<Color3> highlightColor;
config->GetAttribute("HighlightColor", highlightColor);
if (highlightColor)
element["highlight-color"] = colorToObject(highlightColor.GetValue());
BooleanValue trailEnabled;
config->GetAttribute("EnableMotionTrail", trailEnabled);
element["trail-enabled"] = trailEnabled.Get();
Color3 trailColor;
OptionalValue<Color3> trailColorAttr;
config->GetAttribute("MotionTrailColor", trailColorAttr);
if (trailColorAttr)
trailColor = trailColorAttr.GetValue();
else if (baseColor)
trailColor = baseColor.GetValue();
else if (highlightColor)
trailColor = highlightColor.GetValue();
else
trailColor = NextTrailColor();
element["trail-color"] = colorToObject(trailColor);
Vector3DValue orientation;
config->GetAttribute("Orientation", orientation);
element["orientation"]["x"] = orientation.Get().x;
element["orientation"]["y"] = orientation.Get().y;
element["orientation"]["z"] = orientation.Get().z;
Vector3DValue offset;
config->GetAttribute("Offset", offset);
element["offset"]["x"] = offset.Get().x;
element["offset"]["y"] = offset.Get().y;
element["offset"]["z"] = offset.Get().z;
BooleanValue visible;
config->GetAttribute("Visible", visible);
element["visible"] = visible.Get();
const auto mobility = node->GetObject<MobilityModel>();
if (mobility)
{
const auto position = mobility->GetPosition();
element["position"]["x"] = position.x;
element["position"]["y"] = position.y;
element["position"]["z"] = position.z;
}
else
{
// Without a position, we can't do much better then showing at the origin
element["position"]["x"] = 0.0;
element["position"]["y"] = 0.0;
element["position"]["z"] = 0.0;
}
// Check NetDevices for p2p links
for (auto i = 0u; i < node->GetNDevices(); i++)
{
const auto device = node->GetDevice(i);
// We only support Point-to-Point links for now
if (!device->IsPointToPoint())
continue;
auto baseChannel = device->GetChannel();
if (!baseChannel)
continue;
auto p2pChannel = DynamicCast<PointToPointChannel>(baseChannel);
if (!p2pChannel)
continue;
for (auto j = 0u; j < p2pChannel->GetNDevices(); j++)
{
auto channelNode = p2pChannel->GetDevice(j)->GetNode();
if (channelNode->GetId() == nodeId)
continue;
// Check to make sure the remote Node is configured for display
// If not, then ignore the link as we can't display it
if (channelNode->GetObject<NodeConfiguration>() == nullptr)
continue;
// Check to see if we've already written this link
// from the other devices perspective
const auto otherNodeId = channelNode->GetId();
auto otherNode = deviceLinkMap.find(otherNodeId);
// If we've already recorded the other pointing to
// this node, then there's no need to duplicate
if (otherNode != deviceLinkMap.end() && otherNode->second == nodeId)
continue;
deviceLinkMap.insert({nodeId, otherNodeId});
}
}
nodes.emplace_back(element);
}
m_document["nodes"] = nodes;
auto links = nlohmann::json::array();
for (const auto& [key, value] : deviceLinkMap)
{
nlohmann::json element;
element["type"] = "point-to-point";
auto linkNodes = nlohmann::json::array();
linkNodes.emplace_back(key);
linkNodes.emplace_back(value);
element["node-ids"] = linkNodes;
links.emplace_back(element);
}
// Links appended to in the next section
for (const auto& logicalLink : m_logicalLinks)
{
nlohmann::json element;
element["type"] = "logical";
UintegerValue id;
logicalLink->GetAttribute("Id", id);
element["id"] = id.Get();
Color3Value color;
logicalLink->GetAttribute("Color", color);
element["color"] = colorToObject(color.Get());
element["active"] = logicalLink->IsActive();
element["diameter"] = logicalLink->GetDiameter();
const auto [first, second] = logicalLink->GetNodes();
element["nodes"] = nlohmann::json::array({first, second});
links.emplace_back(element);
}
m_document["links"] = links;
// Buildings
auto buildings = nlohmann::json::array();
for (const auto& config : m_buildings)
{
const auto building = config->GetObject<Building>();
nlohmann::json element;
element["type"] = "building";
Color3Value color;
config->GetAttribute("Color", color);
element["color"] = colorToObject(color.Get());
BooleanValue visible;
config->GetAttribute("Visible", visible);
element["visible"] = visible.Get();
element["id"] = building->GetId();
element["floors"] = building->GetNFloors();
element["rooms"]["x"] = building->GetNRoomsX();
element["rooms"]["y"] = building->GetNRoomsY();
const auto& bounds = building->GetBoundaries();
element["bounds"]["x"]["min"] = bounds.xMin;
element["bounds"]["x"]["max"] = bounds.xMax;
element["bounds"]["y"]["min"] = bounds.yMin;
element["bounds"]["y"]["max"] = bounds.yMax;
element["bounds"]["z"]["min"] = bounds.zMin;
element["bounds"]["z"]["max"] = bounds.zMax;
buildings.emplace_back(element);
}
m_document["buildings"] = buildings;
// Decorations
auto decorations = nlohmann::json::array();
for (const auto& decoration : m_decorations)
{
nlohmann::json element;
element["type"] = "decoration";
UintegerValue id;
decoration->GetAttribute("Id", id);
element["id"] = id.Get();
StringValue model;
decoration->GetAttribute("Model", model);
element["model"] = model.Get();
Vector3DValue orientation;
decoration->GetAttribute("Orientation", orientation);
element["orientation"]["x"] = orientation.Get().x;
element["orientation"]["y"] = orientation.Get().y;
element["orientation"]["z"] = orientation.Get().z;
Vector3DValue position;
decoration->GetAttribute("Position", position);
element["position"]["x"] = position.Get().x;
element["position"]["y"] = position.Get().y;
element["position"]["z"] = position.Get().z;
DoubleValue scale;
decoration->GetAttribute("Scale", scale);
Vector3DValue scaleAxes;
decoration->GetAttribute("ScaleAxes", scaleAxes);
auto outputScale = nlohmann::json::object();
outputScale["x"] = scale.Get() * scaleAxes.Get().x;
outputScale["y"] = scale.Get() * scaleAxes.Get().y;
outputScale["z"] = scale.Get() * scaleAxes.Get().z;
element["scale"] = outputScale;
auto targetScale = nlohmann::json::object();
BooleanValue keepRatio;
decoration->GetAttribute("KeepRatio", keepRatio);
targetScale["keep-ratio"] = keepRatio.Get();
OptionalValue<double> height;
decoration->GetAttribute("Height", height);
if (height)
targetScale["height"] = height.GetValue();
OptionalValue<double> width;
decoration->GetAttribute("Width", width);
if (width)
targetScale["width"] = width.GetValue();
OptionalValue<double> depth;
decoration->GetAttribute("Depth", depth);
if (depth)
targetScale["depth"] = depth.GetValue();
element["target-scale"] = targetScale;
decorations.emplace_back(element);
}
m_document["decorations"] = decorations;
// Series
for (const auto& xYSeries : m_xYSeries)
{
xYSeries->Commit();
}
for (const auto& categorySeries : m_categorySeries)
{
categorySeries->Commit();
}
for (const auto& seriesCollection : m_seriesCollections)
{
seriesCollection->Commit();
}
// Streams
for (const auto& stream : m_streams)
{
stream->Commit();
}
// Areas
auto areas = nlohmann::json::array();
for (const auto& area : m_areas)
{
nlohmann::json element;
element["type"] = "rectangular-area";
UintegerValue id;
area->GetAttribute("Id", id);
element["id"] = id.Get();
StringValue name;
area->GetAttribute("Name", name);
if (name.Get().empty())
element["name"] = "Area: " + std::to_string(id.Get());
else
element["name"] = name.Get();
RectangleValue boundsValue;
area->GetAttribute("Bounds", boundsValue);
auto bounds = boundsValue.Get();
auto points = nlohmann::json::array();
// Counter clockwise order is important here
// 1 4
// |----|
// | | | ^
// V | | |
// |----|
// 2 -> 3
// Left Top (1)
points.emplace_back(pointToObject(bounds.xMin, bounds.yMax));
// Left Bottom (2)
points.emplace_back(pointToObject(bounds.xMin, bounds.yMin));
// Right Bottom (3)
points.emplace_back(pointToObject(bounds.xMax, bounds.yMin));
// Right Top (4)
points.emplace_back(pointToObject(bounds.xMax, bounds.yMax));
element["points"] = points;
DoubleValue height;
area->GetAttribute("Height", height);
element["height"] = height.Get();
#ifndef NETSIMULYZER_PRE_NS3_41_ENUM_VALUE
EnumValue<RectangularArea::DrawMode> fillMode;
#else
EnumValue fillMode;
#endif
area->GetAttribute("Fill", fillMode);
switch (fillMode.Get())
{
case RectangularArea::DrawMode::Solid:
element["fill-mode"] = "solid";
break;
case RectangularArea::DrawMode::Hidden:
element["fill-mode"] = "hidden";
break;
default:
NS_ABORT_MSG("Unhandled RectangularArea::DrawMode: " << fillMode.Get());
break;
}
#ifndef NETSIMULYZER_PRE_NS3_41_ENUM_VALUE
EnumValue<RectangularArea::DrawMode> borderMode;
#else
EnumValue borderMode;
#endif
area->GetAttribute("Border", borderMode);
switch (borderMode.Get())
{
case RectangularArea::DrawMode::Solid:
element["border-mode"] = "solid";
break;
case RectangularArea::DrawMode::Hidden:
element["border-mode"] = "hidden";
break;
default:
NS_ABORT_MSG("Unhandled RectangularArea::DrawMode: " << borderMode.Get());
break;
}
Color3Value fillColor;
area->GetAttribute("FillColor", fillColor);
element["fill-color"] = colorToObject(fillColor.Get());
Color3Value borderColor;
area->GetAttribute("BorderColor", borderColor);
element["border-color"] = colorToObject(borderColor.Get());
areas.emplace_back(element);
}
m_document["areas"] = areas;
// We're out of the initial config now
// Everything else is an event
m_currentSection = Orchestrator::Section::Events;
NS_ABORT_MSG_IF(m_startTime > m_stopTime, "StopTime must be after StartTime");
// This method should be called immediately after the simulation starts,
// so using the Start Time as the delay should be fine
if (m_pollMobility && !m_mobilityPollEvent.has_value())
m_mobilityPollEvent = Simulator::Schedule(m_startTime, &Orchestrator::PollMobility, this);
Simulator::ScheduleDestroy(&Orchestrator::Flush, this);
// Mark that simulation has begun,
// so we can begin tracking mobility
// events
m_simulationStarted = true;
}
void
Orchestrator::SetPollMobility(bool enable)
{
NS_LOG_FUNCTION(this);
m_pollMobility = enable;
if (m_pollMobility && !m_mobilityPollEvent.has_value())
{
if (Simulator::Now() > m_stopTime)
return;
else if (Simulator::Now() >= m_startTime)
m_mobilityPollEvent = Simulator::ScheduleNow(&Orchestrator::PollMobility, this);
else
m_mobilityPollEvent = Simulator::Schedule(Simulator::Now() - m_startTime,
&Orchestrator::PollMobility,
this);
}
else if (!m_pollMobility && m_mobilityPollEvent.has_value())
{
Simulator::Cancel(m_mobilityPollEvent.value());
m_mobilityPollEvent.reset();
}
}
bool
Orchestrator::GetPollMobility() const
{
NS_LOG_FUNCTION(this);
return m_pollMobility;
}
void
Orchestrator::PollMobility(void)
{
NS_LOG_FUNCTION(this);
// Stop the polling if we've passed StopTime
// StartTime addressed in scheduling
if (Simulator::Now() > m_stopTime)
{
NS_LOG_DEBUG("PollMobility() Activated past StopTime, Ignoring");
m_mobilityPollEvent.reset();
return;
}
for (const auto& config : m_nodes)
{
const auto node = config->GetObject<Node>();
auto position = config->MobilityPoll();
if (position)
WritePosition(node->GetId(), Simulator::Now(), position.value());
}
m_mobilityPollEvent =
Simulator::Schedule(m_mobilityPollInterval, &Orchestrator::PollMobility, this);
}
void
Orchestrator::WritePosition(uint32_t nodeId, Time time, Vector3D position)
{
NS_LOG_FUNCTION(this << nodeId << time << position);
nlohmann::json element;
element["type"] = "node-position";
element["nanoseconds"] = time.GetNanoSeconds();
element["id"] = nodeId;
element["x"] = position.x;
element["y"] = position.y;
element["z"] = position.z;
m_document["events"].emplace_back(element);
}
void
Orchestrator::DoDispose(void)
{
NS_LOG_FUNCTION(this);
Flush();
m_xYSeries.clear();
m_categorySeries.clear();
m_seriesCollections.clear();
m_decorations.clear();
m_nodes.clear();
m_buildings.clear();
m_streams.clear();
m_areas.clear();
Object::DoDispose();
}
void
Orchestrator::HandleCourseChange(const CourseChangeEvent& event)
{
NS_LOG_FUNCTION(this);
if (Simulator::Now() < m_startTime || Simulator::Now() > m_stopTime)
{
NS_LOG_DEBUG("HandleCourseChange() Activated outside (StartTime, StopTime), Ignoring");
return;
}
else if (!m_simulationStarted)
{
NS_LOG_DEBUG("HandleCourseChange() Activated before simulation started, Ignoring");
return;
}
WritePosition(event.nodeId, event.time, event.position);
}
void
Orchestrator::HandlePositionChange(const DecorationMoveEvent& event)
{
NS_LOG_FUNCTION(this);
if (Simulator::Now() < m_startTime || Simulator::Now() > m_stopTime)
{
NS_LOG_DEBUG("HandlePositionChange() Activated outside (StartTime, StopTime), Ignoring");
return;
}
else if (!m_simulationStarted)
{
NS_LOG_DEBUG("HandleCourseChange() Activated before simulation started, Ignoring");
return;
}
if (m_currentSection != Section::Events)
{
// We'll get the final orientation when we write the head info
NS_LOG_DEBUG("DecorationMoveEvent ignored. Not in Events section");
return;
}
nlohmann::json element;
element["type"] = "decoration-position";
element["nanoseconds"] = event.time.GetNanoSeconds();
element["id"] = event.id;
element["x"] = event.position.x;
element["y"] = event.position.y;
element["z"] = event.position.z;
m_document["events"].emplace_back(element);
}
void
Orchestrator::HandleModelChange(const NodeModelChangeEvent& event)
{
NS_LOG_FUNCTION(this);
if (Simulator::Now() < m_startTime || Simulator::Now() > m_stopTime)
{
NS_LOG_DEBUG("HandleModelChange() Activated outside (StartTime, StopTime), Ignoring");
return;
}
else if (!m_simulationStarted)
{
NS_LOG_DEBUG("HandleModelChange() Activated before simulation started, Ignoring");
return;
}
if (m_currentSection != Section::Events)