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