8from __future__ 
import print_function
 
   14except ModuleNotFoundError:
 
   16        "Error: ns3 Python module not found;" 
   17        " Python bindings may not be enabled" 
   18        " or your PYTHONPATH might not be properly configured" 
   26    from ctypes 
import c_bool, c_char_p, c_int, create_string_buffer
 
   28    NumNodesSide = c_int(2)
 
   31    ResultsBuffer = create_string_buffer(b
"output.xml", BUFFLEN)
 
   32    Results = c_char_p(ResultsBuffer.raw)
 
   34    cmd = ns.CommandLine(__file__)
 
   37        "Grid side number of nodes (total number of nodes will be this number squared)",
 
   40    cmd.AddValue(
"Results", 
"Write XML results to file", Results, BUFFLEN)
 
   41    cmd.AddValue(
"Plot", 
"Plot the results using the matplotlib python module", Plot)
 
   44    wifi = ns.WifiHelper()
 
   45    wifiMac = ns.WifiMacHelper()
 
   46    wifiPhy = ns.YansWifiPhyHelper()
 
   47    wifiChannel = ns.YansWifiChannelHelper.Default()
 
   48    wifiPhy.SetChannel(wifiChannel.Create())
 
   49    ssid = ns.Ssid(
"wifi-default")
 
   50    wifiMac.SetType(
"ns3::AdhocWifiMac", 
"Ssid", ns.SsidValue(ssid))
 
   52    internet = ns.InternetStackHelper()
 
   53    list_routing = ns.Ipv4ListRoutingHelper()
 
   54    olsr_routing = ns.OlsrHelper()
 
   55    static_routing = ns.Ipv4StaticRoutingHelper()
 
   56    list_routing.Add(static_routing, 0)
 
   57    list_routing.Add(olsr_routing, 100)
 
   58    internet.SetRoutingHelper(list_routing)
 
   60    ipv4Addresses = ns.Ipv4AddressHelper()
 
   61    ipv4Addresses.SetBase(ns.Ipv4Address(
"10.0.0.0"), ns.Ipv4Mask(
"255.255.255.0"))
 
   64    inetAddress = ns.InetSocketAddress(ns.Ipv4Address(
"10.0.0.1"), port)
 
   65    onOffHelper = ns.OnOffHelper(
"ns3::UdpSocketFactory", inetAddress.ConvertTo())
 
   66    onOffHelper.SetAttribute(
"DataRate", ns.DataRateValue(ns.DataRate(
"100kbps")))
 
   67    onOffHelper.SetAttribute(
"OnTime", ns.StringValue(
"ns3::ConstantRandomVariable[Constant=1]"))
 
   68    onOffHelper.SetAttribute(
"OffTime", ns.StringValue(
"ns3::ConstantRandomVariable[Constant=0]"))
 
   73    if NumNodesSide.value == 2:
 
   74        num_nodes_side = NUM_NODES_SIDE
 
   76        num_nodes_side = NumNodesSide.value
 
   78    nodes = ns.NodeContainer(num_nodes_side * num_nodes_side)
 
   80    for xi 
in range(num_nodes_side):
 
   81        for yi 
in range(num_nodes_side):
 
   82            node = nodes.Get(accumulator)
 
   84            container = ns.NodeContainer(node)
 
   85            internet.Install(container)
 
   87            mobility = ns.CreateObject[ns.ConstantPositionMobilityModel]()
 
   88            mobility.SetPosition(ns.Vector(xi * DISTANCE, yi * DISTANCE, 0))
 
   89            node.AggregateObject(mobility)
 
   91            device = wifi.Install(wifiPhy, wifiMac, node)
 
   92            ipv4_interfaces = ipv4Addresses.Assign(device)
 
   93            addresses.append(ipv4_interfaces.GetAddress(0))
 
   95    for i, node 
in [(i, nodes.Get(i)) 
for i 
in range(nodes.GetN())]:
 
   96        destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
 
   98        onOffHelper.SetAttribute(
 
  100            ns.AddressValue(ns.InetSocketAddress(destaddr, port).ConvertTo()),
 
  102        container = ns.NodeContainer(node)
 
  103        app = onOffHelper.Install(container)
 
  104        urv = ns.CreateObject[ns.UniformRandomVariable]()  
 
  105        startDelay = ns.Seconds(urv.GetValue(20, 30))
 
  106        app.Start(startDelay)
 
  109    flowmon_helper = ns.FlowMonitorHelper()
 
  111    monitor = flowmon_helper.InstallAll()
 
  112    monitor = flowmon_helper.GetMonitor()
 
  113    monitor.SetAttribute(
"DelayBinWidth", ns.DoubleValue(0.001))
 
  114    monitor.SetAttribute(
"JitterBinWidth", ns.DoubleValue(0.001))
 
  115    monitor.SetAttribute(
"PacketSizeBinWidth", ns.DoubleValue(20))
 
  117    ns.Simulator.Stop(ns.Seconds(44))
 
  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)
 
  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)
 
  132            print(
"Delay Histogram", file=os)
 
  133            for i 
in range(st.delayHistogram.GetNBins()):
 
  138                    st.delayHistogram.GetBinStart(i),
 
  140                    st.delayHistogram.GetBinEnd(i),
 
  142                    st.delayHistogram.GetBinCount(i),
 
  145            print(
"Jitter Histogram", file=os)
 
  146            for i 
in range(st.jitterHistogram.GetNBins()):
 
  151                    st.jitterHistogram.GetBinStart(i),
 
  153                    st.jitterHistogram.GetBinEnd(i),
 
  155                    st.jitterHistogram.GetBinCount(i),
 
  158            print(
"PacketSize Histogram", file=os)
 
  159            for i 
in range(st.packetSizeHistogram.GetNBins()):
 
  164                    st.packetSizeHistogram.GetBinStart(i),
 
  166                    st.packetSizeHistogram.GetBinEnd(i),
 
  168                    st.packetSizeHistogram.GetBinCount(i),
 
  172        for reason, drops 
in enumerate(st.packetsDropped):
 
  173            print(
"  Packets dropped by reason %i: %i" % (reason, drops), file=os)
 
  177    monitor.CheckForLostPackets()
 
  178    classifier = flowmon_helper.GetClassifier()
 
  180    if Results.value != b
"output.xml":
 
  181        for flow_id, flow_stats 
in monitor.GetFlowStats():
 
  182            t = classifier.FindFlow(flow_id)
 
  183            proto = {6: 
"TCP", 17: 
"UDP"}[t.protocol]
 
  185                "FlowID: %i (%s %s/%s --> %s/%i)" 
  191                    t.destinationAddress,
 
  195            print_stats(sys.stdout, flow_stats)
 
  197        res = monitor.SerializeToXmlFile(Results.value.decode(
"utf-8"), 
True, 
True)
 
  201        from matplotlib 
import pyplot 
as plt
 
  204        for flow_id, flow_stats 
in monitor.GetFlowStats():
 
  205            tupl = classifier.FindFlow(flow_id)
 
  206            if tupl.protocol == 17 
and tupl.sourcePort == 698:
 
  208            delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
 
  210        plt.xlabel(
"Delay (s)")
 
  211        plt.ylabel(
"Number of Flows")
 
  217if __name__ == 
"__main__":
 
  218    sys.exit(main(sys.argv))