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
19from __future__ import print_function
20import sys
21
22from ns import ns
23
24DISTANCE = 20 # (m)
25NUM_NODES_SIDE = 3
26
27
28def 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",
66 ns.network.Address(ns.addressFromInetSocketAddress(inetAddress)))
67 onOffHelper.SetAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps")))
68 onOffHelper.SetAttribute("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
69 onOffHelper.SetAttribute("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
70
71 addresses = []
72 nodes = []
73
74 if NumNodesSide.value == 2:
75 num_nodes_side = NUM_NODES_SIDE
76 else:
77 num_nodes_side = NumNodesSide.value
78
79 nodes = ns.NodeContainer(num_nodes_side*num_nodes_side)
80 accumulator = 0
81 for xi in range(num_nodes_side):
82 for yi in range(num_nodes_side):
83
84 node = nodes.Get(accumulator)
85 accumulator += 1
86 container = ns.network.NodeContainer(node)
87 internet.Install(container)
88
89 mobility = ns.CreateObject("ConstantPositionMobilityModel")
90 mobility.SetPosition(ns.core.Vector(xi*DISTANCE, yi*DISTANCE, 0))
91 node.AggregateObject(mobility)
92
93 device = wifi.Install(wifiPhy, wifiMac, node)
94 ipv4_interfaces = ipv4Addresses.Assign(device)
95 addresses.append(ipv4_interfaces.GetAddress(0))
96
97 for i, node in [(i, nodes.Get(i)) for i in range(nodes.GetN())]:
98 destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
99 #print (i, destaddr)
100 genericAddress = ns.addressFromInetSocketAddress(ns.network.InetSocketAddress(destaddr, port))
101 onOffHelper.SetAttribute("Remote", ns.network.AddressValue(genericAddress))
102 container = ns.network.NodeContainer(node)
103 app = onOffHelper.Install(container)
104 urv = ns.CreateObject("UniformRandomVariable")#ns.cppyy.gbl.get_rng()
105 startDelay = ns.Seconds(urv.GetValue(20, 30))
106 app.Start(startDelay)
107
108 #internet.EnablePcapAll("wifi-olsr")
109 flowmon_helper = ns.flow_monitor.FlowMonitorHelper()
110 #flowmon_helper.SetMonitorAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(31)))
111 monitor = flowmon_helper.InstallAll()
112 monitor = flowmon_helper.GetMonitor()
113 monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001))
114 monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001))
115 monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20))
116
117 ns.core.Simulator.Stop(ns.core.Seconds(44.0))
118 ns.core.Simulator.Run()
119
120 def print_stats(os, st):
121 print (" Tx Bytes: ", st.txBytes, file=os)
122 print (" Rx Bytes: ", st.rxBytes, file=os)
123 print (" Tx Packets: ", st.txPackets, file=os)
124 print (" Rx Packets: ", st.rxPackets, file=os)
125 print (" Lost Packets: ", st.lostPackets, file=os)
126 if st.rxPackets > 0:
127 print (" Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets), file=os)
128 print (" Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets-1)), file=os)
129 print (" Mean{Hop Count}: ", float(st.timesForwarded) / st.rxPackets + 1, file=os)
130
131 if 0:
132 print ("Delay Histogram", file=os)
133 for i in range(st.delayHistogram.GetNBins () ):
134 print (" ",i,"(", st.delayHistogram.GetBinStart (i), "-", \
135 st.delayHistogram.GetBinEnd (i), "): ", st.delayHistogram.GetBinCount (i), file=os)
136 print ("Jitter Histogram", file=os)
137 for i in range(st.jitterHistogram.GetNBins () ):
138 print (" ",i,"(", st.jitterHistogram.GetBinStart (i), "-", \
139 st.jitterHistogram.GetBinEnd (i), "): ", st.jitterHistogram.GetBinCount (i), file=os)
140 print ("PacketSize Histogram", file=os)
141 for i in range(st.packetSizeHistogram.GetNBins () ):
142 print (" ",i,"(", st.packetSizeHistogram.GetBinStart (i), "-", \
143 st.packetSizeHistogram.GetBinEnd (i), "): ", st.packetSizeHistogram.GetBinCount (i), file=os)
144
145 for reason, drops in enumerate(st.packetsDropped):
146 print (" Packets dropped by reason %i: %i" % (reason, drops), file=os)
147 #for reason, drops in enumerate(st.bytesDropped):
148 # print "Bytes dropped by reason %i: %i" % (reason, drops)
149
150 monitor.CheckForLostPackets()
151 classifier = flowmon_helper.GetClassifier()
152
153 if Results.value != b"output.xml":
154 for flow_id, flow_stats in monitor.GetFlowStats():
155 t = classifier.FindFlow(flow_id)
156 proto = {6: 'TCP', 17: 'UDP'} [t.protocol]
157 print ("FlowID: %i (%s %s/%s --> %s/%i)" % \
158 (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort))
159 print_stats(sys.stdout, flow_stats)
160 else:
161 res = monitor.SerializeToXmlFile(Results.value.decode("utf-8"), True, True)
162 print (res)
163
164
165 if Plot.value:
166 import pylab
167 delays = []
168 for flow_id, flow_stats in monitor.GetFlowStats():
169 tupl = classifier.FindFlow(flow_id)
170 if tupl.protocol == 17 and tupl.sourcePort == 698:
171 continue
172 delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
173 pylab.hist(delays, 20)
174 pylab.xlabel("Delay (s)")
175 pylab.ylabel("Number of Flows")
176 pylab.show()
177
178 return 0
179
180
181if __name__ == '__main__':
182 sys.exit(main(sys.argv))
183