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 = 100 # (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.Default()
56  wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
57  wifiPhy.SetChannel(wifiChannel.Create())
58  ssid = ns.wifi.Ssid("wifi-default")
59  wifi.SetRemoteStationManager("ns3::ArfWifiManager")
60  wifiMac.SetType ("ns3::AdhocWifiMac",
61  "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  onOffHelper = ns.applications.OnOffHelper("ns3::UdpSocketFactory",
76  ns.network.Address(ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"), port)))
77  onOffHelper.SetAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps")))
78  onOffHelper.SetAttribute("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
79  onOffHelper.SetAttribute("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
80 
81  addresses = []
82  nodes = []
83 
84  if cmd.NumNodesSide is None:
85  num_nodes_side = NUM_NODES_SIDE
86  else:
87  num_nodes_side = int(cmd.NumNodesSide)
88 
89  for xi in range(num_nodes_side):
90  for yi in range(num_nodes_side):
91 
92  node = ns.network.Node()
93  nodes.append(node)
94 
95  internet.Install(ns.network.NodeContainer(node))
96 
97  mobility = ns.mobility.ConstantPositionMobilityModel()
98  mobility.SetPosition(ns.core.Vector(xi*DISTANCE, yi*DISTANCE, 0))
99  node.AggregateObject(mobility)
100 
101  devices = wifi.Install(wifiPhy, wifiMac, node)
102  ipv4_interfaces = ipv4Addresses.Assign(devices)
103  addresses.append(ipv4_interfaces.GetAddress(0))
104 
105  for i, node in enumerate(nodes):
106  destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
107  #print (i, destaddr)
108  onOffHelper.SetAttribute("Remote", ns.network.AddressValue(ns.network.InetSocketAddress(destaddr, port)))
109  app = onOffHelper.Install(ns.network.NodeContainer(node))
110  urv = ns.core.UniformRandomVariable()
111  app.Start(ns.core.Seconds(urv.GetValue(20, 30)))
112 
113  #internet.EnablePcapAll("wifi-olsr")
114  flowmon_helper = ns.flow_monitor.FlowMonitorHelper()
115  #flowmon_helper.SetMonitorAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(31)))
116  monitor = flowmon_helper.InstallAll()
117  monitor = flowmon_helper.GetMonitor()
118  monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001))
119  monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001))
120  monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20))
121 
122  ns.core.Simulator.Stop(ns.core.Seconds(44.0))
123  ns.core.Simulator.Run()
124 
125  def print_stats(os, st):
126  print (" Tx Bytes: ", st.txBytes, file=os)
127  print (" Rx Bytes: ", st.rxBytes, file=os)
128  print (" Tx Packets: ", st.txPackets, file=os)
129  print (" Rx Packets: ", st.rxPackets, file=os)
130  print (" Lost Packets: ", st.lostPackets, file=os)
131  if st.rxPackets > 0:
132  print (" Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets), file=os)
133  print (" Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets-1)), file=os)
134  print (" Mean{Hop Count}: ", float(st.timesForwarded) / st.rxPackets + 1, file=os)
135 
136  if 0:
137  print ("Delay Histogram", file=os)
138  for i in range(st.delayHistogram.GetNBins () ):
139  print (" ",i,"(", st.delayHistogram.GetBinStart (i), "-", \
140  st.delayHistogram.GetBinEnd (i), "): ", st.delayHistogram.GetBinCount (i), file=os)
141  print ("Jitter Histogram", file=os)
142  for i in range(st.jitterHistogram.GetNBins () ):
143  print (" ",i,"(", st.jitterHistogram.GetBinStart (i), "-", \
144  st.jitterHistogram.GetBinEnd (i), "): ", st.jitterHistogram.GetBinCount (i), file=os)
145  print ("PacketSize Histogram", file=os)
146  for i in range(st.packetSizeHistogram.GetNBins () ):
147  print (" ",i,"(", st.packetSizeHistogram.GetBinStart (i), "-", \
148  st.packetSizeHistogram.GetBinEnd (i), "): ", st.packetSizeHistogram.GetBinCount (i), file=os)
149 
150  for reason, drops in enumerate(st.packetsDropped):
151  print (" Packets dropped by reason %i: %i" % (reason, drops), file=os)
152  #for reason, drops in enumerate(st.bytesDropped):
153  # print "Bytes dropped by reason %i: %i" % (reason, drops)
154 
155  monitor.CheckForLostPackets()
156  classifier = flowmon_helper.GetClassifier()
157 
158  if cmd.Results is None:
159  for flow_id, flow_stats in monitor.GetFlowStats():
160  t = classifier.FindFlow(flow_id)
161  proto = {6: 'TCP', 17: 'UDP'} [t.protocol]
162  print ("FlowID: %i (%s %s/%s --> %s/%i)" % \
163  (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort))
164  print_stats(sys.stdout, flow_stats)
165  else:
166  print (monitor.SerializeToXmlFile(cmd.Results, True, True))
167 
168 
169  if cmd.Plot is not None:
170  import pylab
171  delays = []
172  for flow_id, flow_stats in monitor.GetFlowStats():
173  tupl = classifier.FindFlow(flow_id)
174  if tupl.protocol == 17 and tupl.sourcePort == 698:
175  continue
176  delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
177  pylab.hist(delays, 20)
178  pylab.xlabel("Delay (s)")
179  pylab.ylabel("Number of Flows")
180  pylab.show()
181 
182  return 0
183 
184 
185 if __name__ == '__main__':
186  sys.exit(main(sys.argv))
187