A Discrete-Event Network Simulator
API
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 import sys
21 
22 from ns import ns
23 
24 DISTANCE = 20 # (m)
25 NUM_NODES_SIDE = 3
26 
27 
28 def main(argv):
29 
30  from ctypes import c_int, c_bool, c_char_p, create_string_buffer
31  NumNodesSide = c_int(2)
32  Plot = c_bool(False)
33  BUFFLEN = 4096
34  ResultsBuffer = create_string_buffer(b"output.xml", BUFFLEN)
35  Results = c_char_p(ResultsBuffer.raw)
36 
37  cmd = ns.CommandLine(__file__)
38  cmd.AddValue("NumNodesSide", "Grid side number of nodes (total number of nodes will be this number squared)", NumNodesSide)
39  cmd.AddValue("Results", "Write XML results to file", Results, BUFFLEN)
40  cmd.AddValue("Plot", "Plot the results using the matplotlib python module", Plot)
41  cmd.Parse(argv)
42 
43  wifi = ns.CreateObject("WifiHelper")
44  wifiMac = ns.CreateObject("WifiMacHelper")
45  wifiPhy = ns.CreateObject("YansWifiPhyHelper")
46  wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
47  wifiPhy.SetChannel(wifiChannel.Create())
48  ssid = ns.wifi.Ssid("wifi-default")
49  wifiMac.SetType ("ns3::AdhocWifiMac",
50  "Ssid", ns.wifi.SsidValue(ssid))
51 
52  internet = ns.internet.InternetStackHelper()
53  list_routing = ns.internet.Ipv4ListRoutingHelper()
54  olsr_routing = ns.olsr.OlsrHelper()
55  static_routing = ns.internet.Ipv4StaticRoutingHelper()
56  list_routing.Add(static_routing, 0)
57  list_routing.Add(olsr_routing, 100)
58  internet.SetRoutingHelper(list_routing)
59 
60  ipv4Addresses = ns.internet.Ipv4AddressHelper()
61  ipv4Addresses.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0"))
62 
63  port = 9 # Discard port(RFC 863)
64  inetAddress = ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"), port)
65  onOffHelper = ns.applications.OnOffHelper("ns3::UdpSocketFactory", inetAddress.ConvertTo())
66  onOffHelper.SetAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps")))
67  onOffHelper.SetAttribute("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
68  onOffHelper.SetAttribute("OffTime", ns.core.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 
83  node = nodes.Get(accumulator)
84  accumulator += 1
85  container = ns.network.NodeContainer(node)
86  internet.Install(container)
87 
88  mobility = ns.CreateObject("ConstantPositionMobilityModel")
89  mobility.SetPosition(ns.core.Vector(xi*DISTANCE, yi*DISTANCE, 0))
90  node.AggregateObject(mobility)
91 
92  device = wifi.Install(wifiPhy, wifiMac, node)
93  ipv4_interfaces = ipv4Addresses.Assign(device)
94  addresses.append(ipv4_interfaces.GetAddress(0))
95 
96  for i, node in [(i, nodes.Get(i)) for i in range(nodes.GetN())]:
97  destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
98  #print (i, destaddr)
99  onOffHelper.SetAttribute("Remote", ns.network.AddressValue(ns.network.InetSocketAddress(destaddr, port).ConvertTo()))
100  container = ns.network.NodeContainer(node)
101  app = onOffHelper.Install(container)
102  urv = ns.CreateObject("UniformRandomVariable")#ns.cppyy.gbl.get_rng()
103  startDelay = ns.Seconds(urv.GetValue(20, 30))
104  app.Start(startDelay)
105 
106  #internet.EnablePcapAll("wifi-olsr")
107  flowmon_helper = ns.flow_monitor.FlowMonitorHelper()
108  #flowmon_helper.SetMonitorAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(31)))
109  monitor = flowmon_helper.InstallAll()
110  monitor = flowmon_helper.GetMonitor()
111  monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001))
112  monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001))
113  monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20))
114 
115  ns.core.Simulator.Stop(ns.core.Seconds(44.0))
116  ns.core.Simulator.Run()
117 
118  def print_stats(os, st):
119  print (" Tx Bytes: ", st.txBytes, file=os)
120  print (" Rx Bytes: ", st.rxBytes, file=os)
121  print (" Tx Packets: ", st.txPackets, file=os)
122  print (" Rx Packets: ", st.rxPackets, file=os)
123  print (" Lost Packets: ", st.lostPackets, file=os)
124  if st.rxPackets > 0:
125  print (" Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets), file=os)
126  print (" Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets-1)), file=os)
127  print (" Mean{Hop Count}: ", float(st.timesForwarded) / st.rxPackets + 1, file=os)
128 
129  if 0:
130  print ("Delay Histogram", file=os)
131  for i in range(st.delayHistogram.GetNBins () ):
132  print (" ",i,"(", st.delayHistogram.GetBinStart (i), "-", \
133  st.delayHistogram.GetBinEnd (i), "): ", st.delayHistogram.GetBinCount (i), file=os)
134  print ("Jitter Histogram", file=os)
135  for i in range(st.jitterHistogram.GetNBins () ):
136  print (" ",i,"(", st.jitterHistogram.GetBinStart (i), "-", \
137  st.jitterHistogram.GetBinEnd (i), "): ", st.jitterHistogram.GetBinCount (i), file=os)
138  print ("PacketSize Histogram", file=os)
139  for i in range(st.packetSizeHistogram.GetNBins () ):
140  print (" ",i,"(", st.packetSizeHistogram.GetBinStart (i), "-", \
141  st.packetSizeHistogram.GetBinEnd (i), "): ", st.packetSizeHistogram.GetBinCount (i), file=os)
142 
143  for reason, drops in enumerate(st.packetsDropped):
144  print (" Packets dropped by reason %i: %i" % (reason, drops), file=os)
145  #for reason, drops in enumerate(st.bytesDropped):
146  # print "Bytes dropped by reason %i: %i" % (reason, drops)
147 
148  monitor.CheckForLostPackets()
149  classifier = flowmon_helper.GetClassifier()
150 
151  if Results.value != b"output.xml":
152  for flow_id, flow_stats in monitor.GetFlowStats():
153  t = classifier.FindFlow(flow_id)
154  proto = {6: 'TCP', 17: 'UDP'} [t.protocol]
155  print ("FlowID: %i (%s %s/%s --> %s/%i)" % \
156  (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort))
157  print_stats(sys.stdout, flow_stats)
158  else:
159  res = monitor.SerializeToXmlFile(Results.value.decode("utf-8"), True, True)
160  print (res)
161 
162 
163  if Plot.value:
164  import pylab
165  delays = []
166  for flow_id, flow_stats in monitor.GetFlowStats():
167  tupl = classifier.FindFlow(flow_id)
168  if tupl.protocol == 17 and tupl.sourcePort == 698:
169  continue
170  delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
171  pylab.hist(delays, 20)
172  pylab.xlabel("Delay (s)")
173  pylab.ylabel("Number of Flows")
174  pylab.show()
175 
176  return 0
177 
178 
179 if __name__ == '__main__':
180  sys.exit(main(sys.argv))
181