-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cc
2381 lines (2120 loc) · 73.3 KB
/
main.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
#include "ns3/core-module.h"
#include "ns3/double.h"
#include "ns3/flow-monitor.h"
#include "ns3/network-module.h"
#include "ns3/applications-module.h"
#include "ns3/mobility-module.h"
#include "ns3/config-store-module.h"
#include "ns3/internet-module.h"
#include "leach-helper.h"
#include "leach-routing-protocol.h"
#include "ns3/nstime.h"
#include "ns3/ptr.h"
#include "ns3/uinteger.h"
#include "wsn-helper.h"
#include "ns3/wifi-module.h"
#include "ns3/energy-module.h"
#include "ns3/vector.h"
#include "LeachPacket.h"
#include "ns3/udp-header.h"
#include "ns3/netanim-module.h"
#include "ns3/flow-monitor-helper.h"
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <iomanip>
using namespace ns3;
uint16_t port = 9;
uint32_t packetsGenerated = 0;
uint32_t packetsDropped = 0;
NS_LOG_COMPONENT_DEFINE ("LeachProposal");
/// Trace function for remaining energy at node.
void
RemainingEnergy (double oldValue, double remainingEnergy)
{
NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
<< "s Current remaining energy = " << remainingEnergy << "J");
}
/// Trace function for total energy consumption at node.
void
TotalEnergy (double oldValue, double totalEnergy)
{
NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
<< "s Total energy consumed by radio = " << totalEnergy << "J");
}
/// record packet counts
void
TotalPackets (uint32_t oldValue, uint32_t newValue)
{
packetsGenerated += (newValue - oldValue);
}
/// dropped packets from LeachRoutingProtocol
void
CountDroppedPkt (uint32_t oldValue, uint32_t newValue)
{
packetsDropped += (newValue - oldValue);
}
bool
cmp (struct ns3::leach::msmt a, struct ns3::leach::msmt b)
{
return (a.begin < b.begin);
}
class LeachProposal
{
public:
LeachProposal ();
~LeachProposal ();
void CaseRun (uint32_t nWifis,
uint32_t nSinks,
double totalTime,
std::string rate,
std::string phyMode,
uint32_t periodicUpdateInterval,
double dataStart,
double lambda,
bool verbose,
bool tracing,
bool netAnim);
private:
uint32_t m_nWifis;
uint32_t m_nSinks;
double m_totalTime;
std::string m_rate;
std::string m_phyMode;
uint32_t m_periodicUpdateInterval;
double m_dataStart;
uint32_t bytesTotal;
uint32_t packetsReceived;
uint32_t packetsReceivedYetExpired;
uint32_t packetsDecompressed;
Vector positions[205];
double m_lambda;
bool m_verbose;
bool m_tracing;
bool m_netAnim;
std::vector<struct ns3::leach::msmt>* m_timeline;
std::vector<Time>* m_txtime;
NodeContainer nodes;
NetDeviceContainer devices;
Ipv4InterfaceContainer interfaces;
EnergySourceContainer sources;
private:
void CreateNodes ();
void CreateDevices ();
void InstallInternetStack (std::string tr_name);
void InstallApplications ();
void SetupMobility ();
void SetupEnergyModel ();
void ReceivePacket (Ptr <Socket> );
Ptr <Socket> SetupPacketReceive (Ipv4Address, Ptr <Node> );
};
int main (int argc, char **argv)
{
uint32_t nWifis = 50;
uint32_t nSinks = 1;
double totalTime = 2.0;
std::string rate ("2048bps");
std::string phyMode ("DsssRate11Mbps");
uint32_t periodicUpdateInterval = 5;
double dataStart = 0.0;
double lambda = 1.0;
bool verbose = true;
bool tracing = true;
bool netAnim = false;
CommandLine cmd;
cmd.AddValue ("nWifis", "Number of WiFi nodes", nWifis);
cmd.AddValue ("nSinks", "Number of Base Stations", nSinks);
cmd.AddValue ("totalTime", "Total Simulation time", totalTime);
cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
cmd.AddValue ("rate", "CBR traffic rate", rate);
cmd.AddValue ("periodicUpdateInterval", "Periodic Interval Time", periodicUpdateInterval);
cmd.AddValue ("dataStart", "Time at which nodes start to transmit data", dataStart);
cmd.AddValue ("verbose", "Enable Logging", verbose);
cmd.AddValue ("tracing", "Enable PCAP and ASCII Tracing", tracing);
cmd.AddValue ("netAnim", "GUI Animation Interface", netAnim);
cmd.Parse (argc, argv);
SeedManager::SetSeed (12345);
std::cout << "Seed Set\n";
//Config::SetDefault ("ns3::leach::WsnApplication::PacketSize", UintegerValue(64));
//Config::SetDefault ("ns3::leach::WsnApplication::DataRate", DataRateValue (rate));
Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue (phyMode));
Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2000"));
//test = LeachProposal ();
LeachProposal *test = new LeachProposal;
test->CaseRun (nWifis, nSinks, totalTime, rate, phyMode, periodicUpdateInterval, dataStart, lambda, verbose, tracing, netAnim);
//delete test;
return 0;
}
LeachProposal::LeachProposal ()
: bytesTotal (0),
packetsReceived (0),
packetsReceivedYetExpired (0),
packetsDecompressed (0)
{
}
LeachProposal::~LeachProposal()
{
}
void
LeachProposal::ReceivePacket (Ptr <Socket> socket)
{
Ptr <Packet> packet;
uint32_t packetSize = 0;
uint32_t packetCount = 0;
NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << " Received one packet!");
while ((packet = socket->Recv ()))
{
leach::LeachHeader leachHeader;
bytesTotal += packet->GetSize();
packetSize += packet->GetSize();
//NS_LOG_UNCOND("packet size: " << packet->GetSize());
//packet->Print(std::cout);
while(packet->GetSize() >= 56)
{
packet->RemoveHeader(leachHeader);
packet->RemoveAtStart(16);
//NS_LOG_UNCOND(leachHeader);
if(leachHeader.GetDeadline() > Simulator::Now()) packetsDecompressed++;
else packetsReceivedYetExpired++;
packetCount++;
}
packetsReceived++;
}
NS_LOG_UNCOND ("packet size = " << packetSize << ", packetCount = " << packetCount);
NS_LOG_UNCOND ("packet size/packet count = " << packetSize/(double)packetCount);
//std::cout << "packet size = " << packetSize << ", packetCount = " << packetCount << std::endl;
//std::cout << "packet size/packet count = " << packetSize/(double)packetCount << std::endl;
}
Ptr <Socket>
LeachProposal::SetupPacketReceive (Ipv4Address addr, Ptr <Node> node)
{
TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
Ptr <Socket> sink = Socket::CreateSocket (node, tid);
InetSocketAddress local = InetSocketAddress (addr, port);
sink->Bind (local);
sink->SetRecvCallback (MakeCallback ( &LeachProposal::ReceivePacket, this));
return sink;
}
void
LeachProposal::CaseRun (uint32_t nWifis, uint32_t nSinks, double totalTime, std::string rate,
std::string phyMode, uint32_t periodicUpdateInterval, double dataStart,
double lambda, bool verbose, bool tracing, bool netAnim)
{
m_nWifis = nWifis;
m_nSinks = nSinks;
m_totalTime = totalTime;
m_rate = rate;
m_phyMode = phyMode;
m_periodicUpdateInterval = periodicUpdateInterval;
m_dataStart = dataStart;
m_lambda = lambda;
m_verbose = verbose;
m_tracing = tracing;
m_netAnim = netAnim;
std::stringstream ss;
ss << m_nWifis;
std::string t_nodes = ss.str ();
std::stringstream ss3;
ss3 << m_totalTime;
std::string sTotalTime = ss3.str ();
std::string tr_name = "Leach_Manet_" + t_nodes + "Nodes_" + sTotalTime + "SimTime";
CreateNodes ();
CreateDevices ();
SetupMobility ();
SetupEnergyModel();
InstallInternetStack (tr_name);
InstallApplications ();
std::cout << "\nStarting simulation for " << m_totalTime << " s ...\n\n";
//if (m_netAnim)
//{
std::cout << "Generating xml file for NetAnim..." << std::endl;
AnimationInterface anim ("anim/leach-animation.xml"); // Mandatory
anim.UpdateNodeDescription (nodes.Get (0), "sink"); // Optional
anim.UpdateNodeColor (nodes.Get (0), 0, 0, 255); // Optional
anim.UpdateNodeSize ( 0, 20.0, 20.0); // Optional
//anim.GetNodeEnergyFraction(nodes.Get(0)); // Optional
for (uint32_t i = 1; i < m_nWifis; ++i)
{
anim.UpdateNodeDescription (nodes.Get (i), "node"); // Optional
anim.UpdateNodeColor (nodes.Get (i), 255, 0, 0); // Optional
anim.UpdateNodeSize ( i, 5.0, 5.0); // Optional
//anim.GetNodeEnergyFraction (nodes.Get(i)); // Optional
}
anim.EnablePacketMetadata (); // Optional
anim.EnableIpv4RouteTracking ("anim/routingtable-leach.xml", Seconds (0), Seconds (5), Seconds (0.25)); //Optional
anim.EnableWifiMacCounters (Seconds (0), Seconds (50)); //Optional
anim.EnableWifiPhyCounters (Seconds (0), Seconds (50)); //Optional
std::cout << "Finished generating xml file for NetAnim.\n" << std::endl;
//}
Ptr<FlowMonitor> flowMonitor;
FlowMonitorHelper flowHelper;
flowMonitor = flowHelper.InstallAll();
Simulator::Stop (Seconds (m_totalTime));
Simulator::Run ();
flowMonitor->SerializeToXmlFile("anim/flowMonitor-leach.flowmon", true, true);
double avgIdle = 0.0, avgTx = 0.0, avgRx = 0.0;
double energyTx = 0.0, energyRx = 0.0;
#if 0
char file_name[20];
FILE* pfile, *p2file;
snprintf(file_name, 19, "timeline%d-%d", m_nWifis, (int)lambda);
pfile = fopen(file_name, "w");
snprintf(file_name, 19, "txtime%d-%d", m_nWifis, (int)lambda);
p2file = fopen(file_name, "w");
#endif
std::cout << "Total bytes received: " << bytesTotal << "\n";
std::cout << "Total packets received: " << packetsReceived << "\n"
<< "Total packets decompressed: " << packetsDecompressed << "\n"
<< "Total packets received yet expired+dropped: " << packetsReceivedYetExpired + packetsDropped << "\n"
<< "Total packets generated:" << packetsGenerated << "\n";
for (uint32_t i=0; i<m_nWifis; i++)
{
Ptr<BasicEnergySource> basicSourcePtr = DynamicCast<BasicEnergySource> (sources.Get (i));
Ptr<DeviceEnergyModel> basicRadioModelPtr = basicSourcePtr->FindDeviceEnergyModels ("ns3::WifiRadioEnergyModel").Get (0);
Ptr<WifiRadioEnergyModel> ptr = DynamicCast<WifiRadioEnergyModel> (basicRadioModelPtr);
NS_ASSERT (basicRadioModelPtr != NULL);
avgIdle += ptr->GetIdleTime().ToDouble(Time::MS);
avgTx += ptr->GetTxTime().ToDouble(Time::MS);
avgRx += ptr->GetRxTime().ToDouble(Time::MS);
energyTx += ptr->GetTxTime().ToDouble(Time::MS) * ptr->GetTxCurrentA();
energyRx += ptr->GetRxTime().ToDouble(Time::MS) * ptr->GetTxCurrentA();
//NS_LOG_UNCOND("Idle time: " << ptr->GetIdleTime() << ", Tx Time: " << ptr->GetTxTime() << ", Rx Time: " << ptr->GetRxTime());
}
std::cout << "Avg Idle time(ms): " << avgIdle/m_nWifis << "\n"
<< "Avg Tx Time(ms): " << avgTx/m_nWifis << "\n"
<< "Avg Rx Time(ms): " << avgRx/m_nWifis << "\n";
std::cout << "Avg Tx energy(mJ): " << energyTx/m_nWifis << "\n"
<< "Avg Rx energy(mJ): " << energyRx/m_nWifis << "\n";
std::cout << "\nGenerating Trace File." << std::endl;
Ptr<leach::RoutingProtocol> leachTracer = DynamicCast<leach::RoutingProtocol> ((nodes.Get(m_nWifis/2))->GetObject<Ipv4> ()->GetRoutingProtocol());
m_timeline = leachTracer->getTimeline();
m_txtime = leachTracer->getTxTime();
//std::cout << m_timeline << std::endl;
//std::cout << m_txtime << std::endl;
#if 0 //Seg Fault
sort(m_timeline->begin(), m_timeline->end(), cmp);
for (std::vector<struct ns3::leach::msmt>::iterator it=m_timeline->begin(); it!=m_timeline->end(); ++it)
{
fprintf(pfile, "%.6f, %.6f\n", it->begin.GetSeconds(), it->end.GetSeconds());
}
//sort(tx_time->begin(), tx_time->end());
for (std::vector<Time>::iterator it=m_txtime->begin(); it!=m_txtime->end(); ++it)
{
fprintf(p2file, "%.6f\n", it->GetSeconds());
}
std::cout << "Here" << std::endl;
fclose(pfile);
fclose(p2file);
#endif
Simulator::Destroy ();
}
void
LeachProposal::CreateNodes ()
{
std::cout << "Creating " << (unsigned) m_nWifis << " nodes.\n";
nodes.Create (m_nWifis);
NS_ASSERT_MSG (m_nWifis > m_nSinks, "Sinks must be less or equal to the number of nodes in network");
std::cout << "Finished creating " << (unsigned) m_nWifis << " nodes.\n";
}
void
LeachProposal::CreateDevices ()
{
std::cout << "Creating " << (unsigned) m_nWifis << " devices.\n";
WifiMacHelper wifiMac;
wifiMac.SetType ("ns3::AdhocWifiMac");
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannel;
wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
wifiChannel.AddPropagationLoss ("ns3::RangePropagationLossModel", "MaxRange", DoubleValue(1000));
wifiPhy.SetChannel (wifiChannel.Create ());
WifiHelper wifi;
if (m_verbose)
{
wifi.EnableLogComponents();
}
// TODO: Change Standard to WIFI_PHY_STANDARD_80211ah
wifi.SetStandard (WIFI_PHY_STANDARD_80211b);
wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", StringValue (m_phyMode), "ControlMode",
StringValue (m_phyMode));
devices = wifi.Install (wifiPhy, wifiMac, nodes);
if (m_tracing)
{
AsciiTraceHelper ascii;
wifiPhy.EnableAsciiAll (ascii.CreateFileStream("trace/Leach-Manet.mob"));
wifiPhy.EnablePcapAll ("trace/pcap/Leach-Manet");
}
std::cout << "Finished creating " << (unsigned) m_nWifis << " devices.\n";
}
void
LeachProposal::SetupMobility ()
{
std::cout << "Setting Mobility Model for " << (unsigned) m_nWifis << " nodes.\n";
MobilityHelper mobility;
int64_t streamIndex = 0; // used to get consistent mobility across scenarios
int nodeSpeed = 5; //m/s
int nodePause = 0;
ObjectFactory pos;
pos.SetTypeId ("ns3::RandomRectanglePositionAllocator");
pos.Set ("X", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=7500.0]"));
pos.Set ("Y", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=7500.0]"));
Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> ();
streamIndex += taPositionAlloc->AssignStreams (streamIndex);
std::stringstream ssSpeed;
ssSpeed << "ns3::UniformRandomVariable[Min=0.0|Max=" << nodeSpeed << "]";
std::stringstream ssPause;
ssPause << "ns3::ConstantRandomVariable[Constant=" << nodePause << "]";
mobility.SetMobilityModel ("ns3::RandomWaypointMobilityModel",
"Speed", StringValue (ssSpeed.str ()),
"Pause", StringValue (ssPause.str ()),
"PositionAllocator", PointerValue (taPositionAlloc));
mobility.SetPositionAllocator (taPositionAlloc);
mobility.Install (nodes);
streamIndex += mobility.AssignStreams (nodes, streamIndex);
NS_UNUSED (streamIndex); // From this point, streamIndex is unused
}
void
LeachProposal::SetupEnergyModel()
{
std::cout << "Setting Energy Model for " << (unsigned) m_nWifis << " nodes.\n";
/** Energy Model **/
/***************************************************************************/
/* energy source */
BasicEnergySourceHelper basicSourceHelper;
// configure energy source
basicSourceHelper.Set ("BasicEnergySourceInitialEnergyJ", DoubleValue (100));
// install source
/*EnergySourceContainer */sources = basicSourceHelper.Install (nodes);
/* device energy model */
WifiRadioEnergyModelHelper radioEnergyHelper;
// install device model
DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install (devices, sources);
/***************************************************************************/
for (uint32_t i=0; i<m_nWifis; i++)
{
Ptr<BasicEnergySource> basicSourcePtr = DynamicCast<BasicEnergySource> (sources.Get (i));
basicSourcePtr->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback (&RemainingEnergy));
// device energy model
Ptr<DeviceEnergyModel> basicRadioModelPtr = basicSourcePtr->FindDeviceEnergyModels ("ns3::WifiRadioEnergyModel").Get (0);
NS_ASSERT (basicRadioModelPtr != NULL);
basicRadioModelPtr->TraceConnectWithoutContext ("TotalEnergyConsumption", MakeCallback (&TotalEnergy));
}
std::cout << "Finished setting Energy Model for " << (unsigned) m_nWifis << " nodes.\n";
}
#if 1
void
LeachProposal::InstallInternetStack (std::string tr_name)
{
std::cout << "Installing Internet Stack for " << (unsigned) m_nWifis << " nodes.\n";
LeachHelper leach;
//std::cout << m_lambda << std::endl;
//leach.Set ("Lambda", DoubleValue (m_lambda));
//leach.Set ("PeriodicUpdateInterval", TimeValue (Seconds (m_periodicUpdateInterval)));
InternetStackHelper stack;
#if 1
//uint32_t count = 0;
stack.Install (nodes);
int j=0;
for (NodeContainer::Iterator i = nodes.Begin (); i != nodes.End (); ++i, ++j)
{
//leach.Set("Position", Vector4DValue(positions[count++]));
stack.SetRoutingHelper (leach); // has effect on the next Install ()
//stack.Install (*i);
Ptr<leach::RoutingProtocol> leachTracer = DynamicCast<leach::RoutingProtocol> ((*i)->GetObject<Ipv4> ()->GetRoutingProtocol());
//TODO: Fix next line
//leachTracer->TraceConnectWithoutContext ("DroppedCount", MakeCallback (&CountDroppedPkt));
if (0)
{
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> (("trace/" + tr_name + ".routes"), std::ios::out);
leach.PrintRoutingTableAt(Seconds(m_periodicUpdateInterval), *i, routingStream);
}
}
#endif
//stack.Install (nodes); // should give change to leach protocol on the position property
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.252.0");
interfaces = address.Assign (devices);
std::cout << "Finished installing Internet Stack for " << (unsigned) m_nWifis << " nodes.\n";
}
void
LeachProposal::InstallApplications ()
{
std::cout << "Installing Applications for " << (unsigned) m_nWifis << " devices.\n";
Ptr<Node> node = NodeList::GetNode (0);
Ipv4Address nodeAddress = node->GetObject<Ipv4> ()->GetAddress (1, 0).GetLocal ();
Ptr<Socket> sink = SetupPacketReceive (nodeAddress, node);
//TODO: Use WsnHelper
//WsnHelper wsn1 ("ns3::UdpSocketFactory", Address (InetSocketAddress (interfaces.GetAddress (0), port)));
OnOffHelper wsn1 ("ns3::UdpSocketFactory", Address (InetSocketAddress (interfaces.GetAddress (0), port)));
//wsn1.SetAttribute ("PktGenRate", DoubleValue(m_lambda));
//// 0 for periodic, 1 for Poisson
//wsn1.SetAttribute ("PktGenPattern", IntegerValue(0));
//wsn1.SetAttribute ("PacketDeadlineLen", IntegerValue(3000000000)); // default
//wsn1.SetAttribute ("PacketDeadlineMin", IntegerValue(5000000000)); // default
for (uint32_t clientNode = 1; clientNode <= m_nWifis - 1; clientNode++ )
{
ApplicationContainer apps1 = wsn1.Install (nodes.Get (clientNode));
Ptr<WsnApplication> wsnapp = DynamicCast<WsnApplication> (apps1.Get (0));
Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> ();
apps1.Start (Seconds (var->GetValue (m_dataStart, m_dataStart + 1)));
apps1.Stop (Seconds (m_totalTime));
//TODO: Fix next line
//wsnapp->TraceConnectWithoutContext ("PktCount", MakeCallback (&TotalPackets));
}
std::cout << "Finished installing Applications on " << (unsigned) m_nWifis << " devices.\n";
}
#endif
/*leach-packet.cc*/
/*****************************************************************************/
#if 1
//LeachHeader::LeachHeader (BooleanValue PIR, Vector position, Vector acceleration, Ipv4Address address, Time m)
leach::LeachHeader::LeachHeader (BooleanValue PIR, Vector position, Vector acceleration, Ipv4Address address, Time m) :
m_PIR (PIR),
m_position (position),
m_acceleration (acceleration),
m_address (address),
m_deadline (m)
{
}
#endif
leach::LeachHeader::~LeachHeader ()
{
}
TypeId
leach::LeachHeader::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::leach::LeachHeader")
.SetParent<Header> ()
.SetGroupName("Leach")
.AddConstructor<LeachHeader>();
return tid;
}
TypeId
leach::LeachHeader::GetInstanceTypeId () const
{
return GetTypeId ();
}
uint32_t
leach::LeachHeader::GetSerializedSize () const
{
return sizeof(m_PIR)+sizeof(m_position)+sizeof(m_acceleration)+sizeof(m_address)+sizeof(m_deadline);
}
void
leach::LeachHeader::Serialize (Buffer::Iterator i) const
{
i.Write ((const uint8_t*)&m_PIR, sizeof(m_PIR));
i.Write ((const uint8_t*)&m_acceleration, sizeof(m_acceleration));
i.Write ((const uint8_t*)&m_position, sizeof(m_position));
i.Write ((const uint8_t*)&m_address, sizeof(m_address));
i.Write ((const uint8_t*)&m_address+4, sizeof(m_address));
i.Write ((const uint8_t*)&m_deadline, sizeof(m_deadline));
}
uint32_t
leach::LeachHeader::Deserialize (Buffer::Iterator start)
{
Buffer::Iterator i = start;
i.Read ((uint8_t*)&m_PIR, sizeof(m_PIR));
i.Read ((uint8_t*)&m_position, sizeof(m_position));
i.Read ((uint8_t*)&m_acceleration, sizeof(m_acceleration));
i.Read ((uint8_t*)&m_address, sizeof(m_address));
i.ReadU32();
i.Read ((uint8_t*)&m_deadline, sizeof(m_deadline));
uint32_t dist = i.GetDistanceFrom(start);
NS_ASSERT (dist == GetSerializedSize());
return dist;
}
void
leach::LeachHeader::Print(std::ostream &os) const
{
os << " PIR: " << m_PIR
<< " Position: " << m_position
<< " Acceleration: " << m_acceleration
<< ", IP: " << m_address
<< ", Deadline:" << m_deadline
<< "\n";
}
/*leach-header.cc*/
/*****************************************************************************/
LeachHelper::~LeachHelper ()
{
}
LeachHelper::LeachHelper () : Ipv4RoutingHelper ()
{
m_agentFactory.SetTypeId ("ns3::leach::RoutingProtocol");
}
LeachHelper*
LeachHelper::Copy (void) const
{
return new LeachHelper (*this);
}
Ptr<Ipv4RoutingProtocol>
LeachHelper::Create (Ptr<Node> node) const
{
Ptr<leach::RoutingProtocol> agent = m_agentFactory.Create<leach::RoutingProtocol> ();
node->AggregateObject (agent);
return agent;
}
void
LeachHelper::Set (std::string name, const AttributeValue &v)
{
m_agentFactory.Set (name, v);
}
/*leach-routing-protocol.cc*/
/*****************************************************************************/
/// UDP Port for LEACH control traffic
const uint32_t leach::RoutingProtocol::LEACH_PORT = 269;
double max(double a, double b) {
return (a>b)?a:b;
}
TypeId
leach::RoutingProtocol::GetTypeId (void)
{
static TypeId tid = TypeId("ns3::leach::RoutingProtocol")
.SetParent<Ipv4RoutingProtocol> ()
.SetGroupName("Leach")
.AddConstructor<RoutingProtocol>()
.AddAttribute ("PeriodicUpdateInterval", "Periodic interval between exchange of full routing table among nodes.",
TimeValue (Seconds(15)),
MakeTimeAccessor(&RoutingProtocol::m_periodicUpdateInterval),
MakeTimeChecker())
.AddAttribute ("Position", "X and Y position of node",
Vector3DValue(),
MakeVectorAccessor(&RoutingProtocol::m_position),
MakeVectorChecker())
.AddAttribute ("Acceleration", "X and Y acceleration of node",
Vector3DValue(),
MakeVectorAccessor(&RoutingProtocol::m_acceleration),
MakeVectorChecker())
.AddAttribute ("PIR", "True or False for PIR sensor on node",
BooleanValue(),
MakeBooleanAccessor(&RoutingProtocol::m_PIR),
MakeBooleanChecker())
.AddAttribute ("lambda", "Average packet generation rate",
DoubleValue(1.0),
MakeDoubleAccessor(&RoutingProtocol::m_lambda),
MakeDoubleChecker<double>())
.AddTraceSource ("DroppedCount", "Total Packets dropped",
MakeTraceSourceAccessor(&RoutingProtocol::m_dropped),
"ns3::TracedValueCallback::Uint32")
;
return tid;
}
void
leach::RoutingProtocol::SetPosition(Vector pos)
{
m_position = pos;
}
Vector
leach::RoutingProtocol::GetPosition() const
{
return m_position;
}
void
leach::RoutingProtocol::SetAcceleration(Vector accel)
{
m_acceleration = accel;
}
Vector
leach::RoutingProtocol::GetAcceleration() const
{
return m_acceleration;
}
void
leach::RoutingProtocol::SetPIR(BooleanValue pir)
{
m_PIR = pir;
}
BooleanValue
leach::RoutingProtocol::GetPIR() const
{
return m_PIR;
}
#if 0
std::vector<struct msmt>*
leach::RoutingProtocol::getTimeline()
{
return &timeline;
}
#endif
std::vector<Time>*
leach::RoutingProtocol::getTxTime()
{
return &tx_time;
}
int64_t
leach::RoutingProtocol::AssignStreams(int64_t stream)
{
try
{
NS_LOG_FUNCTION(this << stream);
m_uniformRandomVariable -> SetStream(stream);
return 1;
}
catch(...)
{
NS_LOG_ERROR("Cannot AssignStreams");
return 0;
}
}
leach::RoutingProtocol::RoutingProtocol()
: Round(0),
isSink(0),
m_dropped(0),
m_lambda(4.0),
timeline(),
tx_time(),
m_routingTable(),
m_bestRoute(),
m_queue(),
m_periodicUpdateTimer(Timer::CANCEL_ON_DESTROY),
m_broadcastClusterHeadTimer (Timer::CANCEL_ON_DESTROY),
m_respondToClusterHeadTimer (Timer::CANCEL_ON_DESTROY)
{
m_uniformRandomVariable = CreateObject<UniformRandomVariable> ();
for (int i = 0; i < 1021; i++) m_hash[i] = NULL;
}
leach::RoutingProtocol::~RoutingProtocol()
{
}
void
leach::RoutingProtocol::DoDispose()
{
m_ipv4 = 0;
for (std::map<Ptr<Socket>, Ipv4InterfaceAddress>::iterator iter = m_socketAddress.begin();
iter != m_socketAddress.end(); iter++)
{
iter->first->Close();
}
m_socketAddress.clear();
Ipv4RoutingProtocol::DoDispose();
}
void
leach::RoutingProtocol::PrintRoutingTable(Ptr<OutputStreamWrapper> stream,Time::Unit unit) const
{
*stream->GetStream() << "Node: " << m_ipv4->GetObject<Node> ()->GetId() << ", "
<< "Time: " << Now().As(unit) << ", "
<< "Local Time" << GetObject<Node>()->GetLocalTime().As(unit) << ", "
<< "LEACH Routing Table" << std::endl;
m_routingTable.Print(stream);
*stream->GetStream() << std::endl;
}
void
leach::RoutingProtocol::Start ()
{
m_selfCallback = MakeCallback(&RoutingProtocol::Send, this);
m_errorCallback = MakeCallback(&RoutingProtocol::Drop, this);
m_sinkAddress = Ipv4Address ("10.1.1.1");
ns3::PacketMetadata::Enable();
ns3::Packet::EnablePrinting();
if (m_mainAddress == m_sinkAddress)
{
isSink = 1;
}
else
{
Round = 0;
m_routingTable.SetHoldDownTime (Time (m_periodicUpdateInterval));
m_periodicUpdateTimer.SetFunction (&RoutingProtocol::PeriodicUpdate, this);
m_broadcastClusterHeadTimer.SetFunction (&RoutingProtocol::SendBroadcast, this);
m_respondToClusterHeadTimer.SetFunction (&RoutingProtocol::RespondToClusterHead, this);
m_periodicUpdateTimer.Schedule (MicroSeconds (m_uniformRandomVariable->GetInteger(10,1000)));
}
}
Ptr<Ipv4Route>
leach::RoutingProtocol::LoopbackRoute(const Ipv4Header &header, Ptr<NetDevice> oif) const
{
NS_ASSERT (m_lo != 0);
Ptr<Ipv4Route> route = Create<Ipv4Route> ();
route->SetDestination(header.GetDestination());
std::map<Ptr<Socket>, Ipv4InterfaceAddress>::const_iterator j = m_socketAddress.begin();
if (oif)
{
// Iterate to find addressof oif device
for (j = m_socketAddress.begin(); j != m_socketAddress.end(); ++j)
{
Ipv4Address addr = j->second.GetLocal();
int32_t interface = m_ipv4->GetInterfaceForAddress(addr);
if (oif == m_ipv4->GetNetDevice(static_cast<uint32_t>(interface)))
{
route->SetSource(addr);
break;
}
}
}
else
{
route->SetSource(j->second.GetLocal());
}
NS_ASSERT_MSG(route->GetSource() != Ipv4Address(), "Valid Leach source address not found");
route->SetGateway(Ipv4Address("127.0.0.1"));
route->SetOutputDevice(m_lo);
return route;
}
bool
leach::RoutingProtocol::RouteInput(Ptr<const Packet> p, const Ipv4Header &header, Ptr<const NetDevice> idev, UnicastForwardCallback ucb, MulticastForwardCallback mcb, LocalDeliverCallback lcb, ErrorCallback ecb)
{
NS_LOG_FUNCTION(m_mainAddress << " received packet " << p->GetUid ()
<< " from " << header.GetSource ()
<< " on interface " << idev->GetAddress ()
<< " to destination " << header.GetDestination ());
if (m_socketAddress.empty())
{
NS_LOG_DEBUG("No Leach Interface");
return false;
}
NS_ASSERT (m_ipv4 != 0);
// Check if input device supports IPv4
NS_ASSERT (m_ipv4->GetInterfaceForDevice(idev) >= 0);
int32_t iif = m_ipv4->GetInterfaceForDevice(idev);
Ipv4Address dst = header.GetDestination();
Ipv4Address origin = header.GetSource();
// LEACH implementation is unicast
if (dst.IsMulticast())
{
NS_LOG_ERROR("ERROR: Multicast destination found. Leach Implementation is not multicast.");
return false;
}
// Deferred route request
if (idev == m_lo)
{
NS_LOG_DEBUG("Loopback Route");
#ifdef DA
Ptr<Packet> pa = new Packet(*p);
EnqueuePacket (pa, header);
return false;
#else
RoutingTableEntry toDst;
NS_LOG_DEBUG("Deferred: " << dst);
if (m_routingTable.LookupRoute(dst, toDst))
{
Ptr<Ipv4Route> route = toDst.GetRoute();
NS_LOG_DEBUG("Deferred forwarding");
NS_LOG_DEBUG("Src: " << route->GetSource() << ", Dst: " << toDst.GetDestination() << ", Gateway: " << toDst.GetNextHop());
ucb(route, p, header);
}
else
{
NS_LOG_DEBUG("Route not found");
Ptr<Ipv4Route> route = Create<Ipv4Route> ();
route->SetDestination(dst);
route->SetSource(origin);
route->SetGateway(Ipv4Address ("127.0.0.1"));
route->SetOutputDevice(m_lo);
EnqueueForNoDA(ucb, route, p, header);
}
return true;
#endif
}
for (std::map<Ptr<Socket>, Ipv4InterfaceAddress>::const_iterator j = m_socketAddress.begin();
j != m_socketAddress.end(); ++j)
{
Ipv4InterfaceAddress iface = j->second;
if (origin == iface.GetLocal())
{
return true;
}
}
// Local Delivery to each leach interface
for (std::map<Ptr<Socket>, Ipv4InterfaceAddress>::const_iterator j = m_socketAddress.begin();
j != m_socketAddress.end(); ++j)
{
Ipv4InterfaceAddress iface = j->second;
if (m_ipv4->GetInterfaceForAddress(iface.GetLocal()) == iif)
{
// Ignore Broadcast
if (dst == iface.GetBroadcast() || dst.IsBroadcast())
{
Ptr<Packet> packet = p->Copy();
if (lcb.IsNull())
{
NS_LOG_ERROR ("Unable to deliver packet locally due to null callback " << p->GetUid () << " from " << origin);
ecb (p, header, Socket::ERROR_NOROUTETOHOST);
}
else
{
NS_LOG_LOGIC ("Broadcast local delivery to " << iface.GetLocal ());
lcb (p, header, iif);
}
if (header.GetTtl() > 1)
{
NS_LOG_LOGIC("Forwarding Broadcast. TTL " << (uint16_t) header.GetTtl());
RoutingTableEntry toBroadcast;
if (m_routingTable.LookupRoute(dst, toBroadcast, true))
{
Ptr<Ipv4Route> route = toBroadcast.GetRoute();
ucb (route, packet, header);
}
else
{
NS_LOG_DEBUG("No route to forward. Drop Packet " << p->GetUid());
}
}
return true;
}
}
}
// This means arrival
if (m_ipv4->IsDestinationAddress(dst, iif))
{
if (lcb.IsNull())
{
NS_LOG_ERROR ("Unable to deliver packet locally due to null callback " << p->GetUid () << " from " << origin);
ecb (p, header, Socket::ERROR_NOROUTETOHOST);
}
else
{
NS_LOG_LOGIC ("Unicast local delivery to " << dst);
lcb (p, header, iif);
}
return true;
}
// Check if input device supports IPv4 forwarding
if (!m_ipv4->IsForwarding(iif))
{
NS_LOG_LOGIC("Forwarding Disabled for this interface.");
ecb (p, header, Socket::ERROR_NOROUTETOHOST);
return true;
}
// Enqueue, not send