19from __future__
import print_function
25except ModuleNotFoundError:
27 "Error: ns3 Python module not found;"
28 " Python bindings may not be enabled"
29 " or your PYTHONPATH might not be properly configured"
37 from ctypes
import c_bool, c_char_p, c_int, create_string_buffer
39 NumNodesSide = c_int(2)
42 ResultsBuffer = create_string_buffer(b
"output.xml", BUFFLEN)
43 Results = c_char_p(ResultsBuffer.raw)
45 cmd = ns.CommandLine(__file__)
48 "Grid side number of nodes (total number of nodes will be this number squared)",
51 cmd.AddValue(
"Results",
"Write XML results to file", Results, BUFFLEN)
52 cmd.AddValue(
"Plot",
"Plot the results using the matplotlib python module", Plot)
55 wifi = ns.WifiHelper()
56 wifiMac = ns.WifiMacHelper()
57 wifiPhy = ns.YansWifiPhyHelper()
58 wifiChannel = ns.YansWifiChannelHelper.Default()
59 wifiPhy.SetChannel(wifiChannel.Create())
60 ssid = ns.Ssid(
"wifi-default")
61 wifiMac.SetType(
"ns3::AdhocWifiMac",
"Ssid", ns.SsidValue(ssid))
63 internet = ns.InternetStackHelper()
64 list_routing = ns.Ipv4ListRoutingHelper()
65 olsr_routing = ns.OlsrHelper()
66 static_routing = ns.Ipv4StaticRoutingHelper()
67 list_routing.Add(static_routing, 0)
68 list_routing.Add(olsr_routing, 100)
69 internet.SetRoutingHelper(list_routing)
71 ipv4Addresses = ns.Ipv4AddressHelper()
72 ipv4Addresses.SetBase(ns.Ipv4Address(
"10.0.0.0"), ns.Ipv4Mask(
"255.255.255.0"))
75 inetAddress = ns.InetSocketAddress(ns.Ipv4Address(
"10.0.0.1"), port)
76 onOffHelper = ns.OnOffHelper(
"ns3::UdpSocketFactory", inetAddress.ConvertTo())
77 onOffHelper.SetAttribute(
"DataRate", ns.DataRateValue(ns.DataRate(
"100kbps")))
78 onOffHelper.SetAttribute(
"OnTime", ns.StringValue(
"ns3::ConstantRandomVariable[Constant=1]"))
79 onOffHelper.SetAttribute(
"OffTime", ns.StringValue(
"ns3::ConstantRandomVariable[Constant=0]"))
84 if NumNodesSide.value == 2:
85 num_nodes_side = NUM_NODES_SIDE
87 num_nodes_side = NumNodesSide.value
89 nodes = ns.NodeContainer(num_nodes_side * num_nodes_side)
91 for xi
in range(num_nodes_side):
92 for yi
in range(num_nodes_side):
93 node = nodes.Get(accumulator)
95 container = ns.NodeContainer(node)
96 internet.Install(container)
98 mobility = ns.CreateObject[ns.ConstantPositionMobilityModel]()
99 mobility.SetPosition(ns.Vector(xi * DISTANCE, yi * DISTANCE, 0))
100 node.AggregateObject(mobility)
102 device = wifi.Install(wifiPhy, wifiMac, node)
103 ipv4_interfaces = ipv4Addresses.Assign(device)
104 addresses.append(ipv4_interfaces.GetAddress(0))
106 for i, node
in [(i, nodes.Get(i))
for i
in range(nodes.GetN())]:
107 destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
109 onOffHelper.SetAttribute(
111 ns.AddressValue(ns.InetSocketAddress(destaddr, port).ConvertTo()),
113 container = ns.NodeContainer(node)
114 app = onOffHelper.Install(container)
115 urv = ns.CreateObject[ns.UniformRandomVariable]()
116 startDelay = ns.Seconds(urv.GetValue(20, 30))
117 app.Start(startDelay)
120 flowmon_helper = ns.FlowMonitorHelper()
122 monitor = flowmon_helper.InstallAll()
123 monitor = flowmon_helper.GetMonitor()
124 monitor.SetAttribute(
"DelayBinWidth", ns.DoubleValue(0.001))
125 monitor.SetAttribute(
"JitterBinWidth", ns.DoubleValue(0.001))
126 monitor.SetAttribute(
"PacketSizeBinWidth", ns.DoubleValue(20))
128 ns.Simulator.Stop(ns.Seconds(44.0))
131 def print_stats(os, st):
132 print(
" Tx Bytes: ", st.txBytes, file=os)
133 print(
" Rx Bytes: ", st.rxBytes, file=os)
134 print(
" Tx Packets: ", st.txPackets, file=os)
135 print(
" Rx Packets: ", st.rxPackets, file=os)
136 print(
" Lost Packets: ", st.lostPackets, file=os)
138 print(
" Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets), file=os)
139 print(
" Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets - 1)), file=os)
140 print(
" Mean{Hop Count}: ", float(st.timesForwarded) / st.rxPackets + 1, file=os)
143 print(
"Delay Histogram", file=os)
144 for i
in range(st.delayHistogram.GetNBins()):
149 st.delayHistogram.GetBinStart(i),
151 st.delayHistogram.GetBinEnd(i),
153 st.delayHistogram.GetBinCount(i),
156 print(
"Jitter Histogram", file=os)
157 for i
in range(st.jitterHistogram.GetNBins()):
162 st.jitterHistogram.GetBinStart(i),
164 st.jitterHistogram.GetBinEnd(i),
166 st.jitterHistogram.GetBinCount(i),
169 print(
"PacketSize Histogram", file=os)
170 for i
in range(st.packetSizeHistogram.GetNBins()):
175 st.packetSizeHistogram.GetBinStart(i),
177 st.packetSizeHistogram.GetBinEnd(i),
179 st.packetSizeHistogram.GetBinCount(i),
183 for reason, drops
in enumerate(st.packetsDropped):
184 print(
" Packets dropped by reason %i: %i" % (reason, drops), file=os)
188 monitor.CheckForLostPackets()
189 classifier = flowmon_helper.GetClassifier()
191 if Results.value != b
"output.xml":
192 for flow_id, flow_stats
in monitor.GetFlowStats():
193 t = classifier.FindFlow(flow_id)
194 proto = {6:
"TCP", 17:
"UDP"}[t.protocol]
196 "FlowID: %i (%s %s/%s --> %s/%i)"
202 t.destinationAddress,
206 print_stats(sys.stdout, flow_stats)
208 res = monitor.SerializeToXmlFile(Results.value.decode(
"utf-8"),
True,
True)
212 from matplotlib
import pyplot
as plt
215 for flow_id, flow_stats
in monitor.GetFlowStats():
216 tupl = classifier.FindFlow(flow_id)
217 if tupl.protocol == 17
and tupl.sourcePort == 698:
219 delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
221 plt.xlabel(
"Delay (s)")
222 plt.ylabel(
"Number of Flows")
228if __name__ ==
"__main__":
229 sys.exit(main(sys.argv))