A Discrete-Event Network Simulator
API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups 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 import sys
20 
21 import ns.applications
22 import ns.core
23 import ns.flow_monitor
24 import ns.internet
25 import ns.mobility
26 import ns.network
27 import ns.olsr
28 import ns.wifi
29 try:
30  import ns.visualizer
31 except ImportError:
32  pass
33 
34 DISTANCE = 100 # (m)
35 NUM_NODES_SIDE = 3
36 
37 def main(argv):
38 
39  cmd = ns.core.CommandLine()
40 
41  cmd.NumNodesSide = None
42  cmd.AddValue("NumNodesSide", "Grid side number of nodes (total number of nodes will be this number squared)")
43 
44  cmd.Results = None
45  cmd.AddValue("Results", "Write XML results to file")
46 
47  cmd.Plot = None
48  cmd.AddValue("Plot", "Plot the results using the matplotlib python module")
49 
50  cmd.Parse(argv)
51 
52  wifi = ns.wifi.WifiHelper.Default()
53  wifiMac = ns.wifi.NqosWifiMacHelper.Default()
54  wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
55  wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
56  wifiPhy.SetChannel(wifiChannel.Create())
57  ssid = ns.wifi.Ssid("wifi-default")
58  wifi.SetRemoteStationManager("ns3::ArfWifiManager")
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 >> os, " Tx Bytes: ", st.txBytes
126  print >> os, " Rx Bytes: ", st.rxBytes
127  print >> os, " Tx Packets: ", st.txPackets
128  print >> os, " Rx Packets: ", st.rxPackets
129  print >> os, " Lost Packets: ", st.lostPackets
130  if st.rxPackets > 0:
131  print >> os, " Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets)
132  print >> os, " Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets-1))
133  print >> os, " Mean{Hop Count}: ", float(st.timesForwarded) / st.rxPackets + 1
134 
135  if 0:
136  print >> os, "Delay Histogram"
137  for i in range(st.delayHistogram.GetNBins () ):
138  print >> os, " ",i,"(", st.delayHistogram.GetBinStart (i), "-", \
139  st.delayHistogram.GetBinEnd (i), "): ", st.delayHistogram.GetBinCount (i)
140  print >> os, "Jitter Histogram"
141  for i in range(st.jitterHistogram.GetNBins () ):
142  print >> os, " ",i,"(", st.jitterHistogram.GetBinStart (i), "-", \
143  st.jitterHistogram.GetBinEnd (i), "): ", st.jitterHistogram.GetBinCount (i)
144  print >> os, "PacketSize Histogram"
145  for i in range(st.packetSizeHistogram.GetNBins () ):
146  print >> os, " ",i,"(", st.packetSizeHistogram.GetBinStart (i), "-", \
147  st.packetSizeHistogram.GetBinEnd (i), "): ", st.packetSizeHistogram.GetBinCount (i)
148 
149  for reason, drops in enumerate(st.packetsDropped):
150  print " Packets dropped by reason %i: %i" % (reason, drops)
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