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# This program is free software; you can redistribute it and/or modify
5# it under the terms of the GNU General Public License version 2 as
6# published by the Free Software Foundation;
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program; if not, write to the Free Software
15# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16#
17# Authors: Gustavo Carneiro <gjc@inescporto.pt>
18
19from __future__ import print_function
20
21import sys
22
23try:
24 from ns import ns
25except ModuleNotFoundError:
26 raise SystemExit(
27 "Error: ns3 Python module not found;"
28 " Python bindings may not be enabled"
29 " or your PYTHONPATH might not be properly configured"
30 )
31
32DISTANCE = 20 # (m)
33NUM_NODES_SIDE = 3
34
35
36def main(argv):
37 from ctypes import c_bool, c_char_p, c_int, create_string_buffer
38
39 NumNodesSide = c_int(2)
40 Plot = c_bool(False)
41 BUFFLEN = 4096
42 ResultsBuffer = create_string_buffer(b"output.xml", BUFFLEN)
43 Results = c_char_p(ResultsBuffer.raw)
44
45 cmd = ns.CommandLine(__file__)
46 cmd.AddValue(
47 "NumNodesSide",
48 "Grid side number of nodes (total number of nodes will be this number squared)",
49 NumNodesSide,
50 )
51 cmd.AddValue("Results", "Write XML results to file", Results, BUFFLEN)
52 cmd.AddValue("Plot", "Plot the results using the matplotlib python module", Plot)
53 cmd.Parse(argv)
54
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))
62
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)
70
71 ipv4Addresses = ns.Ipv4AddressHelper()
72 ipv4Addresses.SetBase(ns.Ipv4Address("10.0.0.0"), ns.Ipv4Mask("255.255.255.0"))
73
74 port = 9 # Discard port(RFC 863)
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]"))
80
81 addresses = []
82 nodes = []
83
84 if NumNodesSide.value == 2:
85 num_nodes_side = NUM_NODES_SIDE
86 else:
87 num_nodes_side = NumNodesSide.value
88
89 nodes = ns.NodeContainer(num_nodes_side * num_nodes_side)
90 accumulator = 0
91 for xi in range(num_nodes_side):
92 for yi in range(num_nodes_side):
93 node = nodes.Get(accumulator)
94 accumulator += 1
95 container = ns.NodeContainer(node)
96 internet.Install(container)
97
98 mobility = ns.CreateObject[ns.ConstantPositionMobilityModel]()
99 mobility.SetPosition(ns.Vector(xi * DISTANCE, yi * DISTANCE, 0))
100 node.AggregateObject(mobility)
101
102 device = wifi.Install(wifiPhy, wifiMac, node)
103 ipv4_interfaces = ipv4Addresses.Assign(device)
104 addresses.append(ipv4_interfaces.GetAddress(0))
105
106 for i, node in [(i, nodes.Get(i)) for i in range(nodes.GetN())]:
107 destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
108 # print (i, destaddr)
109 onOffHelper.SetAttribute(
110 "Remote",
111 ns.AddressValue(ns.InetSocketAddress(destaddr, port).ConvertTo()),
112 )
113 container = ns.NodeContainer(node)
114 app = onOffHelper.Install(container)
115 urv = ns.CreateObject[ns.UniformRandomVariable]() # ns.cppyy.gbl.get_rng()
116 startDelay = ns.Seconds(urv.GetValue(20, 30))
117 app.Start(startDelay)
118
119 # internet.EnablePcapAll("wifi-olsr")
120 flowmon_helper = ns.FlowMonitorHelper()
121 # flowmon_helper.SetMonitorAttribute("StartTime", ns.TimeValue(ns.Seconds(31)))
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))
127
128 ns.Simulator.Stop(ns.Seconds(44.0))
129 ns.Simulator.Run()
130
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)
137 if st.rxPackets > 0:
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)
141
142 if 0:
143 print("Delay Histogram", file=os)
144 for i in range(st.delayHistogram.GetNBins()):
145 print(
146 " ",
147 i,
148 "(",
149 st.delayHistogram.GetBinStart(i),
150 "-",
151 st.delayHistogram.GetBinEnd(i),
152 "): ",
153 st.delayHistogram.GetBinCount(i),
154 file=os,
155 )
156 print("Jitter Histogram", file=os)
157 for i in range(st.jitterHistogram.GetNBins()):
158 print(
159 " ",
160 i,
161 "(",
162 st.jitterHistogram.GetBinStart(i),
163 "-",
164 st.jitterHistogram.GetBinEnd(i),
165 "): ",
166 st.jitterHistogram.GetBinCount(i),
167 file=os,
168 )
169 print("PacketSize Histogram", file=os)
170 for i in range(st.packetSizeHistogram.GetNBins()):
171 print(
172 " ",
173 i,
174 "(",
175 st.packetSizeHistogram.GetBinStart(i),
176 "-",
177 st.packetSizeHistogram.GetBinEnd(i),
178 "): ",
179 st.packetSizeHistogram.GetBinCount(i),
180 file=os,
181 )
182
183 for reason, drops in enumerate(st.packetsDropped):
184 print(" Packets dropped by reason %i: %i" % (reason, drops), file=os)
185 # for reason, drops in enumerate(st.bytesDropped):
186 # print "Bytes dropped by reason %i: %i" % (reason, drops)
187
188 monitor.CheckForLostPackets()
189 classifier = flowmon_helper.GetClassifier()
190
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]
195 print(
196 "FlowID: %i (%s %s/%s --> %s/%i)"
197 % (
198 flow_id,
199 proto,
200 t.sourceAddress,
201 t.sourcePort,
202 t.destinationAddress,
203 t.destinationPort,
204 )
205 )
206 print_stats(sys.stdout, flow_stats)
207 else:
208 res = monitor.SerializeToXmlFile(Results.value.decode("utf-8"), True, True)
209 print(res)
210
211 if Plot.value:
212 from matplotlib import pyplot as plt
213
214 delays = []
215 for flow_id, flow_stats in monitor.GetFlowStats():
216 tupl = classifier.FindFlow(flow_id)
217 if tupl.protocol == 17 and tupl.sourcePort == 698:
218 continue
219 delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
220 plt.hist(delays, 20)
221 plt.xlabel("Delay (s)")
222 plt.ylabel("Number of Flows")
223 plt.show()
224
225 return 0
226
227
228if __name__ == "__main__":
229 sys.exit(main(sys.argv))