A Discrete-Event Network Simulator
QKDNetSim v2.0 (NS-3 v3.41) @ (+)
API
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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 
19 from __future__ import print_function
20 
21 import sys
22 
23 try:
24  from ns import ns
25 except 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 
32 DISTANCE = 20 # (m)
33 NUM_NODES_SIDE = 3
34 
35 
36 def 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.CreateObject("WifiHelper")
56  wifiMac = ns.CreateObject("WifiMacHelper")
57  wifiPhy = ns.CreateObject("YansWifiPhyHelper")
58  wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
59  wifiPhy.SetChannel(wifiChannel.Create())
60  ssid = ns.wifi.Ssid("wifi-default")
61  wifiMac.SetType("ns3::AdhocWifiMac", "Ssid", ns.wifi.SsidValue(ssid))
62 
63  internet = ns.internet.InternetStackHelper()
64  list_routing = ns.internet.Ipv4ListRoutingHelper()
65  olsr_routing = ns.olsr.OlsrHelper()
66  static_routing = ns.internet.Ipv4StaticRoutingHelper()
67  list_routing.Add(static_routing, 0)
68  list_routing.Add(olsr_routing, 100)
69  internet.SetRoutingHelper(list_routing)
70 
71  ipv4Addresses = ns.internet.Ipv4AddressHelper()
72  ipv4Addresses.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0"))
73 
74  port = 9 # Discard port(RFC 863)
75  inetAddress = ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"), port)
76  onOffHelper = ns.applications.OnOffHelper("ns3::UdpSocketFactory", inetAddress.ConvertTo())
77  onOffHelper.SetAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps")))
78  onOffHelper.SetAttribute(
79  "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")
80  )
81  onOffHelper.SetAttribute(
82  "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")
83  )
84 
85  addresses = []
86  nodes = []
87 
88  if NumNodesSide.value == 2:
89  num_nodes_side = NUM_NODES_SIDE
90  else:
91  num_nodes_side = NumNodesSide.value
92 
93  nodes = ns.NodeContainer(num_nodes_side * num_nodes_side)
94  accumulator = 0
95  for xi in range(num_nodes_side):
96  for yi in range(num_nodes_side):
97  node = nodes.Get(accumulator)
98  accumulator += 1
99  container = ns.network.NodeContainer(node)
100  internet.Install(container)
101 
102  mobility = ns.CreateObject("ConstantPositionMobilityModel")
103  mobility.SetPosition(ns.core.Vector(xi * DISTANCE, yi * DISTANCE, 0))
104  node.AggregateObject(mobility)
105 
106  device = wifi.Install(wifiPhy, wifiMac, node)
107  ipv4_interfaces = ipv4Addresses.Assign(device)
108  addresses.append(ipv4_interfaces.GetAddress(0))
109 
110  for i, node in [(i, nodes.Get(i)) for i in range(nodes.GetN())]:
111  destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
112  # print (i, destaddr)
113  onOffHelper.SetAttribute(
114  "Remote",
115  ns.network.AddressValue(ns.network.InetSocketAddress(destaddr, port).ConvertTo()),
116  )
117  container = ns.network.NodeContainer(node)
118  app = onOffHelper.Install(container)
119  urv = ns.CreateObject("UniformRandomVariable") # ns.cppyy.gbl.get_rng()
120  startDelay = ns.Seconds(urv.GetValue(20, 30))
121  app.Start(startDelay)
122 
123  # internet.EnablePcapAll("wifi-olsr")
124  flowmon_helper = ns.flow_monitor.FlowMonitorHelper()
125  # flowmon_helper.SetMonitorAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(31)))
126  monitor = flowmon_helper.InstallAll()
127  monitor = flowmon_helper.GetMonitor()
128  monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001))
129  monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001))
130  monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20))
131 
132  ns.core.Simulator.Stop(ns.core.Seconds(44.0))
133  ns.core.Simulator.Run()
134 
135  def print_stats(os, st):
136  print(" Tx Bytes: ", st.txBytes, file=os)
137  print(" Rx Bytes: ", st.rxBytes, file=os)
138  print(" Tx Packets: ", st.txPackets, file=os)
139  print(" Rx Packets: ", st.rxPackets, file=os)
140  print(" Lost Packets: ", st.lostPackets, file=os)
141  if st.rxPackets > 0:
142  print(" Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets), file=os)
143  print(" Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets - 1)), file=os)
144  print(" Mean{Hop Count}: ", float(st.timesForwarded) / st.rxPackets + 1, file=os)
145 
146  if 0:
147  print("Delay Histogram", file=os)
148  for i in range(st.delayHistogram.GetNBins()):
149  print(
150  " ",
151  i,
152  "(",
153  st.delayHistogram.GetBinStart(i),
154  "-",
155  st.delayHistogram.GetBinEnd(i),
156  "): ",
157  st.delayHistogram.GetBinCount(i),
158  file=os,
159  )
160  print("Jitter Histogram", file=os)
161  for i in range(st.jitterHistogram.GetNBins()):
162  print(
163  " ",
164  i,
165  "(",
166  st.jitterHistogram.GetBinStart(i),
167  "-",
168  st.jitterHistogram.GetBinEnd(i),
169  "): ",
170  st.jitterHistogram.GetBinCount(i),
171  file=os,
172  )
173  print("PacketSize Histogram", file=os)
174  for i in range(st.packetSizeHistogram.GetNBins()):
175  print(
176  " ",
177  i,
178  "(",
179  st.packetSizeHistogram.GetBinStart(i),
180  "-",
181  st.packetSizeHistogram.GetBinEnd(i),
182  "): ",
183  st.packetSizeHistogram.GetBinCount(i),
184  file=os,
185  )
186 
187  for reason, drops in enumerate(st.packetsDropped):
188  print(" Packets dropped by reason %i: %i" % (reason, drops), file=os)
189  # for reason, drops in enumerate(st.bytesDropped):
190  # print "Bytes dropped by reason %i: %i" % (reason, drops)
191 
192  monitor.CheckForLostPackets()
193  classifier = flowmon_helper.GetClassifier()
194 
195  if Results.value != b"output.xml":
196  for flow_id, flow_stats in monitor.GetFlowStats():
197  t = classifier.FindFlow(flow_id)
198  proto = {6: "TCP", 17: "UDP"}[t.protocol]
199  print(
200  "FlowID: %i (%s %s/%s --> %s/%i)"
201  % (
202  flow_id,
203  proto,
204  t.sourceAddress,
205  t.sourcePort,
206  t.destinationAddress,
207  t.destinationPort,
208  )
209  )
210  print_stats(sys.stdout, flow_stats)
211  else:
212  res = monitor.SerializeToXmlFile(Results.value.decode("utf-8"), True, True)
213  print(res)
214 
215  if Plot.value:
216  import pylab
217 
218  delays = []
219  for flow_id, flow_stats in monitor.GetFlowStats():
220  tupl = classifier.FindFlow(flow_id)
221  if tupl.protocol == 17 and tupl.sourcePort == 698:
222  continue
223  delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
224  pylab.hist(delays, 20)
225  pylab.xlabel("Delay (s)")
226  pylab.ylabel("Number of Flows")
227  pylab.show()
228 
229  return 0
230 
231 
232 if __name__ == "__main__":
233  sys.exit(main(sys.argv))