A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
wifi-olsr-flowmon.py
Go to the documentation of this file.
1# -*- Mode: Python; -*-
2# Copyright (c) 2009 INESC Porto
3#
4# SPDX-License-Identifier: GPL-2.0-only
5#
6# Authors: Gustavo Carneiro <gjc@inescporto.pt>
7
8from __future__ import print_function
9
10import sys
11
12try:
13 from ns import ns
14except ModuleNotFoundError:
15 raise SystemExit(
16 "Error: ns3 Python module not found;"
17 " Python bindings may not be enabled"
18 " or your PYTHONPATH might not be properly configured"
19 )
20
21DISTANCE = 20 # (m)
22NUM_NODES_SIDE = 3
23
24
25def main(argv):
26 from ctypes import c_bool, c_char_p, c_int, create_string_buffer
27
28 NumNodesSide = c_int(2)
29 Plot = c_bool(False)
30 BUFFLEN = 4096
31 ResultsBuffer = create_string_buffer(b"output.xml", BUFFLEN)
32 Results = c_char_p(ResultsBuffer.raw)
33
34 cmd = ns.CommandLine(__file__)
35 cmd.AddValue(
36 "NumNodesSide",
37 "Grid side number of nodes (total number of nodes will be this number squared)",
38 NumNodesSide,
39 )
40 cmd.AddValue("Results", "Write XML results to file", Results, BUFFLEN)
41 cmd.AddValue("Plot", "Plot the results using the matplotlib python module", Plot)
42 cmd.Parse(argv)
43
44 wifi = ns.WifiHelper()
45 wifiMac = ns.WifiMacHelper()
46 wifiPhy = ns.YansWifiPhyHelper()
47 wifiChannel = ns.YansWifiChannelHelper.Default()
48 wifiPhy.SetChannel(wifiChannel.Create())
49 ssid = ns.Ssid("wifi-default")
50 wifiMac.SetType("ns3::AdhocWifiMac", "Ssid", ns.SsidValue(ssid))
51
52 internet = ns.InternetStackHelper()
53 list_routing = ns.Ipv4ListRoutingHelper()
54 olsr_routing = ns.OlsrHelper()
55 static_routing = ns.Ipv4StaticRoutingHelper()
56 list_routing.Add(static_routing, 0)
57 list_routing.Add(olsr_routing, 100)
58 internet.SetRoutingHelper(list_routing)
59
60 ipv4Addresses = ns.Ipv4AddressHelper()
61 ipv4Addresses.SetBase(ns.Ipv4Address("10.0.0.0"), ns.Ipv4Mask("255.255.255.0"))
62
63 port = 9 # Discard port(RFC 863)
64 inetAddress = ns.InetSocketAddress(ns.Ipv4Address("10.0.0.1"), port)
65 onOffHelper = ns.OnOffHelper("ns3::UdpSocketFactory", inetAddress.ConvertTo())
66 onOffHelper.SetAttribute("DataRate", ns.DataRateValue(ns.DataRate("100kbps")))
67 onOffHelper.SetAttribute("OnTime", ns.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
68 onOffHelper.SetAttribute("OffTime", ns.StringValue("ns3::ConstantRandomVariable[Constant=0]"))
69
70 addresses = []
71 nodes = []
72
73 if NumNodesSide.value == 2:
74 num_nodes_side = NUM_NODES_SIDE
75 else:
76 num_nodes_side = NumNodesSide.value
77
78 nodes = ns.NodeContainer(num_nodes_side * num_nodes_side)
79 accumulator = 0
80 for xi in range(num_nodes_side):
81 for yi in range(num_nodes_side):
82 node = nodes.Get(accumulator)
83 accumulator += 1
84 container = ns.NodeContainer(node)
85 internet.Install(container)
86
87 mobility = ns.CreateObject[ns.ConstantPositionMobilityModel]()
88 mobility.SetPosition(ns.Vector(xi * DISTANCE, yi * DISTANCE, 0))
89 node.AggregateObject(mobility)
90
91 device = wifi.Install(wifiPhy, wifiMac, node)
92 ipv4_interfaces = ipv4Addresses.Assign(device)
93 addresses.append(ipv4_interfaces.GetAddress(0))
94
95 for i, node in [(i, nodes.Get(i)) for i in range(nodes.GetN())]:
96 destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
97 # print (i, destaddr)
98 onOffHelper.SetAttribute(
99 "Remote",
100 ns.AddressValue(ns.InetSocketAddress(destaddr, port).ConvertTo()),
101 )
102 container = ns.NodeContainer(node)
103 app = onOffHelper.Install(container)
104 urv = ns.CreateObject[ns.UniformRandomVariable]() # ns.cppyy.gbl.get_rng()
105 startDelay = ns.Seconds(urv.GetValue(20, 30))
106 app.Start(startDelay)
107
108 # internet.EnablePcapAll("wifi-olsr")
109 flowmon_helper = ns.FlowMonitorHelper()
110 # flowmon_helper.SetMonitorAttribute("StartTime", ns.TimeValue(ns.Seconds(31)))
111 monitor = flowmon_helper.InstallAll()
112 monitor = flowmon_helper.GetMonitor()
113 monitor.SetAttribute("DelayBinWidth", ns.DoubleValue(0.001))
114 monitor.SetAttribute("JitterBinWidth", ns.DoubleValue(0.001))
115 monitor.SetAttribute("PacketSizeBinWidth", ns.DoubleValue(20))
116
117 ns.Simulator.Stop(ns.Seconds(44.0))
118 ns.Simulator.Run()
119
120 def print_stats(os, st):
121 print(" Tx Bytes: ", st.txBytes, file=os)
122 print(" Rx Bytes: ", st.rxBytes, file=os)
123 print(" Tx Packets: ", st.txPackets, file=os)
124 print(" Rx Packets: ", st.rxPackets, file=os)
125 print(" Lost Packets: ", st.lostPackets, file=os)
126 if st.rxPackets > 0:
127 print(" Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets), file=os)
128 print(" Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets - 1)), file=os)
129 print(" Mean{Hop Count}: ", float(st.timesForwarded) / st.rxPackets + 1, file=os)
130
131 if 0:
132 print("Delay Histogram", file=os)
133 for i in range(st.delayHistogram.GetNBins()):
134 print(
135 " ",
136 i,
137 "(",
138 st.delayHistogram.GetBinStart(i),
139 "-",
140 st.delayHistogram.GetBinEnd(i),
141 "): ",
142 st.delayHistogram.GetBinCount(i),
143 file=os,
144 )
145 print("Jitter Histogram", file=os)
146 for i in range(st.jitterHistogram.GetNBins()):
147 print(
148 " ",
149 i,
150 "(",
151 st.jitterHistogram.GetBinStart(i),
152 "-",
153 st.jitterHistogram.GetBinEnd(i),
154 "): ",
155 st.jitterHistogram.GetBinCount(i),
156 file=os,
157 )
158 print("PacketSize Histogram", file=os)
159 for i in range(st.packetSizeHistogram.GetNBins()):
160 print(
161 " ",
162 i,
163 "(",
164 st.packetSizeHistogram.GetBinStart(i),
165 "-",
166 st.packetSizeHistogram.GetBinEnd(i),
167 "): ",
168 st.packetSizeHistogram.GetBinCount(i),
169 file=os,
170 )
171
172 for reason, drops in enumerate(st.packetsDropped):
173 print(" Packets dropped by reason %i: %i" % (reason, drops), file=os)
174 # for reason, drops in enumerate(st.bytesDropped):
175 # print "Bytes dropped by reason %i: %i" % (reason, drops)
176
177 monitor.CheckForLostPackets()
178 classifier = flowmon_helper.GetClassifier()
179
180 if Results.value != b"output.xml":
181 for flow_id, flow_stats in monitor.GetFlowStats():
182 t = classifier.FindFlow(flow_id)
183 proto = {6: "TCP", 17: "UDP"}[t.protocol]
184 print(
185 "FlowID: %i (%s %s/%s --> %s/%i)"
186 % (
187 flow_id,
188 proto,
189 t.sourceAddress,
190 t.sourcePort,
191 t.destinationAddress,
192 t.destinationPort,
193 )
194 )
195 print_stats(sys.stdout, flow_stats)
196 else:
197 res = monitor.SerializeToXmlFile(Results.value.decode("utf-8"), True, True)
198 print(res)
199
200 if Plot.value:
201 from matplotlib import pyplot as plt
202
203 delays = []
204 for flow_id, flow_stats in monitor.GetFlowStats():
205 tupl = classifier.FindFlow(flow_id)
206 if tupl.protocol == 17 and tupl.sourcePort == 698:
207 continue
208 delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
209 plt.hist(delays, 20)
210 plt.xlabel("Delay (s)")
211 plt.ylabel("Number of Flows")
212 plt.show()
213
214 return 0
215
216
217if __name__ == "__main__":
218 sys.exit(main(sys.argv))