Example #1
0
    def _init_network(self):
        self.initialized = True
        rss = -80

        wifi = ns.wifi.WifiHelper()
        wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211g)

        wifi_phy = ns.wifi.YansWifiPhyHelper.Default()
        wifi_phy.Set("RxGain", ns.core.DoubleValue(0))
        wifi_phy.SetPcapDataLinkType(
            ns.wifi.YansWifiPhyHelper.DLT_IEEE802_11_RADIO
        )

        wifi_channel = ns.wifi.YansWifiChannelHelper()
        wifi_channel.SetPropagationDelay(
            "ns3::ConstantSpeedPropagationDelayModel"
        )
        # fixed RSS regardless of the distance and transmit power
        wifi_channel.AddPropagationLoss(
            "ns3::FixedRssLossModel",
            "Rss",
            ns.core.DoubleValue(rss)
        )

        wifi_phy.SetChannel(wifi_channel.Create())

        # disable rate control
        wifi.SetRemoteStationManager(
            "ns3::ConstantRateWifiManager",
            "DataMode", ns.core.StringValue(self.phy_mode),
            "ControlMode", ns.core.StringValue(self.phy_mode),
        )

        wifi_mac = ns.wifi.WifiMacHelper()
        wifi_mac.SetType("ns3::AdhocWifiMac")

        # mobility
        mobility = ns.mobility.MobilityHelper()
        positions = ns.mobility.ListPositionAllocator()
        for i in range(self.nodes.GetN()):
            positions.Add(ns.mobility.Vector(5*i, int(i/5)*2, 0))

        mobility.SetPositionAllocator(positions)
        mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
        mobility.Install(self.nodes)

        devices = wifi.Install(wifi_phy, wifi_mac, self.nodes)

        self._init_ip(devices)
Example #2
0
    def setup(self):
        wifi = ns.wifi.WifiHelper.Default()
        wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a)
        wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
                                     "DataMode",
                                     ns.core.StringValue("OfdmRate54Mbps"))

        wifiMac = ns.wifi.NqosWifiMacHelper.Default()
        wifiMac.SetType("ns3::AdhocWifiMac")

        wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
        wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
        wifiPhy.SetChannel(wifiChannel.Create())

        nodes = ns.network.NodeContainer()
        for i in xrange(self.options.numnodes):
            name = "n%s" % i
            n = NetnsNode(name, logfile="/tmp/%s.log" % name)
            self.nodes.append(n)
            nodes.Add(n)

        mobility = ns.mobility.MobilityHelper()
        positionAlloc = ns.mobility.ListPositionAllocator()
        for i in xrange(self.options.numnodes):
            positionAlloc.Add(ns.core.Vector(1.0 * i, 0.0, 0.0))
        mobility.SetPositionAllocator(positionAlloc)
        mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
        mobility.Install(nodes)

        devices = wifi.Install(wifiPhy, wifiMac, nodes)

        tapbridge = ns.tap_bridge.TapBridgeHelper()
        addrhelper, mask = parseprefix("10.0.0.0/8")

        for i in xrange(nodes.GetN()):
            n = nodes.Get(i)
            dev = devices.Get(i)
            tap = tapbridge.Install(n, dev)
            tap.SetMode(ns.tap_bridge.TapBridge.CONFIGURE_LOCAL)
            tapname = "ns3tap%d" % i
            tap.SetAttribute("DeviceName", ns.core.StringValue(tapname))
            addr = addrhelper.NewAddress()
            tap.SetAttribute("IpAddress", ns.network.Ipv4AddressValue(addr))
            tap.SetAttribute("Netmask", ns.network.Ipv4MaskValue(mask))

            n.addnetif(tapname,
                       ipaddrs=["%s/%s" % (addr, mask.GetPrefixLength())],
                       rename="ath0")
            n.ipaddr = str(addr)
def main(argv):

    ns.core.GlobalValue.Bind("SimulatorImplementationType",
                             ns.core.StringValue("ns3::RealtimeSimulatorImpl"))
    ns.core.GlobalValue.Bind("ChecksumEnabled", ns.core.BooleanValue("true"))

    nodes = ns.network.NodeContainer()
    nodes.Create(2)

    wifi = ns.wifi.WifiHelper.Default()
    wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a)
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue("OfdmRate54Mbps"))

    wifiMac = ns.wifi.NqosWifiMacHelper.Default()
    wifiMac.SetType("ns3::AdhocWifiMac")

    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())

    devices = wifi.Install(wifiPhy, wifiMac, nodes)

    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()
    positionAlloc.Add(ns.core.Vector(0.0, 0.0, 0.0))
    positionAlloc.Add(ns.core.Vector(5.0, 0.0, 0.0))
    mobility.SetPositionAllocator(positionAlloc)
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install(nodes)

    tapBridge = ns.tap_bridge.TapBridgeHelper()
    tapBridge.SetAttribute("Mode", ns.core.StringValue("UseLocal"))
    tapBridge.SetAttribute("DeviceName", ns.core.StringValue("tap-left"))
    tapBridge.Install(nodes.Get(0), devices.Get(0))

    tapBridge.SetAttribute("DeviceName", ns.core.StringValue("tap-right"))
    tapBridge.Install(nodes.Get(1), devices.Get(1))

    ns.core.Simulator.Stop(ns.core.Seconds(600))
    ns.core.Simulator.Run(signal_check_frequency=-1)
    ns.core.Simulator.Destroy()
    return 0
def main(argv):
    #
    # We are interacting with the outside, real, world.  This means we have to
    # interact in real-time and therefore we have to use the real-time simulator
    # and take the time to calculate checksums.
    #
    ns.core.GlobalValue.Bind("SimulatorImplementationType",
                             ns.core.StringValue("ns3::RealtimeSimulatorImpl"))
    ns.core.GlobalValue.Bind("ChecksumEnabled", ns.core.BooleanValue("true"))

    #
    # Create two ghost nodes.  The first will represent the virtual machine host
    # on the left side of the network; and the second will represent the VM on
    # the right side.
    #
    nodes = ns.network.NodeContainer()
    nodes.Create(2)

    #
    # We're going to use 802.11 A so set up a wifi helper to reflect that.
    #
    wifi = ns.wifi.WifiHelper.Default()
    wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a)
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue("OfdmRate54Mbps"))

    #
    # No reason for pesky access points, so we'll use an ad-hoc network.
    #
    wifiMac = ns.wifi.NqosWifiMacHelper.Default()
    wifiMac.SetType("ns3::AdhocWifiMac")

    #
    # Configure the physcial layer.
    #
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())

    #
    # Install the wireless devices onto our ghost nodes.
    #
    devices = wifi.Install(wifiPhy, wifiMac, nodes)

    #
    # We need location information since we are talking about wifi, so add a
    # constant position to the ghost nodes.
    #
    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()
    positionAlloc.Add(ns.core.Vector(0.0, 0.0, 0.0))
    positionAlloc.Add(ns.core.Vector(5.0, 0.0, 0.0))
    mobility.SetPositionAllocator(positionAlloc)
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install(nodes)

    #
    # Use the TapBridgeHelper to connect to the pre-configured tap devices for
    # the left side.  We go with "UseLocal" mode since the wifi devices do not
    # support promiscuous mode (because of their natures0.  This is a special
    # case mode that allows us to extend a linux bridge into ns-3 IFF we will
    # only see traffic from one other device on that bridge.  That is the case
    # for this configuration.
    #
    tapBridge = ns.tap_bridge.TapBridgeHelper()
    tapBridge.SetAttribute("Mode", ns.core.StringValue("UseLocal"))
    tapBridge.SetAttribute("DeviceName", ns.core.StringValue("tap-left"))
    tapBridge.Install(nodes.Get(0), devices.Get(0))

    #
    # Connect the right side tap to the right side wifi device on the right-side
    # ghost node.
    #
    tapBridge.SetAttribute("DeviceName", ns.core.StringValue("tap-right"))
    tapBridge.Install(nodes.Get(1), devices.Get(1))

    #
    # Run the simulation for ten minutes to give the user time to play around
    #
    ns.core.Simulator.Stop(ns.core.Seconds(600))
    ns.core.Simulator.Run(signal_check_frequency=-1)
    ns.core.Simulator.Destroy()
    return 0
  	ns.core.Config.SetDefault ("ns3::RangePropagationLossModel::MaxRange", ns.core.DoubleValue (5))

	wifiStaNodes = ns.network.NodeContainer ()
	wifiStaNodes.Create (2)
	wifiApNode = ns.network.NodeContainer ()
	wifiApNode.Create (1)
	
	channel = ns.wifi.YansWifiChannelHelper.Default ()
	channel.AddPropagationLoss ("ns3::RangePropagationLossModel") # wireless range limited to 5 meters!

	phy = ns.wifi.YansWifiPhyHelper.Default ()
	phy.SetPcapDataLinkType (ns.wifi.YansWifiPhyHelper.DLT_IEEE802_11_RADIO)
	phy.SetChannel (channel.Create ())

	wifi = ns.wifi.WifiHelper.Default ()
	wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211n_5GHZ)
	wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue ("HtMcs7"), "ControlMode", ns.core.StringValue ("HtMcs0"))
  mac = ns.wifi.HtWifiMacHelper.Default ()

  ssid = ns.wifi.Ssid ("simple-mpdu-aggregation")
  mac.SetType ("ns3::StaWifiMac",
		    "Ssid", ns.wifi.SsidValue (ssid),
		    "ActiveProbing", ns.core.BooleanValue (False),
		    "BE_MaxAmpduSize", ns.core.UintegerValue (maxAmpduSize))

  staDevices = ns.network.NetDeviceContainer ()
  staDevices = wifi.Install (phy, mac, wifiStaNodes)

  mac.SetType ("ns3::ApWifiMac",
		    "Ssid", ns.wifi.SsidValue (ssid),
		    "BeaconInterval", ns.core.TimeValue (ns.core.MicroSeconds (102400)),
def main(argv):
    cmd = ns.core.CommandLine()
    cmd.simulationTime = 10  #seconds
    cmd.distance = 0.0  #meters
    cmd.frequency = 2.4  #whether 2.4 or 5.0 GHz

    simulationTime = float(cmd.simulationTime)
    distance = float(cmd.distance)
    frequency = float(cmd.frequency)

    #Configuration arguments
    bandwidth = 20
    mcs = 3
    gi = True

    print("\n Configured BW:", bandwidth, "MCS:", mcs, "GI:", gi)

    channel = ns.wifi.YansWifiChannelHelper.Default()
    phy = ns.wifi.YansWifiPhyHelper.Default()
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.NqosWifiMacHelper.Default()

    phy.SetChannel(channel.Create())

    payloadSize = 1448  #bytes
    ns.core.Config.SetDefault("ns3::TcpSocket::SegmentSize",
                              ns.core.UintegerValue(payloadSize))

    wifiStaNode = ns.network.NodeContainer()
    wifiStaNode.Create(1)
    wifiApNode = ns.network.NodeContainer()
    wifiApNode.Create(1)

    wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211n_2_4GHZ)
    ns.core.Config.SetDefault(
        "ns3::LogDistancePropagationLossModel::ReferenceLoss",
        ns.core.DoubleValue(40.046))

    # Set guard interval
    phy.Set("ShortGuardEnabled", ns.core.BooleanValue(gi))

    mac = ns.wifi.HtWifiMacHelper.Default()
    DataRate = ns.wifi.HtWifiMacHelper.DataRateForMcs(mcs)
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 DataRate, "ControlMode", DataRate)

    ssid = ns.wifi.Ssid("wifi-80211n")

    mac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                "ActiveProbing", ns.core.BooleanValue(False))

    staDevice = wifi.Install(phy, mac, wifiStaNode)
    mac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

    apDevice = wifi.Install(phy, mac, wifiApNode)

    # Set channel width
    ns.core.Config.Set(
        "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth",
        ns.core.UintegerValue(bandwidth))

    # mobility
    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()

    positionAlloc.Add(ns.core.Vector3D(0.0, 0.0, 0.0))
    positionAlloc.Add(ns.core.Vector3D(distance, 0.0, 0.0))
    mobility.SetPositionAllocator(positionAlloc)

    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")

    mobility.Install(wifiApNode)
    mobility.Install(wifiStaNode)

    # Internet stack
    stack = ns.internet.InternetStackHelper()
    stack.Install(wifiApNode)
    stack.Install(wifiStaNode)

    address = ns.internet.Ipv4AddressHelper()

    address.SetBase(ns.network.Ipv4Address("192.168.1.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    staNodeInterface = address.Assign(staDevice)
    apNodeInterface = address.Assign(apDevice)

    # Setting applications
    serverApp = ns.network.ApplicationContainer()
    sinkApp = ns.network.ApplicationContainer()
    port = 50000
    apLocalAddress = ns.network.Address(
        ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port))
    packetSinkHelper = ns.applications.PacketSinkHelper(
        "ns3::TcpSocketFactory", apLocalAddress)
    sinkApp = packetSinkHelper.Install(wifiStaNode.Get(0))

    print("\n Application is starting ! \n")

    sinkApp.Start(ns.core.Seconds(0.0))
    sinkApp.Stop(ns.core.Seconds(simulationTime + 1))

    onoff = ns.applications.OnOffHelper("ns3::TcpSocketFactory",
                                        ns.network.Ipv4Address.GetAny())
    onoff.SetAttribute(
        "OnTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
    onoff.SetAttribute(
        "OffTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))
    onoff.SetAttribute("PacketSize", ns.core.UintegerValue(payloadSize))
    onoff.SetAttribute("DataRate",
                       ns.network.DataRateValue(
                           ns.network.DataRate(1000000000)))  # bit/s
    apps = ns.network.ApplicationContainer()

    remoteAddress = ns.network.AddressValue(
        ns.network.InetSocketAddress(staNodeInterface.GetAddress(0), port))
    onoff.SetAttribute("Remote", remoteAddress)
    apps.Add(onoff.Install(wifiApNode.Get(0)))
    apps.Start(ns.core.Seconds(1.0))
    apps.Stop(ns.core.Seconds(simulationTime + 1))

    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

    ns.core.Simulator.Stop(ns.core.Seconds(simulationTime + 1))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()

    throughput = 0
    # TCP
    totalPacketsThrough = sinkApp.Get(0).GetTotalRx()
    throughput = totalPacketsThrough * 8 / (simulationTime * 1000000.0
                                            )  # Mbit/s

    print "*** Throughput: ", throughput, " Mbit/s***"
    return 0
def main(argv):
    cmd = ns.core.CommandLine()
    cmd.simulationTime = 10  #seconds
    cmd.distance = 0.0  #meters
    simulationTime = float(cmd.simulationTime)
    distance = float(cmd.distance)

    #Configuration arguments
    udp = True
    bandwidth = [20, 40, 80]
    mcs = [2, 4, 7]
    gi = [False, True]
    amsduVOBE = 11406  #Maximum amound by standard definition
    amsduVIBK = 11406  #Maximum amound by standard definition
    expected_val = [[11, 20.8, 39], [20, 36, 66.5], [30, 54, 91]]

    print "MCS's: \t Bandwidth: \t Troughput:\t\t  Delay:\t Lost packets:\tTransmited packets:"

    for count_mcs, a in enumerate(mcs):
        for count_bandwidth, b in enumerate(bandwidth):
            for c in gi:
                channel = ns.wifi.YansWifiChannelHelper.Default()
                phy = ns.wifi.YansWifiPhyHelper.Default()
                wifi = ns.wifi.WifiHelper()
                mac = ns.wifi.NqosWifiMacHelper.Default()

                phy.SetChannel(channel.Create())

                if udp == False:
                    payloadSize = 1448  #bytes
                    ns.core.Config.SetDefault(
                        "ns3::TcpSocket::SegmentSize",
                        ns.core.UintegerValue(payloadSize))
                elif udp == True:
                    payloadSize = 1472

                wifiStaNode = ns.network.NodeContainer()
                wifiStaNode.Create(2)
                wifiApNode = ns.network.NodeContainer()
                wifiApNode.Create(1)

                wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211ac)

                # Set guard interval
                phy.Set("ShortGuardEnabled", ns.core.BooleanValue(c))

                mac = ns.wifi.VhtWifiMacHelper.Default()
                DataRate = ns.wifi.VhtWifiMacHelper.DataRateForMcs(a)
                wifi.SetRemoteStationManager(
                    "ns3::ConstantRateWifiManager", "DataMode", DataRate,
                    "ControlMode", ns.wifi.VhtWifiMacHelper.DataRateForMcs(0))

                ssid = ns.wifi.Ssid("wifi-80211ac")

                mac.SetType(
                    "ns3::StaWifiMac", "Ssid",
                    ns.wifi.SsidValue(ssid), "ActiveProbing",
                    ns.core.BooleanValue(False), "BE_MaxAmsduSize",
                    ns.core.UintegerValue(amsduVOBE), "BK_MaxAmsduSize",
                    ns.core.UintegerValue(amsduVIBK), "VI_MaxAmsduSize",
                    ns.core.UintegerValue(amsduVIBK), "VO_MaxAmsduSize",
                    ns.core.UintegerValue(amsduVOBE), "BE_MaxAmpduSize",
                    ns.core.UintegerValue(0), "BK_MaxAmpduSize",
                    ns.core.UintegerValue(0), "VI_MaxAmpduSize",
                    ns.core.UintegerValue(0), "VO_MaxAmpduSize",
                    ns.core.UintegerValue(0))

                staDevice = wifi.Install(phy, mac, wifiStaNode)
                mac.SetType(
                    "ns3::ApWifiMac", "Ssid",
                    ns.wifi.SsidValue(ssid), "BE_MaxAmsduSize",
                    ns.core.UintegerValue(amsduVOBE), "BK_MaxAmsduSize",
                    ns.core.UintegerValue(amsduVIBK), "VI_MaxAmsduSize",
                    ns.core.UintegerValue(amsduVIBK), "VO_MaxAmsduSize",
                    ns.core.UintegerValue(amsduVOBE), "BE_MaxAmpduSize",
                    ns.core.UintegerValue(0), "BK_MaxAmpduSize",
                    ns.core.UintegerValue(0), "VI_MaxAmpduSize",
                    ns.core.UintegerValue(0), "VO_MaxAmpduSize",
                    ns.core.UintegerValue(0))

                apDevice = wifi.Install(phy, mac, wifiApNode)

                # Set channel width
                ns.core.Config.Set(
                    "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth",
                    ns.core.UintegerValue(b))

                # mobility
                mobility = ns.mobility.MobilityHelper()
                positionAlloc = ns.mobility.ListPositionAllocator()

                positionAlloc.Add(ns.core.Vector3D(0.0, 0.0, 0.0))
                positionAlloc.Add(ns.core.Vector3D(distance, 0.0, 0.0))
                mobility.SetPositionAllocator(positionAlloc)

                mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")

                mobility.Install(wifiApNode)
                mobility.Install(wifiStaNode)

                # Internet stack
                stack = ns.internet.InternetStackHelper()
                stack.Install(wifiApNode)
                stack.Install(wifiStaNode)

                address = ns.internet.Ipv4AddressHelper()

                address.SetBase(ns.network.Ipv4Address("192.168.1.0"),
                                ns.network.Ipv4Mask("255.255.255.0"))
                staNodeInterface = address.Assign(staDevice)
                apNodeInterface = address.Assign(apDevice)

                # Setting applications
                serverApp = ns.network.ApplicationContainer()
                sinkApp = ns.network.ApplicationContainer()

                if udp == False:

                    # TCP flow
                    port = 50000
                    apLocalAddress = ns.network.Address(
                        ns.network.InetSocketAddress(
                            ns.network.Ipv4Address.GetAny(), port))
                    packetSinkHelper = ns.applications.PacketSinkHelper(
                        "ns3::TcpSocketFactory", apLocalAddress)
                    sinkApp = packetSinkHelper.Install(wifiApNode)

                    sinkApp.Start(ns.core.Seconds(0.0))
                    sinkApp.Stop(ns.core.Seconds(simulationTime + 1))

                    onoff = ns.applications.OnOffHelper(
                        "ns3::TcpSocketFactory",
                        ns.network.Ipv4Address.GetAny())
                    onoff.SetAttribute(
                        "OnTime",
                        ns.core.StringValue(
                            "ns3::ConstantRandomVariable[Constant=1]"))
                    onoff.SetAttribute(
                        "OffTime",
                        ns.core.StringValue(
                            "ns3::ConstantRandomVariable[Constant=0]"))
                    onoff.SetAttribute("PacketSize",
                                       ns.core.UintegerValue(payloadSize))
                    onoff.SetAttribute(
                        "DataRate",
                        ns.network.DataRateValue(
                            ns.network.DataRate(1000000000)))  # bit/s
                    apps = ns.network.ApplicationContainer()

                    remoteAddress = ns.network.AddressValue(
                        ns.network.InetSocketAddress(
                            staNodeInterface.GetAddress(0), port))
                    onoff.SetAttribute("Remote", remoteAddress)
                    apps.Add(onoff.Install(wifiStaNode))
                    apps.Start(ns.core.Seconds(1.0))
                    apps.Stop(ns.core.Seconds(simulationTime + 1))

                elif udp == True:

                    # UDP flow
                    myServer = ns.applications.UdpServerHelper(9)
                    serverApp = myServer.Install(
                        ns.network.NodeContainer(wifiApNode))
                    serverApp.Start(ns.core.Seconds(0.0))
                    serverApp.Stop(ns.core.Seconds(simulationTime + 1))

                    temp = float(
                        (expected_val[count_mcs][count_bandwidth] * 1000000) /
                        (payloadSize * 8))
                    inter = float(1 / temp)
                    inter = format(inter, 'f')

                    myClient = ns.applications.UdpClientHelper(
                        apNodeInterface.GetAddress(0), 9)
                    myClient.SetAttribute("MaxPackets",
                                          ns.core.UintegerValue(4294967295))
                    myClient.SetAttribute(
                        "Interval",
                        ns.core.TimeValue(ns.core.Time(inter)))  # packets/s
                    myClient.SetAttribute("PacketSize",
                                          ns.core.UintegerValue(payloadSize))

                    clientApp = myClient.Install(
                        ns.network.NodeContainer(wifiStaNode))
                    clientApp.Start(ns.core.Seconds(1.0))
                    clientApp.Stop(ns.core.Seconds(simulationTime + 1))

                ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

                flowmonitor = ns.flow_monitor.FlowMonitorHelper()
                monitor = flowmonitor.InstallAll()

                monitor.SetAttribute("StartTime",
                                     ns.core.TimeValue(ns.core.Seconds(5)))
                monitor.SetAttribute("DelayBinWidth",
                                     ns.core.DoubleValue(0.001))
                monitor.SetAttribute("JitterBinWidth",
                                     ns.core.DoubleValue(0.001))
                monitor.SetAttribute("PacketSizeBinWidth",
                                     ns.core.DoubleValue(20))
                ns.core.Simulator.Stop(ns.core.Seconds(simulationTime + 1))
                ns.core.Simulator.Run()
                ns.core.Simulator.Destroy()

                monitor.CheckForLostPackets()
                classifier = ns.flow_monitor.Ipv4FlowClassifier()
                classifier = flowmonitor.GetClassifier()
                stats = monitor.GetFlowStats()

                for flow_id, flow_stats in stats:
                    t = classifier.FindFlow(flow_id)
                    p_tran = flow_stats.txPackets
                    p_rec = flow_stats.rxPackets
                    p_diff = p_tran - p_rec
                    delay_sum = flow_stats.delaySum
                    delay = delay_sum / p_rec
                    lost_packets = flow_stats.lostPackets

                throughput = 0
                if udp == False:
                    # TCP
                    totalPacketsThrough = sinkApp.Get(0).GetTotalRx()
                    throughput = totalPacketsThrough * 8 / (
                        simulationTime * 1000000.0)  # Mbit/s
                elif udp == True:
                    # UDP
                    totalPacketsThrough = serverApp.Get(0).GetReceived()
                    throughput = totalPacketsThrough * payloadSize * 8 / (
                        simulationTime * 1000000.0)  # Mbit/s

                print a, "\t", b, "MHz\t", c, "\t", throughput, "Mbit/s\t", delay, "\t\t", lost_packets, "\t\t ", p_tran
    return 0
Example #8
0
def main(argv):
    cmd = ns.core.CommandLine ()
    cmd.udp = "True"
    cmd.simulationTime = 10 #seconds
    cmd.distance = 1.0 #meters
    cmd.frequency = 5.0 #whether 2.4 or 5.0 GHz

    cmd.AddValue ("frequency", "Whether working in the 2.4 or 5.0 GHz band (other values gets rejected)")
    cmd.AddValue ("distance", "Distance in meters between the station and the access point")
    cmd.AddValue ("simulationTime", "Simulation time in seconds")
    cmd.AddValue ("udp", "UDP if set to True, TCP otherwise")
    cmd.Parse (sys.argv)

    udp = cmd.udp
    simulationTime = float(cmd.simulationTime)
    distance = float(cmd.distance)
    frequency = float(cmd.frequency)

    print "MCS value" , "\t\t", "Channel width", "\t\t", "short GI","\t\t","Throughput" ,'\n'
    for i in range(0,8): #MCS
        j = 20
        while j <= 40: #channel width
            for k in range(0,2): #GI: 0 and 1
                if udp:
                    payloadSize = 1472  #bytes
                else:
                    payloadSize = 1448  #bytes
                    ns.core.Config.SetDefault ("ns3::TcpSocket::SegmentSize", ns.core.UintegerValue (payloadSize))

                wifiStaNode = ns.network.NodeContainer ()
                wifiStaNode.Create (1)
                wifiApNode = ns.network.NodeContainer ()
                wifiApNode.Create (1)

                channel = ns.wifi.YansWifiChannelHelper.Default ()
                phy = ns.wifi.YansWifiPhyHelper.Default ()
                phy.SetChannel (channel.Create ())

                # Set guard interval
                phy.Set ("ShortGuardEnabled", ns.core.BooleanValue (k))
                wifi = ns.wifi.WifiHelper.Default ()
                if frequency == 5.0:
                    wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211n_5GHZ)

                elif frequency == 2.4:
                    wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211n_2_4GHZ)
                    ns.core.Config.SetDefault ("ns3::LogDistancePropagationLossModel::ReferenceLoss", ns.core.DoubleValue (40.046))

                else:
                    print "Wrong frequency value!\n"
                    return 0

                mac = ns.wifi.HtWifiMacHelper.Default ()
                DataRate = ns.wifi.HtWifiMacHelper.DataRateForMcs (i)
                wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager","DataMode", DataRate,
                                              "ControlMode", DataRate)

                ssid = ns.wifi.Ssid ("ns3-80211n")

                mac.SetType ("ns3::StaWifiMac",
                             "Ssid", ns.wifi.SsidValue (ssid),
                             "ActiveProbing", ns.core.BooleanValue (False))

                staDevice = wifi.Install (phy, mac, wifiStaNode)
                mac.SetType ("ns3::ApWifiMac",
                             "Ssid", ns.wifi.SsidValue (ssid))

                apDevice = wifi.Install (phy, mac, wifiApNode)

                # Set channel width
                ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue (j))

                # mobility
                mobility = ns.mobility.MobilityHelper ()
                positionAlloc = ns.mobility.ListPositionAllocator ()

                positionAlloc.Add (ns.core.Vector3D (0.0, 0.0, 0.0))
                positionAlloc.Add (ns.core.Vector3D (distance, 0.0, 0.0))
                mobility.SetPositionAllocator (positionAlloc)

                mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel")

                mobility.Install (wifiApNode)
                mobility.Install (wifiStaNode)

                # Internet stack
                stack = ns.internet.InternetStackHelper ()
                stack.Install (wifiApNode)
                stack.Install (wifiStaNode)

                address = ns.internet.Ipv4AddressHelper ()

                address.SetBase (ns.network.Ipv4Address ("192.168.1.0"), ns.network.Ipv4Mask ("255.255.255.0"))
                staNodeInterface = address.Assign (staDevice)
                apNodeInterface = address.Assign (apDevice)

                # Setting applications
                serverApp = ns.network.ApplicationContainer ()
                sinkApp = ns.network.ApplicationContainer ()
                if udp == "True":
                    # UDP flow
                    myServer=ns.applications.UdpServerHelper (9)
                    serverApp = myServer.Install (ns.network.NodeContainer (wifiStaNode.Get (0)))
                    serverApp.Start (ns.core.Seconds (0.0))
                    serverApp.Stop (ns.core.Seconds (simulationTime + 1))

                    myClient = ns.applications.UdpClientHelper (staNodeInterface.GetAddress (0), 9)
                    myClient.SetAttribute ("MaxPackets", ns.core.UintegerValue (4294967295))
                    myClient.SetAttribute ("Interval", ns.core.TimeValue (ns.core.Time ("0.00001"))) # packets/s
                    myClient.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))

                    clientApp = myClient.Install (ns.network.NodeContainer (wifiApNode.Get (0)))
                    clientApp.Start (ns.core.Seconds (1.0))
                    clientApp.Stop (ns.core.Seconds (simulationTime + 1))
                else:
                    port = 50000
                    apLocalAddress = ns.network.Address (ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), port))
                    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", apLocalAddress)
                    sinkApp = packetSinkHelper.Install (wifiStaNode.Get (0))

                    sinkApp.Start (ns.core.Seconds (0.0))
                    sinkApp.Stop (ns.core.Seconds (simulationTime + 1))

                    onoff = ns.applications.OnOffHelper ("ns3::TcpSocketFactory", ns.network.Ipv4Address.GetAny ())
                    onoff.SetAttribute ("OnTime",  ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
                    onoff.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
                    onoff.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))
                    onoff.SetAttribute ("DataRate", ns.network.DataRateValue (ns.network.DataRate (1000000000))) # bit/s
                    apps = ns.network.ApplicationContainer ()

                    remoteAddress = ns.network.AddressValue (ns.network.InetSocketAddress (staNodeInterface.GetAddress (0), port))
                    onoff.SetAttribute ("Remote", remoteAddress)
                    apps.Add (onoff.Install (wifiApNode.Get (0)))
                    apps.Start (ns.core.Seconds (1.0))
                    apps.Stop (ns.core.Seconds (simulationTime + 1))

                ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables ()

                ns.core.Simulator.Stop (ns.core.Seconds (simulationTime + 1))
                ns.core.Simulator.Run ()
                ns.core.Simulator.Destroy ()

                throughput = 0
                if udp == "True":
                    # UDP
                    totalPacketsThrough = serverApp.Get (0).GetReceived ()
                    throughput = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0) # Mbit/s

                else:
                    # TCP
                    totalPacketsThrough = sinkApp.Get (0).GetTotalRx ()
                    throughput = totalPacketsThrough * 8 / (simulationTime * 1000000.0)     # Mbit/s

                print i, "\t\t\t", j , " MHz\t\t\t", k , "\t\t\t" , throughput , " Mbit/s"
            j *= 2
    return 0
Example #9
0
def main(argv):
    payloadSize = 1472 # Bytes
    cmd = ns.core.CommandLine()
    cmd.simulationTime = 9  # seconds
    cmd.apVersion = "80211a"  #
    cmd.staVersion = "80211n_5GHZ"; #
    cmd.apRaa = "Minstrel"  #
    cmd.staRaa = "MinstrelHt"  #
    cmd.apHasTraffic = 0 # Enable/disable traffic on the AP
    cmd.staHasTraffic = 1 # Enable/disable traffic on the Station

    cmd.AddValue("simulationTime", "Simulation time in seconds")
    cmd.AddValue("apVersion", "The standard version used by the AP: 80211a, 80211b, 80211g, 80211_10MHZ, 80211_5MHZ, holland, 80211n_2_4GHZ, 80211n_5GHZ or 80211ac")
    cmd.AddValue("staVersion", "The standard version used by the station: 80211a, 80211b, 80211g, 80211_10MHZ, 80211_5MHZ, holland, 80211n_2_4GHZ, 80211n_5GHZ or 80211ac")
    cmd.AddValue("apRaa", "Rate adaptation algorithm used by the AP")
    cmd.AddValue("staRaa", "Rate adaptation algorithm used by the station")
    cmd.AddValue("apHasTraffic", "Enable/disable traffic on the AP")
    cmd.AddValue("staHasTraffic", "Enable/disable traffic on the station")
    cmd.Parse(sys.argv)


    simulationTime = float(cmd.simulationTime)
    apVersion: str = cmd.apVersion
    staVersion: str = cmd.staVersion
    apRaa: str = cmd.apRaa
    staRaa: str =  cmd.staRaa
    apHasTraffic = cmd.apHasTraffic
    staHasTraffic = cmd.staHasTraffic


    # Create nodes
    wifiStaNodes = ns.network.NodeContainer()
    wifiStaNodes.Create(1)
    wifiApNode = ns.network.NodeContainer()
    wifiApNode.Create(1)

    # Create wireless channel
    channel = ns.wifi.YansWifiChannelHelper.Default()
    phy = ns.wifi.YansWifiPhyHelper.Default()
    phy.SetChannel(channel.Create())  # wireless range limited to 5 meters!

    # Default IEEE 802.11n (2.4 GHz)
    mac = ns.wifi.HtWifiMacHelper.Default()
    wifi = ns.wifi.WifiHelper.Default()
    ssid = ns.wifi.Ssid("ns3")

    wifi.SetStandard(convertstringtostandard(staVersion))
    wifi.SetRemoteStationManager("ns3::" + staRaa + "WifiManager")

    # Install PHY and MAC

    mac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

    staDevices = ns.network.NetDeviceContainer()
    staDevices = wifi.Install(phy, mac, wifiStaNodes)

    mac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

    apDevice = ns.network.NetDeviceContainer()
    apDevice = wifi.Install(phy, mac, wifiApNode)

    #  Workaround needed as long as we do not fully support channel bonding
    if staVersion == "80211ac":
        ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue (20))
        ns.core.Config.Set("/NodeList/0/DeviceList/*/$ns3::WifiNetDevice/Phy/Frequency", ns.core.UintegerValue(5180))

    if apVersion =="80211ac":
        ns.core.Config.Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue(20))
        ns.core.Config.Set("/NodeList/0/DeviceList/*/$ns3::WifiNetDevice/Phy/Frequency", ns.core.UintegerValue(5180))

    # Mobility
    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()

    positionAlloc.Add(ns.core.Vector3D(0.0, 0.0, 0.0))
    positionAlloc.Add(ns.core.Vector3D(5.0, 0.0, 0.0))
    mobility.SetPositionAllocator(positionAlloc)

    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install(wifiApNode)
    mobility.Install(wifiStaNodes)

    # Internet stack
    stack = ns.internet.InternetStackHelper()
    stack.Install(wifiApNode)
    stack.Install(wifiStaNodes)

    address = ns.internet.Ipv4AddressHelper()
    address.SetBase(ns.network.Ipv4Address("192.168.1.0"), ns.network.Ipv4Mask("255.255.255.0"))

    staNodeInterface = ns.internet.Ipv4InterfaceContainer()
    staNodeInterface = address.Assign(staDevices)

    apNodeInterface = ns.internet.Ipv4InterfaceContainer()
    apNodeInterface = address.Assign(apDevice)

    # Setting applications

    apServer = ns.applications.UdpServerHelper(9) # AP server port
    apserverApp = apServer.Install(wifiStaNodes.Get(0))
    apserverApp.Start(ns.core.Seconds(0.0))
    apserverApp.Stop(ns.core.Seconds(simulationTime + 1))

    staServer = ns.applications.UdpServerHelper(5001) # Station server port
    staServerApp = staServer.Install(wifiStaNodes.Get(0))
    staServerApp.Start(ns.core.Seconds(0.0));
    staServerApp.Stop(ns.core.Seconds(simulationTime + 1));

    if apHasTraffic == 1:
        apClient = ns.applications.UdpClientHelper(staNodeInterface.GetAddress(0), 5001);
        apClient.SetAttribute("MaxPackets", ns.core.UintegerValue(4294967295))
        apClient.SetAttribute("Interval", ns.core.TimeValue(ns.core.Time("0.00001"))) # Packets / Second
        apClient.SetAttribute("PacketSize", ns.core.UintegerValue(payloadSize)) # Bytes
        apClientApp = apClient.Install(wifiApNode.Get(0))
        apClientApp.Start(ns.core.Seconds(1.0))
        apClientApp.Stop(ns.core.Seconds(simulationTime + 1))

    if staHasTraffic == 1:
        staClient = ns.applications.UdpClientHelper(apNodeInterface.GetAddress(0), 9)
        staClient.SetAttribute("MaxPackets", ns.core.UintegerValue(4294967295))
        staClient.SetAttribute("Interval", ns.core.TimeValue(ns.core.Time("0.00001"))) # Packets / Second
        staClient.SetAttribute("PacketSize", ns.core.UintegerValue(payloadSize)) # Bytes
        staClientApp = staClient.Install(wifiStaNodes.Get(0))
        staClientApp.Start(ns.core.Seconds(1.0))
        staClientApp.Stop(ns.core.Seconds(simulationTime + 1))

    # Populate routing table
    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

    # Set simulation time and launch simulation
    ns.core.Simulator.Stop(ns.core.Seconds(simulationTime + 1))
    ns.core.Simulator.Run()


    error = False

    if apHasTraffic == 1:
        rxBytes = payloadSize * (staServerApp.Get(0).GetReceived())
        throughput = (rxBytes * 8) / (simulationTime * 1000000.0); # Mbit / s
        print("AP Throughput:", throughput, "Mbit/s")

        if throughput == 0:
            error = True

    if staHasTraffic == 1:
        rxBytes = payloadSize * (apServerApp.Get(0)).GetReceived()
        throughput = (rxBytes * 8) / (simulationTime * 1000000.0) # Mbit / s
        print("STA Throughput:", throughput, "Mbit/s")

        if throughput == 0:
                error = True

        ns.core.Simulator.Destroy()
    if error == True:
        sys.exit(1)

    return 0
Example #10
0
def main(argv):
    cmd = ns.core.CommandLine ()
    cmd.simulationTime = 10 #seconds
    cmd.distance = 0 #meters

    cmd.AddValue ("simulationTime", "Simulation time in seconds")
    cmd.AddValue ("distance", "distance of the first sta from the AP")
    cmd.Parse (sys.argv)
    
    simulationTime = float(cmd.simulationTime)
    distance = float(cmd.distance)

    #Configuration arguments
    bandwidth = 40
    mcs=4
    gi = True
    expected_val= 25

    print "\tMCS's: \t Bandwidth:\t Troughput:\t   Delay:\t  Lost packets:\t  Transmited packets:\t Jitter:"
    channel = ns.wifi.YansWifiChannelHelper.Default ()
    phy = ns.wifi.YansWifiPhyHelper.Default ()
    wifi = ns.wifi.WifiHelper ()
    mac = ns.wifi.WifiMacHelper ()

    phy.SetChannel (channel.Create ())

    payloadSize = 1400 #bytes
    #ns.core.Config.SetDefault ("ns3::TcpSocket::SegmentSize", ns.core.UintegerValue (payloadSize))

    wifiStaNode = ns.network.NodeContainer ()
    wifiStaNode.Create (2)
    wifiApNode = ns.network.NodeContainer ()
    wifiApNode.Create (1)

    wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211ac)

    # Set guard interval
    phy.Set ("ShortGuardEnabled", ns.core.BooleanValue (gi))

    DataRate = "VhtMcs"+str(mcs)
    wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager","DataMode", ns.core.StringValue (DataRate),
                                    "ControlMode", ns.core.StringValue (DataRate))

    ssid = ns.wifi.Ssid ("wifi-80211ac")

    mac.SetType ("ns3::StaWifiMac",
                    "Ssid", ns.wifi.SsidValue (ssid),
                    "ActiveProbing", ns.core.BooleanValue (False))

    staDevice = wifi.Install (phy, mac, wifiStaNode)
    mac.SetType ("ns3::ApWifiMac",
                    "Ssid", ns.wifi.SsidValue (ssid))

    apDevice = wifi.Install (phy, mac, wifiApNode)

    # Set channel width
    ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue (bandwidth))

    # mobility
    mobility = ns.mobility.MobilityHelper ()
    positionAlloc = ns.mobility.ListPositionAllocator ()

    #distance_2 = distance * 2

    positionAlloc.Add (ns.core.Vector3D (0.0, 0.0, 0.0))
    positionAlloc.Add (ns.core.Vector3D (0.0, 0.0, 0.0))
    positionAlloc.Add (ns.core.Vector3D (distance, 0.0, 0.0))
    mobility.SetPositionAllocator (positionAlloc)

    mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel")

    mobility.Install (wifiApNode)
    mobility.Install (wifiStaNode)

    # Internet stack
    stack = ns.internet.InternetStackHelper ()
    stack.Install (wifiApNode)
    stack.Install (wifiStaNode)

    address = ns.internet.Ipv4AddressHelper ()

    address.SetBase (ns.network.Ipv4Address ("192.168.1.0"), ns.network.Ipv4Mask ("255.255.255.0"))
    staNodeInterface = address.Assign (staDevice)
    apNodeInterface = address.Assign (apDevice)

    # Setting applications
    serverApp = ns.network.ApplicationContainer ()
    sinkApp = ns.network.ApplicationContainer ()
    myServer=ns.applications.UdpServerHelper (9)
    serverApp = myServer.Install (ns.network.NodeContainer (wifiApNode))
    serverApp.Start (ns.core.Seconds (0.0))
    serverApp.Stop (ns.core.Seconds (simulationTime + 1))

    temp = float((expected_val*1000000)/(payloadSize*8))
    inter =float(1/temp)
    inter = format(inter,'f')

    
    tid=5

    socketAddress = ns.network.InetSocketAddress(staNodeInterface.GetAddress (1), 9)
    socketAddress.SetTos (tid<<5)


    myClient = ns.applications.OnOffHelper ("ns3::UdpSocketFactory", socketAddress)
    myClient.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ExponentialRandomVariable[Mean=0.976]"))
    myClient.SetAttribute("OffTime", ns.core.StringValue ("ns3::ExponentialRandomVariable[Mean=0.001]"))
    myClient.SetAttribute ("DataRate", ns.network.DataRateValue (ns.network.DataRate (expected_val*1000000))) # bit/s
    myClient.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))

    clientApp = myClient.Install (ns.network.NodeContainer (wifiStaNode))
    clientApp.Start (ns.core.Seconds (1.0))
    clientApp.Stop (ns.core.Seconds (simulationTime + 1))

    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables ()

    flowmonitor = ns.flow_monitor.FlowMonitorHelper ()
    monitor = flowmonitor.InstallAll ()

    monitor.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (1)))
    monitor.SetAttribute ("DelayBinWidth", ns.core.DoubleValue (0.001))
    monitor.SetAttribute ("JitterBinWidth", ns.core.DoubleValue (0.001))
    monitor.SetAttribute ("PacketSizeBinWidth", ns.core.DoubleValue (20))


    ns.core.Simulator.Stop (ns.core.Seconds (simulationTime+1))
    ns.core.Simulator.Run ()
    ns.core.Simulator.Destroy ()

    monitor.CheckForLostPackets ()
    classifier = ns.flow_monitor.Ipv4FlowClassifier ()
    classifier = flowmonitor.GetClassifier ()
    stats = monitor.GetFlowStats ()

    for flow_id, flow_stats in stats:
        t = classifier.FindFlow(flow_id)
        p_tran = flow_stats.txPackets
        p_rec = flow_stats.rxPackets
        delay_sum = flow_stats.delaySum
        jitter_sum = flow_stats.jitterSum
        delay = delay_sum / p_rec
        jitter = jitter_sum / (p_rec-1)
        lost_packets = flow_stats.lostPackets

        throughput = 0
        #totalPacketsThrough = serverApp.Get (0).GetReceived ()
        totalPacketsThrough = p_rec
        throughput = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0)    # Mbit/s

        print "Sta",flow_id,"->",mcs,"\t  ",bandwidth,"MHz\t",throughput,"Mbit/s\t ",delay,"\t\t",lost_packets,"\t\t",p_tran,"\t\t",jitter
        #print "FlowID:",flow_id,"Source Addr:",t.sourceAddress,"Destination Addr:",t.destinationAddress ##Debugowy wpis w celu identyfikacji ruchu
    
    #Stary sposob wyliczania, teraz uzywamy flowMonitora w calosci aby latwiej bylo oddzialac przeplywy

    #throughput = 0
    ## UDP
    #totalPacketsThrough = serverApp.Get (0).GetReceived ()
    #throughput = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0)    # Mbit/s
    
    #print mcs,"\t  ",bandwidth,"MHz\t",throughput,"Mbit/s\t ",delay,"\t\t",lost_packets,"\t\t",p_tran,"\t\t",jitter
    return 0
Example #11
0
def main(argv):
    cmd = ns.core.CommandLine ()
    cmd.udp = "True"
    cmd.useRts = "False"
    cmd.useExtendedBlockAck = "False";
    cmd.simulationTime = 10 # seconds
    cmd.distance = 1.0 # meters
    cmd.frequency = 5.0 # whether 2.4 or 5.0 GHz
    cmd.mcs = -1 # -1 indicates an unset value
    cmd.minExpectedThroughput = 0
    cmd.maxExpectedThroughput = 0
    cmd.minMcs = 0
    cmd.maxMcs = 11

    cmd.AddValue ("frequency", "Whether working in the 2.4 or 5.0 GHz band (other values gets rejected)")
    cmd.AddValue ("distance", "Distance in meters between the station and the access point")
    cmd.AddValue ("simulationTime", "Simulation time in seconds")
    cmd.AddValue ("udp", "UDP if set to 1, TCP otherwise")
    cmd.AddValue ("useExtendedBlockAck", "Enable/disable use of extended BACK")   
    cmd.AddValue ("mcs", "if set, limit testing to a specific MCS (0-11)")
    cmd.AddValue ("minExpectedThroughput", "if set, simulation fails if the lowest throughput is below this value")
    cmd.AddValue ("maxExpectedThroughput", "if set, simulation fails if the highest throughput is above this value")
    cmd.Parse (sys.argv)

    udp = cmd.udp
    useRts = cmd.useRts
    simulationTime = float(cmd.simulationTime)
    distance = float(cmd.distance)
    frequency = double(cmd.frequency)
    mcs = int(cmd.mcs)
    minExpectedThroughput = double(cmd.minExpectedThroughput)
    maxExpectedThroughput = double(cmd.maxExpectedThroughput)

    if useRts == "True":
        ns.core.Config.SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", ns.core.StringValue ("0"))

 
    for l in range(0,12):
        prevThroughput[l] = 0

    print "MCS value" , "\t\t", "Channel width", "\t\t", "short GI","\t\t","Throughput" ,'\n'

    minMcs = int (cmd.minMcs)
    maxMcs = int (cmd.maxMcs)

    if mcs >= 0 and mcs <= 11:
        minMcs = mcs
        maxMcs = mcs

    ChannelWidth = 20
    gi = 3200
    for mcs in range(minMcs, maxMcs+1): # MCS
        index = 0
        previous = 0
        if frequency == 2.4:
            maxChannelWidth = 40
        else:
            maxChannelWidth = 160
        while ChannelWidth <= maxChannelWidth: #MHz
            while gi >= 800: #Nanoseconds
                if udp == "True": # 1500 byte IP packet
                    payloadSize = 1472 # bytes
                else:
                    payloadSize = 1448 # bytes
                    ns.core.Config.SetDefault ("ns3::TcpSocket::SegmentSize", ns.core.UintegerValue (payloadSize))

                wifiStaNode = ns.network.NodeContainer ()
                wifiStaNode.Create (1)
                wifiApNode = ns.network.NodeContainer ()
                wifiApNode.Create (1)

                channel = ns.wifi.YansWifiChannelHelper.Default ()
                phy = ns.wifi.YansWifiPhyHelper.Default ()
                phy.SetChannel (channel.Create ())

                # Set guard interval
                #phy.Set ("GuardInterval", ns.core.TimeValue (ns.core.NanoSeconds(gi)))


                mac = ns.wifi.WifiMacHelper.Default ()
                wifi = ns.wifi.WifiHelper.Default ()

                if frequency == 5.0:
                    wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211ax_5GHZ)
                elif frequency == 2.4:
                    wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211ax_2_4GHZ)
                    ns.core.Config.SetDefault ("ns3::LogDistancePropagationLossModel::ReferenceLoss", ns.core.DoubleValue (40.046))
                else:
                    print("Wrong frequency value!")
                    return 0

                
                mcsstr = str(mcs)
                oss = "HeMcs" + mcsstr 
                wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue (oss),"ControlMode", ns.core.StringValue (oss))

                ssid = ns.wifi.Ssid ("ns3-80211ax")
                mac.SetType ("ns3::StaWifiMac","Ssid", ns.wifi.SsidValue (ssid))


                staDevice = wifi.Install (phy, mac, wifiStaNode)

                mac.SetType ("ns3::ApWifiMac","EnableBeaconJitter", BooleanValue (false),
                             "Ssid", ns.wifi.SsidValue (ssid))

                apDevice = wifi.Install (phy, mac, wifiApNode)

                # Set channel width, guard interval and MPDU buffer size
                ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue (channelWidth))
                ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/HeConfiguration/GuardInterval", ns.core.TimeValue (gi))
                if useExtendedBlockAck == "True":
                    ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/HeConfiguration/MpduBufferSize", ns.core.UintegerValue (256))
                else:
                    ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/HeConfiguration/MpduBufferSize", ns.core.UintegerValue (64))
                


                # mobility
                mobility = ns.mobility.MobilityHelper ()
                positionAlloc = ns.mobility.ListPositionAllocator ()
                positionAlloc.Add (ns.core.Vector (0.0, 0.0, 0.0))
                positionAlloc.Add (ns.core.Vector (distance, 0.0, 0.0))
                mobility.SetPositionAllocator (positionAlloc)

                mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel")

                mobility.Install (wifiApNode)
                mobility.Install (wifiStaNode)

                # Internet stack
                stack = ns.internet.InternetStackHelper ()
                stack.Install (wifiApNode)
                stack.Install (wifiStaNode)

                address = ns.internet.Ipv4AddressHelper ()

                address.SetBase (ns.network.Ipv4Address ("192.168.1.0"), ns.network.Ipv4Mask ("255.255.255.0"))

                staNodeInterface = address.Assign (staDevice)
                apNodeInterface = address.Assign (apDevice)

                # Setting applications
                serverApp = ns.network.ApplicationContainer ()
                if udp == "True": # UDP flow
                    port = 9
                    server = ns.applications.UdpServerHelper (port)
                    serverApp = server.Install (ns.network.NodeContainer (wifiStaNode.Get (0)))
                    serverApp.Start (ns.core.Seconds (0.0))
                    serverApp.Stop (ns.core.Seconds (simulationTime + 1))

                    client = ns.applications.UdpClientHelper (staNodeInterface.GetAddress (0), port)
                    client.SetAttribute ("MaxPackets", ns.core.UintegerValue (4294967295))
                    client.SetAttribute ("Interval", ns.core.TimeValue (ns.core.Time ("0.00001")))  # packets/s
                    client.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))

                    clientApp = client.Install (ns.network.NodeContainer (wifiApNode.Get (0)))
                    clientApp.Start (ns.core.Seconds (1.0))
                    clientApp.Stop (ns.core.Seconds (simulationTime + 1))
                else: # TCP flow
                    port = 50000
                    localAddress = ns.network.Address (ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), port))
                    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", localAddress)
                    serverApp = packetSinkHelper.Install (wifiStaNode.Get (0))
                    serverApp.Start (ns.core.Seconds (0.0))
                    serverApp.Stop (ns.core.Seconds (simulationTime + 1))

                    onoff = ns.applications.OnOffHelper ("ns3::TcpSocketFactory", ns.network.Ipv4Address.GetAny ())
                    onoff.SetAttribute ("OnTime",  ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
                    onoff.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
                    onoff.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))
                    onoff.SetAttribute ("DataRate", ns.network.DataRateValue (ns.network.DataRate (1000000000))) # bit/s
                    remoteAddress = ns.network.AddressValue (ns.network.InetSocketAddress (staNodeInterface.GetAddress (0), port))
                    onoff.SetAttribute ("Remote", remoteAddress)

                    apps = ns.network.ApplicationContainer ()
                    apps.Add (onoff.Install (wifiApNode.Get (0)))
                    apps.Start (ns.core.Seconds (1.0))
                    apps.Stop (ns.core.Seconds (simulationTime + 1))

                ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables ()

                ns.core.Simulator.Stop (ns.core.Seconds (simulationTime + 1))
                ns.core.Simulator.Run ()
                

                rxBytes = 0
                if udp == "True":
                    # UDP
                    rxBytes = payloadSize * ((serverApp.Get (0)).GetReceived ())
                else:
                    # TCP
                    rxBytes = (serverApp.Get (0)).GetTotalRx ()

                throughput = (rxBytes * 8) / (simulationTime * 1000000.0)
                ns.core.Simulator.Destroy ()
                print mcs , "\t\t\t" , channelWidth , "MHz\t\t\t" , gi , "ns\t\t\t" , throughput , " Mbit/s"

                # test first element
                if mcs == 0 and ChannelWidth == 20 and gi == 3200:
                    if throughput <minExpectedThroughput:
                        print("Obtained throughput " , throughput , " is not expected!")
                        sys.exit(1)

                # test last element
                if mcs == 11 and ChannelWidth == 160 and  gi == 800:
                    if maxExpectedThroughput > 0  and throughput > maxExpectedThroughput:
                        print ("Obtained throughput " , throughput , " is not expected!")
                        sys.exit(1)

                # test previous throughput is smaller (for the same mcs)
                if throughput > previous:
                    previous = throughput
                else:
                    print ("Obtained throughput " , throughput , " is not expected!")
                    sys.exit(1)

                # test previous throughput is smaller (for the same channel width and GI)
                if throughput > prevThroughput[index]:
                    prevThroughput[index] = throughput
                else:
                    print ("Obtained throughput " , throughput , " is not expected!")
                    sys.exit(1)

                index = index + 1
                gi = gi/2
            ChannelWidth = ChannelWidth * 2

    return 0
Example #12
0
def experiment(enableCtsRts):

    # 0. Enable or disable CTS/RTS
    ctsThr = 100 if enableCtsRts else 2200
    ns.core.Config.SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", ns.core.UintegerValue (ctsThr))

    # 1. Create 3 nodes
    nodes = ns.network.NodeContainer ()
    nodes.Create (3)

    # 2. Place nodes somehow, this is required by every wireless simulation
    i = 0
    while i < 3:
        nodes.Get (i).AggregateObject (ns.mobility.ConstantPositionMobilityModel ())
        i += 1

    # 3. Create propagation loss matrix
    lossModel = ns.propagation.MatrixPropagationLossModel ()
    lossModel.SetDefaultLoss (200) #set default loss to 200 dB (no link)
    lossModel.SetLoss (nodes.Get (0).GetObject (ns.mobility.MobilityModel.GetTypeId ()), nodes.Get (1).GetObject (ns.mobility.MobilityModel.GetTypeId ()), 50)
    lossModel.SetLoss (nodes.Get (2).GetObject (ns.mobility.MobilityModel.GetTypeId ()), nodes.Get (1).GetObject (ns.mobility.MobilityModel.GetTypeId ()), 50)

    # 4. Create & setup wifi channel
    wifiChannel = ns.wifi.YansWifiChannel ()
    wifiChannel.SetPropagationLossModel (lossModel)
    wifiChannel.SetPropagationDelayModel (ns.propagation.ConstantSpeedPropagationDelayModel ())

    # 5. Install wireless devices
    wifi = ns.wifi.WifiHelper ()
    wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211b)
    wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                  "DataMode", ns.core.StringValue ("DsssRate2Mbps"),
                                  "ControlMode", ns.core.StringValue ("DsssRate1Mbps"))

    wifiPhy = ns.wifi.YansWifiPhyHelper.Default ()
    wifiPhy.SetChannel (wifiChannel)
    wifiMac = ns.wifi.NqosWifiMacHelper.Default ()
    wifiMac.SetType ("ns3::AdhocWifiMac")  # use ad-hoc MAC
    devices = wifi.Install (wifiPhy,wifiMac,nodes)

    # uncomment the following to have athstats output
    # athstats=ns3.AthstatsHelper ()
    # athstats.EnableAthstats ("rtscts-athstats-node-py" if enableCtsRts else "basic-athstats-node-py", nodes)

    # uncomment the following to have pcap output
    # wifiPhy.EnablePcap ("rtscts-pcap-node-py" if enableCtsRts else "basic-pcap-node-py",nodes)

    # 6. Install TCP/IP stack & assign IP addresses
    internet = ns.internet.InternetStackHelper ()
    internet.Install (nodes)
    ipv4 = ns.internet.Ipv4AddressHelper ()
    ipv4.SetBase (ns.network.Ipv4Address ("10.0.0.0"), ns.network.Ipv4Mask ("255.0.0.0"))
    ipv4.Assign (devices)

    # 7. Install applications: two CBR streams each saturating the channel
    cbrApps = ns.network.ApplicationContainer ()
    cbrPort = 12345
    onOffHelper = ns.applications.OnOffHelper ("ns3::UdpSocketFactory", ns.network.InetSocketAddress (ns.network.Ipv4Address ("10.0.0.2"), cbrPort))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (1400))
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))

    # flow 1:  node 0 -> node 1
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("3000000bps"))
    onOffHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (1.000000)))
    cbrApps.Add (onOffHelper.Install (nodes.Get (0)))

    # flow 2:  node 2 -> node 1
    # \internal
    # The slightly different start times and data rates are a workaround
    # for \bugid{388} and \bugid{912}
    #
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("3001100bps"))
    onOffHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (1.001)))
    cbrApps.Add (onOffHelper.Install (nodes.Get (2)))

    # \internal
    # We also use separate UDP applications that will send a single
    # packet before the CBR flows start. 
    # This is a workaround for the lack of perfect ARP, see \bugid{187}
    #
    echoPort = 9
    echoClientHelper = ns.applications.UdpEchoClientHelper (ns.network.Ipv4Address ("10.0.0.2"), echoPort)
    echoClientHelper.SetAttribute ("MaxPackets", ns.core.UintegerValue (1))
    echoClientHelper.SetAttribute ("Interval", ns.core.TimeValue (ns.core.Seconds (0.1)))
    echoClientHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (10))
    pingApps = ns.network.ApplicationContainer ()

    # again using different start times to workaround Bug 388 and Bug 912
    echoClientHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (0.001)))
    pingApps.Add (echoClientHelper.Install(nodes.Get (0)))
    echoClientHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (0.006)))
    pingApps.Add (echoClientHelper.Install (nodes.Get (2)))

    # 8. Install FlowMonitor on all nodes
    flowmon = ns.flow_monitor.FlowMonitorHelper ()
    monitor = flowmon.InstallAll ()

    # 9. Run simulation for 10 seconds
    ns.core.Simulator.Stop (ns.core.Seconds (10))
    ns.core.Simulator.Run ()

    # 10. Print per flow statistics
    monitor.CheckForLostPackets ()
    classifier = ns.flow_monitor.Ipv4FlowClassifier ()
    classifier = flowmon.GetClassifier ()
    stats = monitor.GetFlowStats ()
    for flow_id, flow_stats in monitor.GetFlowStats ():
        # first 2 FlowIds are for ECHO apps, we don't want to display them

        # Duration for throughput measurement is 9.0 seconds, since
        # StartTime of the OnOffApplication is at about "second 1"
        # and
        # Simulator::Stops at "second 10".
        t = classifier.FindFlow(flow_id)
        if flow_id > 2:
            print "FlowID %i (%s -> %s)" % \
            (flow_id-2, t.sourceAddress, t.destinationAddress)
            print >> sys.stdout, "  Tx Packets: ", flow_stats.txPackets
            print >> sys.stdout, "  Tx Bytes: ", flow_stats.txBytes
            print >> sys.stdout, "  TxOffered:  ", flow_stats.txBytes * 8.0 / 9.0 / 1000 / 1000  , " Mbps"
            print >> sys.stdout, "  Rx Packets: ", flow_stats.rxPackets
            print >> sys.stdout, "  Rx Bytes: ", flow_stats.rxBytes
            print >> sys.stdout, "  Throughput: ", flow_stats.rxBytes * 8.0 / 9.0 / 1000 / 1000  , " Mbps"

    # 11. Cleanup
    ns.core.Simulator.Destroy ()
Example #13
0
def main(argv):

    ns.core.LogComponentEnable("UdpEchoClientApplication",
                               ns.core.LOG_LEVEL_INFO)
    ns.core.LogComponentEnable("UdpEchoServerApplication",
                               ns.core.LOG_LEVEL_INFO)

    # define a node container
    stations = ns.network.NodeContainer()

    # create 3 nodes
    stations.Create(3)

    # chose the element at 0 to be the AP of the wifi network
    ap = stations.Get(0)

    # contruct the wifi devices and the intercommunication channel between these wifi nodes
    phy = ns.wifi.YansWifiPhyHelper.Default()
    channel = ns.wifi.YansWifiChannelHelper.Default()
    phy.SetChannel(channel.Create())

    # wifi helper
    wifi = ns.wifi.WifiHelper.Default()
    wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211b)
    #wifi.SetRemoteStationManager("ns3::ArfWifiManager")
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue("DsssRate5_5Mbps"))
    #	"DataMode", ns.core.StringValue("wifia-54mbs"))

    # SSID of the network
    ssid = ns.wifi.Ssid("wifi-home")

    # wifi Mac
    mac = ns.wifi.NqosWifiMacHelper.Default()
    mac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                "ActiveProbing", ns.core.BooleanValue(False))

    # network device container
    stationDevices = wifi.Install(phy, mac, stations)

    # configuring type for the AP
    mac.SetType("ns3::ApWifiMac", "Ssid",
                ns.wifi.SsidValue(ssid), "BeaconGeneration",
                ns.core.BooleanValue(True), "BeaconInterval",
                ns.core.TimeValue(ns.core.Seconds(2.5)))
    apDevices = wifi.Install(phy, mac, ap)

    # mobility, I dont know that this does
    mobility = ns.mobility.MobilityHelper()
    mobility.Install(stations)
    ns.core.Simulator.Schedule(ns.core.Seconds(1.0), AdvancePosition, ap)

    #print help(ns.internet.InternetStackHelper)
    stackHelper = ns.internet.InternetStackHelper()
    stack = stackHelper.Install(stations)

    #Ipv4 address container
    address = ns.internet.Ipv4AddressHelper()
    address.SetBase(ns.network.Ipv4Address("10.1.1.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    stInterfaces = address.Assign(stationDevices)
    apInterfaces = address.Assign(apDevices)

    device = apDevices.Get(ap.GetId())

    echoServer = ns.applications.UdpEchoServerHelper(9)

    serverApps = echoServer.Install(stations.Get(1))
    serverApps.Start(ns.core.Seconds(1.0))
    serverApps.Stop(ns.core.Seconds(10.0))

    echoClient = ns.applications.UdpEchoClientHelper(
        stInterfaces.GetAddress(1), 9)
    echoClient.SetAttribute("MaxPackets", ns.core.UintegerValue(1))
    echoClient.SetAttribute("Interval",
                            ns.core.TimeValue(ns.core.Seconds(1.0)))
    echoClient.SetAttribute("PacketSize", ns.core.UintegerValue(1024))

    clientApps = echoClient.Install(stations.Get(2))
    clientApps.Start(ns.core.Seconds(1.0))
    clientApps.Stop(ns.core.Seconds(2.0))

    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()

    return 0
Example #14
0
def main(argv):
    cmd = ns.core.CommandLine ()
    cmd.simulationTime = 10 #seconds
    cmd.distance = 0.0 #meters
    
    simulationTime = float(cmd.simulationTime)
    distance = float(cmd.distance)
    Sta_Nodes = 5
    #Configuration arguments
    udp = True #If false, TCP will be used by default
    bandwidth = 20
    ofdm =["OfdmRate9Mbps", "OfdmRate24Mbps", "OfdmRate48Mbps"]
    expected_val = [3.8,4.9,6.5]
    print "OFDM Rate: \t Troughput:\t\t  Delay:\t Lost packets:\tTransmited Packets:"
    for count, a in enumerate(ofdm):
      
        channel = ns.wifi.YansWifiChannelHelper.Default ()
        phy = ns.wifi.YansWifiPhyHelper.Default ()
        wifi = ns.wifi.WifiHelper ()
        mac = ns.wifi.NqosWifiMacHelper.Default ()

        phy.SetChannel (channel.Create ())
        
        if udp == False:
            payloadSize = 1448  #bytes
            ns.core.Config.SetDefault ("ns3::TcpSocket::SegmentSize", ns.core.UintegerValue (payloadSize))
        elif udp == True:
            payloadSize = 1472

        wifiStaNode = ns.network.NodeContainer ()
        wifiStaNode.Create (Sta_Nodes)
        wifiApNode = ns.network.NodeContainer ()
        wifiApNode.Create (1)
        
        wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211a)

        wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager","DataMode", ns.core.StringValue (a),
                                    "ControlMode", ns.core.StringValue (a))

        ssid = ns.wifi.Ssid ("wifi-80211a")

        mac.SetType ("ns3::StaWifiMac",
                        "Ssid", ns.wifi.SsidValue (ssid),
                        "ActiveProbing", ns.core.BooleanValue (False))

        staDevice = wifi.Install (phy, mac, wifiStaNode)

        mac.SetType ("ns3::ApWifiMac",
                        "Ssid", ns.wifi.SsidValue (ssid))

        apDevice = wifi.Install (phy, mac, wifiApNode)

        # Set channel width
        ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue (bandwidth))

        # mobility
        mobility = ns.mobility.MobilityHelper ()
        positionAlloc = ns.mobility.ListPositionAllocator ()

        positionAlloc.Add (ns.core.Vector3D (0.0, 0.0, 0.0))
        positionAlloc.Add (ns.core.Vector3D (distance, 0.0, 0.0))
        positionAlloc.Add (ns.core.Vector3D (distance, 0.0, 0.0))
        
        mobility.SetPositionAllocator (positionAlloc)

        mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel")

        mobility.Install (wifiApNode)
        mobility.Install (wifiStaNode)

        # Internet stack
        stack = ns.internet.InternetStackHelper ()
        stack.Install (wifiApNode)
        stack.Install (wifiStaNode)

        address = ns.internet.Ipv4AddressHelper ()
        address.SetBase (ns.network.Ipv4Address ("192.168.1.0"), ns.network.Ipv4Mask ("255.255.255.0"))
        staNodeInterface = ns.internet.Ipv4InterfaceContainer ()
        staNodeInterface = address.Assign (staDevice)
        apNodeInterface = ns.internet.Ipv4InterfaceContainer ()
        apNodeInterface = address.Assign (apDevice)

        #Setting applications
        serverApp = ns.network.ApplicationContainer ()
        sinkApp = ns.network.ApplicationContainer ()

        if udp == False:
            # TCP flow
            port = 50000
            apLocalAddress = ns.network.Address (ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), port))
            packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", apLocalAddress)
            sinkApp = packetSinkHelper.Install (wifiApNode.Get (0))

            sinkApp.Start (ns.core.Seconds (0.0))
            sinkApp.Stop (ns.core.Seconds (simulationTime + 1))

            onoff = ns.applications.OnOffHelper ("ns3::TcpSocketFactory", ns.network.Ipv4Address.GetAny ())
            onoff.SetAttribute ("OnTime",  ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
            onoff.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
            onoff.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))
            temp = int(expected_val2[count]*1000000)
            onoff.SetAttribute ("DataRate", ns.network.DataRateValue (ns.network.DataRate (temp))) # bit/s
            apps = ns.network.ApplicationContainer ()

            remoteAddress = ns.network.AddressValue (ns.network.InetSocketAddress (apNodeInterface.GetAddress (0), port))
            onoff.SetAttribute ("Remote", remoteAddress)
            apps.Add (onoff.Install (wifiStaNode))
            apps.Start (ns.core.Seconds (1.0))
            apps.Stop (ns.core.Seconds (simulationTime + 1))
        elif udp == True:
            # UDP flow
            myServer=ns.applications.UdpServerHelper (9)
            serverApp = myServer.Install (wifiApNode)
            serverApp.Start (ns.core.Seconds (0.0))
            serverApp.Stop (ns.core.Seconds (simulationTime + 1))
            
            temp = float((expected_val[count]*1000000)/(payloadSize*8))
            inter =float(1/temp)
            #print(expected_val[count], inter)
            myClient = ns.applications.UdpClientHelper (apNodeInterface.GetAddress (0), 9)
            myClient.SetAttribute ("MaxPackets", ns.core.UintegerValue (4294967295))
            myClient.SetAttribute ("Interval", ns.core.TimeValue (ns.core.Time (str(inter)))) # packets/s
            myClient.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))

            clientApp = myClient.Install (wifiStaNode)
            clientApp.Start (ns.core.Seconds (1.0))
            clientApp.Stop (ns.core.Seconds (simulationTime + 1))

        ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables ()

        flowmonitor = ns.flow_monitor.FlowMonitorHelper ()
        monitor = flowmonitor.InstallAll ()

        monitor.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (5)))
        monitor.SetAttribute ("DelayBinWidth", ns.core.DoubleValue (0.001))
        monitor.SetAttribute ("JitterBinWidth", ns.core.DoubleValue (0.001))
        monitor.SetAttribute ("PacketSizeBinWidth", ns.core.DoubleValue (20))
        
        
        ns.core.Simulator.Stop (ns.core.Seconds (simulationTime))
        ns.core.Simulator.Run ()
        ns.core.Simulator.Destroy ()

        monitor.CheckForLostPackets ()
        classifier = ns.flow_monitor.Ipv4FlowClassifier ()
        classifier = flowmonitor.GetClassifier ()
        stats = monitor.GetFlowStats ()
        
        for flow_id, flow_stats in stats:
            t = classifier.FindFlow(flow_id)
            p_tran = flow_stats.txPackets
            p_rec = flow_stats.rxPackets
            delay_sum = flow_stats.delaySum
            delay = delay_sum / p_rec
            lost_packets = flow_stats.lostPackets
        throughput = 0
        if udp == False:
            # TCP
            totalPacketsThrough = sinkApp.Get (0).GetTotalRx ()
            throughput = totalPacketsThrough * 8 / (simulationTime * 1000000.0) # Mbit/s
        elif udp == True:
            # UDP
            totalPacketsThrough = serverApp.Get (0).GetReceived ()
            throughput = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0) # Mbit/s
            
        print a,"\t",throughput,"Mbit/s\t",delay,"\t\t",lost_packets,"\t\t ",p_tran
    
    return 0
def main (argv):
	cmd = ns.core.CommandLine ()
	cmd.payloadSize = 1472 # bytes
	cmd.simulationTime = 10 # seconds
	cmd.nMpdus = 1
	cmd.maxAmpduSize = 0
	cmd.enableRts = "False"
	cmd.minExpectedThroughput = 0
	cmd.maxExpectedThroughput = 0
    	
	cmd.AddValue ("nMpdus", "Number of aggregated MPDUs")
	cmd.AddValue ("payloadSize", "Payload size in bytes")
	cmd.AddValue ("enableRts", "Enable RTS/CTS")
	cmd.AddValue ("simulationTime", "Simulation time in seconds")
	cmd.AddValue ("minExpectedThroughput", "if set, simulation fails if the lowest throughput is below this value")
	cmd.AddValue ("maxExpectedThroughput", "if set, simulation fails if the highest throughput is above this value")
	cmd.Parse (sys.argv)

	payloadSize = int (cmd.payloadSize)
	simulationTime = float (cmd.simulationTime)
	nMpdus = int (cmd.nMpdus)
	maxAmpduSize = int (cmd.maxAmpduSize)
	enableRts = cmd.enableRts
	minExpectedThroughput = cmd.minExpectedThroughput
	maxExpectedThroughput = cmd.maxExpectedThroughput
	
	if enableRts == "False":
		ns.core.Config.SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", ns.core.StringValue ("999999"))	
	else:
		ns.core.Config.SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", ns.core.StringValue ("0"))    
     
  	ns.core.Config.SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", ns.core.StringValue ("990000"))

  	# Set the maximum size for A-MPDU with regards to the payload size
  	maxAmpduSize = nMpdus * (payloadSize + 200)

  	# Set the maximum wireless range to 5 meters in order to reproduce a hidden nodes scenario, i.e. the distance between hidden stations is larger 	than 5 meters
  	ns.core.Config.SetDefault ("ns3::RangePropagationLossModel::MaxRange", ns.core.DoubleValue (5))

	wifiStaNodes = ns.network.NodeContainer ()
	staDevices.Create (2)
	wifiApNode = ns.network.NodeContainer ()
	wifiApNode.Create (1)
	
	channel = ns.wifi.YansWifiChannelHelper.Default ()
	channel.AddPropagationLoss ("ns3::RangePropagationLossModel") # wireless range limited to 5 meters!

	phy = ns.wifi.YansWifiPhyHelper.Default ()
	phy.SetPcapDataLinkType (ns.wifi.YansWifiPhyHelper.DLT_IEEE802_11_RADIO)
	phy.SetChannel (channel.Create ())

	wifi = ns.wifi.WifiHelper.Default ()
	wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211n_5GHZ)
	wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue ("HtMcs7"), "ControlMode", ns.core.StringValue ("HtMcs0"))
	mac = ns.wifi.HtWifiMacHelper.Default ()

	ssid = ns.wifi.Ssid ("simple-mpdu-aggregation")
	mac.SetType ("ns3::StaWifiMac",
				"Ssid", ns.wifi.SsidValue (ssid),
				"ActiveProbing", ns.core.BooleanValue (False),
				"BE_MaxAmpduSize", ns.core.UintegerValue (maxAmpduSize))

	staDevices = ns.network.NetDeviceContainer ()
	staDevices = wifi.Install (phy, mac, wifiStaNodes)

	mac.SetType ("ns3::ApWifiMac",
				"Ssid", ns.wifi.SsidValue (ssid),
				"EnableBeaconJitter", ns.core.BooleanValue (False),
				"BE_MaxAmpduSize", ns.core.UintegerValue (maxAmpduSize))

	apDevice = ns.network.NetDeviceContainer ()
 	apDevice = wifi.Install (phy, mac, wifiApNode)

	mobility = ns.mobility.MobilityHelper ()
	positionAlloc = ns.mobility.ListPositionAllocator ()

	positionAlloc.Add (ns.core.Vector3D (5.0, 0.0, 0.0))
	positionAlloc.Add (ns.core.Vector3D (0.0, 0.0, 0.0))
	positionAlloc.Add (ns.core.Vector3D (10.0, 0.0, 0.0))
	mobility.SetPositionAllocator (positionAlloc)

	mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel")
	mobility.Install (wifiApNode)
	mobility.Install (wifiStaNodes)

	stack = ns.internet.InternetStackHelper ()
	stack.Install (wifiApNode)
	stack.Install (wifiStaNodes)

	address = ns.internet.Ipv4AddressHelper ()
	address.SetBase (ns.network.Ipv4Address ("192.168.1.0"), ns.network.Ipv4Mask ("255.255.255.0"))
	StaInterface = ns.internet.Ipv4InterfaceContainer ()
	StaInterface = address.Assign (staDevices)
	ApInterface = ns.internet.Ipv4InterfaceContainer ()
	ApInterface = address.Assign (apDevice)

	port = 9 
	server = ns.applications.UdpServerHelper (port)
	serverApp = server.Install (wifiApNode)
	serverApp.Start (ns.core.Seconds (0.0))
	serverApp.Stop (ns.core.Seconds (simulationTime + 1))
      
	client = ns.applications.UdpClientHelper (ApInterface.GetAddress (0), port)
	client.SetAttribute ("MaxPackets", ns.core.UintegerValue (4294967295))
	client.SetAttribute ("Interval", ns.core.TimeValue (ns.core.Time ("0.00002")))
	client.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))
  
	clientApp1 = client.Install (wifiStaNodes)
	clientApp1.Start (ns.core.Seconds (1.0))
	clientApp1.Stop (ns.core.Seconds (simulationTime + 1))
  
	phy.EnablePcap ("SimpleHtHiddenStations_py_Ap", apDevice.Get (0))
	phy.EnablePcap ("SimpleHtHiddenStations_py_Sta1", staDevices.Get (0))
	phy.EnablePcap ("SimpleHtHiddenStations_py_Sta2", staDevices.Get (1))
      
	ns.core.Simulator.Stop (ns.core.Seconds (simulationTime + 1))

	ns.core.Simulator.Run ()
	ns.core.Simulator.Destroy ()
      
	totalPacketsThrough = serverApp.Get (0).GetReceived ()
	throughput = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0)
	print "Throughput:", throughput,"Mbit/s"
  
	if (throughput < minExpectedThroughput or (maxExpectedThroughput > 0 and throughput > maxExpectedThroughput)):
		print "Obtained throughput:", throughput,"is not in the expected boundaries!",'\n'
		exit (1)

	return 0
def main(argv):
    simulationTime = 40  #seconds
    distance = 0.0  #meters
    simulationTime = float(simulationTime)
    distance = float(distance)

    #Configuration arguments
    bandwidth = 40
    mcs = 3
    gi = False
    expected_val = 54

    channel = ns.wifi.YansWifiChannelHelper.Default()
    phy = ns.wifi.YansWifiPhyHelper.Default()
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.WifiMacHelper()

    phy.SetPcapDataLinkType(ns.wifi.WifiPhyHelper.DLT_IEEE802_11_RADIO)
    phy.SetChannel(channel.Create())

    wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211ac)

    wifiStaNode = ns.network.NodeContainer()
    wifiStaNode.Create(1)
    wifiApNode = ns.network.NodeContainer()
    wifiApNode.Create(1)

    # Set guard interval
    #phy.Set ("ShortGuardEnabled", ns.core.BooleanValue (gi))

    #mac = ns.wifi.VhtWifiMacHelper.Default ()
    DataRate = "VhtMcs" + str(mcs)

    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue(DataRate), "ControlMode",
                                 ns.core.StringValue(DataRate))

    ssid = ns.wifi.Ssid("wifi-80211ac")

    mac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                "QosSupported", ns.core.BooleanValue(True), "ActiveProbing",
                ns.core.BooleanValue(False), "BE_MaxAmsduSize",
                ns.core.UintegerValue(0), "BK_MaxAmsduSize",
                ns.core.UintegerValue(0), "VI_MaxAmsduSize",
                ns.core.UintegerValue(0), "VO_MaxAmsduSize",
                ns.core.UintegerValue(0), "BE_MaxAmpduSize",
                ns.core.UintegerValue(65535), "BK_MaxAmpduSize",
                ns.core.UintegerValue(0), "VI_MaxAmpduSize",
                ns.core.UintegerValue(65535), "VO_MaxAmpduSize",
                ns.core.UintegerValue(0))  #Default settings

    #mac.SetType ("ns3::StaWifiMac", "QosSupported", ns.core.BooleanValue (True), "Ssid", ns.wifi.SsidValue (ssid))

    staDevice = wifi.Install(phy, mac, wifiStaNode.Get(0))

    mac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                "QosSupported", ns.core.BooleanValue(True), "BE_MaxAmsduSize",
                ns.core.UintegerValue(0), "BK_MaxAmsduSize",
                ns.core.UintegerValue(0), "VI_MaxAmsduSize",
                ns.core.UintegerValue(0), "VO_MaxAmsduSize",
                ns.core.UintegerValue(0), "BE_MaxAmpduSize",
                ns.core.UintegerValue(65535), "BK_MaxAmpduSize",
                ns.core.UintegerValue(0), "VI_MaxAmpduSize",
                ns.core.UintegerValue(65535), "VO_MaxAmpduSize",
                ns.core.UintegerValue(0))  #Default settings

    apDevice = wifi.Install(phy, mac, wifiApNode.Get(0))

    # Set channel width
    ns.core.Config.Set(
        "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth",
        ns.core.UintegerValue(bandwidth))

    # mobility
    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()

    positionAlloc.Add(ns.core.Vector3D(0.0, 0.0, 0.0))
    positionAlloc.Add(ns.core.Vector3D(distance, 0.0, 0.0))
    mobility.SetPositionAllocator(positionAlloc)

    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")

    mobility.Install(wifiApNode)
    mobility.Install(wifiStaNode)

    # Internet stack
    stack = ns.internet.InternetStackHelper()
    stack.Install(wifiApNode)
    stack.Install(wifiStaNode)

    address = ns.internet.Ipv4AddressHelper()

    address.SetBase(ns.network.Ipv4Address("192.168.1.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    staNodeInterface = address.Assign(staDevice)
    apNodeInterface = address.Assign(apDevice)
    ns.core.Config.SetDefault("ns3::TcpSocket::SegmentSize",
                              ns.core.UintegerValue(1452))
    print(staNodeInterface)
    print(apNodeInterface)
    # Setting applications
    serverApp = ns.network.ApplicationContainer()
    sinkApp = ns.network.ApplicationContainer()

    viPort_1 = 9999
    viPort_2 = 9996
    voPort_1 = 9998
    voPort_2 = 9997
    bePort = 9994

    #ToS values: {0x70, 0x28, 0xb8, 0xc0}; //AC_BE, AC_BK, AC_VI, AC_VO

    #Video 1
    ipv4 = wifiStaNode.Get(0).GetObject(ns.internet.Ipv4.GetTypeId())
    adr = ipv4.GetAddress(1, 0).GetLocal()
    print("Sta IP Addr:")
    print(adr)
    sinkSocket = ns.network.InetSocketAddress(adr, viPort_1)
    sinkSocket.SetTos(0xb8)

    onOffHelper = ns.applications.OnOffHelper("ns3::TcpSocketFactory",
                                              sinkSocket)
    onOffHelper.SetAttribute(
        "OnTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute(
        "OffTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute("DataRate", ns.core.StringValue("11Mbps"))
    onOffHelper.SetAttribute("PacketSize", ns.core.UintegerValue(1452))
    onOffHelper.SetAttribute("StartTime",
                             ns.core.TimeValue(ns.core.Seconds(1.001)))
    serverApp.Add(onOffHelper.Install(wifiApNode.Get(0)))

    packetSinkHelper = ns.applications.PacketSinkHelper(
        "ns3::TcpSocketFactory", sinkSocket)
    sinkApp.Add(packetSinkHelper.Install(wifiStaNode.Get(0)))

    #Voice-1
    ipv4 = wifiStaNode.Get(0).GetObject(ns.internet.Ipv4.GetTypeId())
    adr = ipv4.GetAddress(1, 0).GetLocal()
    sinkSocket = ns.network.InetSocketAddress(adr, voPort_1)
    sinkSocket.SetTos(0xc0)
    onOffHelper = ns.applications.OnOffHelper("ns3::UdpSocketFactory",
                                              sinkSocket)
    onOffHelper.SetAttribute(
        "OnTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute(
        "OffTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute("DataRate", ns.core.StringValue("90Kbps"))
    onOffHelper.SetAttribute("PacketSize", ns.core.UintegerValue(160))
    onOffHelper.SetAttribute("StartTime",
                             ns.core.TimeValue(ns.core.Seconds(10.001)))

    serverApp.Add(onOffHelper.Install(wifiApNode.Get(0)))

    packetSinkHelper = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory", sinkSocket)
    sinkApp.Add(packetSinkHelper.Install(wifiStaNode.Get(0)))
    ##
    ipv4 = wifiApNode.Get(0).GetObject(ns.internet.Ipv4.GetTypeId())
    adr = ipv4.GetAddress(1, 0).GetLocal()
    sinkSocket = ns.network.InetSocketAddress(adr, voPort_2)
    sinkSocket.SetTos(0xc0)
    onOffHelper = ns.applications.OnOffHelper("ns3::UdpSocketFactory",
                                              sinkSocket)
    onOffHelper.SetAttribute(
        "OnTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute(
        "OffTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute("DataRate", ns.core.StringValue("90Kbps"))
    onOffHelper.SetAttribute("PacketSize", ns.core.UintegerValue(160))
    onOffHelper.SetAttribute("StartTime",
                             ns.core.TimeValue(ns.core.Seconds(10.001)))

    serverApp.Add(onOffHelper.Install(wifiStaNode.Get(0)))

    packetSinkHelper = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory", sinkSocket)
    sinkApp.Add(packetSinkHelper.Install(wifiApNode.Get(0)))

    #BestEffort
    ipv4 = wifiStaNode.Get(0).GetObject(ns.internet.Ipv4.GetTypeId())
    adr = ipv4.GetAddress(1, 0).GetLocal()
    sinkSocket = ns.network.InetSocketAddress(adr, bePort)
    sinkSocket.SetTos(0x70)
    onOffHelper = ns.applications.OnOffHelper("ns3::TcpSocketFactory",
                                              sinkSocket)
    onOffHelper.SetAttribute(
        "OnTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute(
        "OffTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute("DataRate", ns.core.StringValue("1Mbps"))
    onOffHelper.SetAttribute("PacketSize", ns.core.UintegerValue(750))
    onOffHelper.SetAttribute("StartTime",
                             ns.core.TimeValue(ns.core.Seconds(30.001)))

    serverApp.Add(onOffHelper.Install(wifiApNode.Get(0)))

    packetSinkHelper = ns.applications.PacketSinkHelper(
        "ns3::TcpSocketFactory", sinkSocket)
    sinkApp.Add(packetSinkHelper.Install(wifiStaNode.Get(0)))

    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

    phy.EnablePcap("AP_Scen4_NS3.pcap", apDevice.Get(0))
    phy.EnablePcap("AP_Scen4STA_NS3.pcap", staDevice.Get(0))

    ns.core.Config.SetDefault("ns3::ConfigStore::Filename",
                              ns.core.StringValue("output-attr.txt"))
    ns.core.Config.SetDefault("ns3::ConfigStore::FileFormat",
                              ns.core.StringValue("RawText"))
    ns.core.Config.SetDefault("ns3::ConfigStore::Mode",
                              ns.core.StringValue("Save"))
    outputConfig = ns.config_store.ConfigStore()
    outputConfig.ConfigureDefaults()
    outputConfig.ConfigureAttributes()

    ns.core.Simulator.Stop(ns.core.Seconds(simulationTime + 1))
    ns.core.Simulator.Run()

    ns.core.Simulator.Destroy()

    return 0
def main(argv):
    simulationTime = 15 #seconds
    distance = 0.0 #meters
    simulationTime = float(simulationTime)
    distance = float(distance)
    
    #Configuration arguments
    bandwidth = 40
    mcs = 3
    gi = False
    expected_val= 54
    
    channel = ns.wifi.YansWifiChannelHelper.Default ()
    phy = ns.wifi.YansWifiPhyHelper.Default ()
    wifi = ns.wifi.WifiHelper ()
    mac = ns.wifi.WifiMacHelper ()

    phy.SetPcapDataLinkType (ns.wifi.WifiPhyHelper.DLT_IEEE802_11_RADIO)
    phy.SetChannel (channel.Create ())
    
    wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211ac)

    wifiStaNode = ns.network.NodeContainer ()
    wifiStaNode.Create (5)
    wifiApNode = ns.network.NodeContainer ()
    wifiApNode.Create (1)

    # Set guard interval
    #phy.Set ("ShortGuardEnabled", ns.core.BooleanValue (gi))


    #mac = ns.wifi.VhtWifiMacHelper.Default ()
    DataRate = "VhtMcs"+str(mcs)

    wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager","DataMode", ns.core.StringValue(DataRate),
                                    "ControlMode", ns.core.StringValue(DataRate))

    ssid = ns.wifi.Ssid ("wifi-80211ac")

    mac.SetType ("ns3::StaWifiMac", "QosSupported", ns.core.BooleanValue (True),
                    "Ssid", ns.wifi.SsidValue (ssid))

    staDevice = wifi.Install (phy, mac, wifiStaNode)

    mac.SetType ("ns3::ApWifiMac","QosSupported", ns.core.BooleanValue (True),
                    "Ssid", ns.wifi.SsidValue (ssid))

    apDevice = wifi.Install (phy, mac, wifiApNode)

    # Set channel width
    ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue (bandwidth))
    
    # mobility
    mobility = ns.mobility.MobilityHelper ()
    positionAlloc = ns.mobility.ListPositionAllocator ()

    positionAlloc.Add (ns.core.Vector3D (0.0, 0.0, 0.0))
    positionAlloc.Add (ns.core.Vector3D (distance, 0.0, 0.0))
    mobility.SetPositionAllocator (positionAlloc)

    mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel")

    mobility.Install (wifiApNode)
    mobility.Install (wifiStaNode)

    # Internet stack
    stack = ns.internet.InternetStackHelper ()
    stack.Install (wifiApNode)
    stack.Install (wifiStaNode)

    address = ns.internet.Ipv4AddressHelper ()

    address.SetBase (ns.network.Ipv4Address ("192.168.1.0"), ns.network.Ipv4Mask ("255.255.255.0"))
    staNodeInterface = address.Assign (staDevice)
    apNodeInterface = address.Assign (apDevice)
    ns.core.Config.SetDefault ("ns3::TcpSocket::SegmentSize", ns.core.UintegerValue (1024))

    # Setting applications
    serverApp = ns.network.ApplicationContainer ()
    sinkApp = ns.network.ApplicationContainer ()
    
    viPort = 9999
    voPort_1 = 9998
    voPort_2 = 9997
    voPort_3 = 9996
    voPort_4 = 9995
    bePort = 9994
    bkPort = 9993
    
    ipv4 = wifiStaNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ())
    adr = ipv4.GetAddress (1,0).GetLocal ()
    print("Sta IP Addr:")
    print(adr)
    sinkSocket = ns.network.InetSocketAddress (adr, viPort)
    sinkSocket.SetTos (0x4)
    onOffHelper = ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket)
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("20Mbps")) #20Mbps
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (1024))
    onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (1.001 + random.uniform(0,0.1))))
    
    serverApp.Add (onOffHelper.Install(wifiApNode.Get(0)))
    
    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket)
    sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (0)))
 
    #Voice - 1
    ipv4 = wifiStaNode.Get (1).GetObject(ns.internet.Ipv4.GetTypeId ())
    adr = ipv4.GetAddress (1,0).GetLocal ()
    sinkSocket = ns.network.InetSocketAddress (adr, voPort_1)
    sinkSocket.SetTos (0x6)
    onOffHelper=ns.applications.OnOffHelper ("ns3::UdpSocketFactory", sinkSocket)
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("64Kbps"))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (160))
    onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (5.001)))

    serverApp.Add (onOffHelper.Install(wifiApNode.Get(0)))

    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::UdpSocketFactory", sinkSocket)
    sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (1)))
    ##
    ipv4 = wifiApNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ())
    adr = ipv4.GetAddress (1,0).GetLocal ()
    sinkSocket = ns.network.InetSocketAddress (adr, voPort_1)
    sinkSocket.SetTos (0x6)
    onOffHelper=ns.applications.OnOffHelper ("ns3::UdpSocketFactory", sinkSocket)
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("64Kbps"))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (160))
    onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (5.001+random.uniform(0,0.1))))

    serverApp.Add (onOffHelper.Install(wifiStaNode.Get(1)))

    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::UdpSocketFactory", sinkSocket)
    sinkApp.Add (packetSinkHelper.Install (wifiApNode.Get (0)))
    

    #Voice - 2
    ipv4 = wifiStaNode.Get (2).GetObject(ns.internet.Ipv4.GetTypeId ())
    adr = ipv4.GetAddress (1,0).GetLocal ()
    sinkSocket = ns.network.InetSocketAddress (adr, voPort_2)
    sinkSocket.SetTos (0x6)
    onOffHelper=ns.applications.OnOffHelper ("ns3::UdpSocketFactory", sinkSocket)
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("64Kbps"))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (160))
    onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (5.001)))

    serverApp.Add (onOffHelper.Install(wifiApNode.Get(0)))

    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::UdpSocketFactory", sinkSocket)
    # sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (2)))
    ##
    ipv4 = wifiApNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ())
    adr = ipv4.GetAddress (1,0).GetLocal ()
    sinkSocket = ns.network.InetSocketAddress (adr, voPort_2)
    sinkSocket.SetTos (0x6)
    onOffHelper=ns.applications.OnOffHelper ("ns3::UdpSocketFactory", sinkSocket)
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("64Kbps"))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (160))
    onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (5.001+random.uniform(0,0.1))))

    serverApp.Add (onOffHelper.Install(wifiStaNode.Get(2)))

    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::UdpSocketFactory", sinkSocket)
    sinkApp.Add (packetSinkHelper.Install (wifiApNode.Get (0))) 

    #BestEffort
    ipv4 = wifiStaNode.Get (3).GetObject(ns.internet.Ipv4.GetTypeId ())
    adr = ipv4.GetAddress (1,0).GetLocal ()
    sinkSocket = ns.network.InetSocketAddress (adr, bePort)
    sinkSocket.SetTos (0x0)
    onOffHelper=ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket)
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("161Kbps"))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (501))
    onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (10.001+random.uniform(0,0.1))))

    serverApp.Add (onOffHelper.Install(wifiApNode.Get(0)))

    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket)
    sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (3)))
    ##
    ipv4 = wifiApNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ())
    adr = ipv4.GetAddress (1,0).GetLocal ()
    sinkSocket = ns.network.InetSocketAddress (adr, bePort)
    sinkSocket.SetTos (0x0)
    onOffHelper=ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket)
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("161Kbps"))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (501))
    onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (10.001+random.uniform(0,0.1))))

    serverApp.Add (onOffHelper.Install(wifiStaNode.Get(3)))

    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket)
    sinkApp.Add (packetSinkHelper.Install (wifiApNode.Get (0)))


    #BackGroun
    ipv4 = wifiStaNode.Get (4).GetObject(ns.internet.Ipv4.GetTypeId ())
    adr = ipv4.GetAddress (1,0).GetLocal ()
    sinkSocket = ns.network.InetSocketAddress (adr, bkPort)
    sinkSocket.SetTos (0x1)
    onOffHelper=ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket)
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("250Kbps"))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (750))
    onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (10.001+random.uniform(0,0.1))))

    serverApp.Add (onOffHelper.Install(wifiApNode.Get(0)))

    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket)
    sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (4)))

    ##
    ipv4 = wifiApNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ())
    adr = ipv4.GetAddress (1,0).GetLocal ()
    sinkSocket = ns.network.InetSocketAddress (adr, bkPort)
    sinkSocket.SetTos (0x1)
    onOffHelper=ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket)
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("250Kbps"))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (750))
    onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (10.001+random.uniform(0,0.1))))

    serverApp.Add (onOffHelper.Install(wifiStaNode.Get(4)))

    packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket)
    sinkApp.Add (packetSinkHelper.Install (wifiApNode.Get (0)))

    ##
    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables ()

    phy.EnablePcap( "AP.pcap", apDevice.Get (0))

    ns.core.Simulator.Stop (ns.core.Seconds (simulationTime+1))
    ns.core.Simulator.Run ()

    ns.core.Simulator.Destroy ()
    
    return 0
Example #18
0
    def Run(self, *positional_parameters, **keyword_parameters):
        ns.network.Packet.EnablePrinting()

        if "SINKS" in os.environ:
            self.m_nSinks = int(os.environ["SINKS"])
        if "TXP" in os.environ:
            self.m_txp = float(os.environ["TXP"])
        if "TOTAL_TIME" in os.environ:
            self.m_total_time = int(os.environ["TOTAL_TIME"])
        if "NODES" in os.environ:
            self.m_nodes = int(os.environ["NODES"])
        if "PROTOCOL" in os.environ:
            self.m_protocol = int(os.environ["PROTOCOL"])
        if "NODE_SPEED" in os.environ:
            self.m_node_speed = int(os.environ["NODE_SPEED"])
        if "NODE_PAUSE" in os.environ:
            self.m_node_pause = int(os.environ["NODE_PAUSE"])
        if "FILE_NAME" in os.environ:
            self.m_CSVfileName = os.environ["FILE_NAME"]

        if 'nSinks' in keyword_parameters:
            self.m_nSinks = keyword_parameters['nSinks']
        if 'txp' in keyword_parameters:
            self.m_txp = keyword_parameters['txp']
        if 'TotalTime' in keyword_parameters:
            self.m_total_time = keyword_parameters['TotalTime']
        if 'Nodes' in keyword_parameters:
            self.m_nodes = keyword_parameters['Nodes']
        if 'Protocol' in keyword_parameters:
            self.m_protocol = keyword_parameters['Protocol']
        if 'NodeSpeed' in keyword_parameters:
            self.m_node_speed = keyword_parameters['NodeSpeed']
        if 'NodePause' in keyword_parameters:
            self.m_node_pause = keyword_parameters['NodePause']
        if 'CSVfileName' in keyword_parameters:
            self.m_CSVfileName = keyword_parameters['CSVfileName']

        self.m_CSVfileName += "." + str(time.time())
        rate = "2048bps"
        phyMode = "DsssRate11Mbps"
        tr_name = self.m_CSVfileName + "-compare"
        self.m_protocolName = "protocol"

        ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize",
                                  ns.core.StringValue("64"))
        ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate",
                                  ns.core.StringValue(rate))

        ns.core.Config.SetDefault(
            "ns3::WifiRemoteStationManager::NonUnicastMode",
            ns.core.StringValue(phyMode))

        adhocNodes = ns.network.NodeContainer()
        adhocNodes.Create(self.m_nodes)

        wifi = ns.wifi.WifiHelper()
        wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211b)

        wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
        wifiChannel = ns.wifi.YansWifiChannelHelper()
        wifiChannel.SetPropagationDelay(
            "ns3::ConstantSpeedPropagationDelayModel")
        wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel")
        wifiPhy.SetChannel(wifiChannel.Create())

        wifiMac = ns.wifi.WifiMacHelper()
        wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
                                     "DataMode", ns.core.StringValue(phyMode),
                                     "ControlMode",
                                     ns.core.StringValue(phyMode))

        wifiPhy.Set("TxPowerStart", ns.core.DoubleValue(self.m_txp))
        wifiPhy.Set("TxPowerEnd", ns.core.DoubleValue(self.m_txp))

        wifiMac.SetType("ns3::AdhocWifiMac")
        adhocDevices = wifi.Install(wifiPhy, wifiMac,
                                    adhocNodes)  # type: NetDeviceContainer

        mobilityAdhoc = ns.mobility.MobilityHelper()
        streamIndex = 0  # used to get consistent mobility across scenarios

        pos = ns.core.ObjectFactory()
        pos.SetTypeId("ns3::RandomRectanglePositionAllocator")
        pos.Set(
            "X",
            ns.core.StringValue(
                "ns3::UniformRandomVariable[Min=0.0|Max=300.0]"))
        pos.Set(
            "Y",
            ns.core.StringValue(
                "ns3::UniformRandomVariable[Min=0.0|Max=1500.0]"))

        # Same as: Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> ();
        taPositionAlloc = pos.Create().GetObject(
            ns.mobility.PositionAllocator.GetTypeId(
            ))  # type: Ptr<PositionAllocator>
        streamIndex += taPositionAlloc.AssignStreams(streamIndex)

        ssSpeed = "ns3::UniformRandomVariable[Min=0.0|Max=%s]" % self.m_node_speed
        ssPause = "ns3::ConstantRandomVariable[Constant=%s]" % self.m_node_pause

        mobilityAdhoc.SetMobilityModel("ns3::RandomWaypointMobilityModel",
                                       "Speed", ns.core.StringValue(ssSpeed),
                                       "Pause", ns.core.StringValue(ssPause),
                                       "PositionAllocator",
                                       ns.core.PointerValue(taPositionAlloc))
        mobilityAdhoc.SetPositionAllocator(taPositionAlloc)
        mobilityAdhoc.Install(adhocNodes)
        streamIndex += mobilityAdhoc.AssignStreams(adhocNodes, streamIndex)
        # NS_UNUSED(streamIndex) # From this point, streamIndex is unused

        aodv = ns.aodv.AodvHelper()
        olsr = ns.olsr.OlsrHelper()
        dsdv = ns.dsdv.DsdvHelper()
        dsr = ns.dsr.DsrHelper()
        dsrMain = ns.dsr.DsrMainHelper()
        list = ns.internet.Ipv4ListRoutingHelper()
        internet = ns.internet.InternetStackHelper()

        if self.m_protocol == 1:
            list.Add(olsr, 100)
            self.m_protocolName = "OLSR"
        elif self.m_protocol == 2:
            list.Add(aodv, 100)
            self.m_protocolName = "AODV"
        elif self.m_protocol == 3:
            list.Add(dsdv, 100)
            self.m_protocolName = "DSDV"
        elif self.m_protocol == 4:
            self.m_protocolName = "DSR"
        else:
            print("No such protocol:%s" % str(self.m_protocol)
                  )  # NS_FATAL_ERROR ("No such protocol:" << m_protocol);

        if self.m_protocol < 4:
            internet.SetRoutingHelper(list)
            internet.Install(adhocNodes)
        elif self.m_protocol == 4:
            internet.Install(adhocNodes)
            dsrMain.Install(dsr, adhocNodes)

        print("assigning ip address")

        addressAdhoc = ns.internet.Ipv4AddressHelper()
        addressAdhoc.SetBase(ns.network.Ipv4Address("10.1.1.0"),
                             ns.network.Ipv4Mask("255.255.255.0"))
        adhocInterfaces = addressAdhoc.Assign(adhocDevices)

        onoff1 = ns.applications.OnOffHelper("ns3::UdpSocketFactory",
                                             ns.network.Address())
        onoff1.SetAttribute(
            "OnTime",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1.0]"))
        onoff1.SetAttribute(
            "OffTime",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.0]"))

        for i in range(0, self.m_nSinks):
            # Ptr<Socket> sink = SetupPacketReceive (adhocInterfaces.GetAddress (i), adhocNodes.Get (i));
            sink = self.SetupPacketReceive(adhocInterfaces.GetAddress(i),
                                           adhocNodes.Get(i))

            remoteAddress = ns.network.AddressValue(
                ns.network.InetSocketAddress(adhocInterfaces.GetAddress(i),
                                             self.port))
            onoff1.SetAttribute("Remote", remoteAddress)

            # Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> ();
            posURV = ns.core.ObjectFactory()
            posURV.SetTypeId("ns3::UniformRandomVariable")
            var = posURV.Create().GetObject(
                ns.core.UniformRandomVariable.GetTypeId())

            temp = onoff1.Install(
                adhocNodes.Get(i +
                               self.m_nSinks))  # type: ApplicationContainer
            temp.Start(ns.core.Seconds(var.GetValue(100.0, 101.0)))
            temp.Stop(ns.core.Seconds(self.m_total_time))

        ss = self.m_nSinks
        nodes = str(ss)

        ss2 = self.m_node_speed
        sNodeSpeed = str(ss2)

        ss3 = self.m_node_pause
        sNodePause = str(ss3)

        ss4 = rate
        sRate = str(ss4)

        tr_name = tr_name + "_" + \
                  self.m_protocolName + "_" + \
                  nodes + "sinks_" + \
                  sNodeSpeed + "speed_" + \
                  sNodePause + "pause_" + \
                  sRate + "rate"

        self.m_CSVfileName = tr_name

        ascii = ns.network.AsciiTraceHelper()

        ns.mobility.MobilityHelper.EnableAsciiAll(
            ascii.CreateFileStream(
                os.path.join(__workdir__, "%s.mob" % tr_name)))

        flowmon_helper = ns.flow_monitor.FlowMonitorHelper()

        monitor = flowmon_helper.InstallAll()
        monitor = flowmon_helper.GetMonitor()
        monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001))
        monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001))
        monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20))

        print("Run Simulation.")

        self.WriteHeaderCsv()
        self.CheckThroughput()

        ns.core.Simulator.Stop(ns.core.Seconds(self.m_total_time))
        ns.core.Simulator.Run()

        monitor.CheckForLostPackets()
        classifier = flowmon_helper.GetClassifier()

        if self.m_debugger:
            for flow_id, flow_stats in monitor.GetFlowStats():

                with open(
                        os.path.join(__workdir__,
                                     (self.m_CSVfileName + ".txt")),
                        'a') as file:

                    t = classifier.FindFlow(flow_id)
                    proto = {6: 'TCP', 17: 'UDP'}[t.protocol]
                    file.write("FlowID: %i (%s %s/%s --> %s/%i)\n" % \
                      (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort))
                    self.print_stats(file, flow_stats)
                    file.close()

        monitor.SerializeToXmlFile(
            os.path.join(__workdir__, "%s.flowmon" % tr_name), True, True)

        delays = []
        for flow_id, flow_stats in monitor.GetFlowStats():
            tupl = classifier.FindFlow(flow_id)
            if tupl.protocol == 17 and tupl.sourcePort == 698:
                continue

            if flow_stats.rxPackets == 0:
                delays.append(0)
            else:
                delays.append(flow_stats.delaySum.GetSeconds() /
                              flow_stats.rxPackets)

        plt.hist(delays, 20)
        plt.xlabel("Delay (s)")
        plt.ylabel("Number of Flows")
        plt.savefig(os.path.join(__workdir__, '%s.png' % tr_name), dpi=75)
        plt.show()

        ns.core.Simulator.Destroy()
def main(argv):
    cmd = ns.core.CommandLine()
    cmd.slot = 9  # slot time in microseconds
    cmd.sifs = 10  # SIFS duration in microseconds
    cmd.ackTimeout = 88  # ACK timeout duration in microseconds
    cmd.ctsTimeout = 88  # CTS timeout duration in microseconds
    cmd.rifs = 2  # RIFS duration in microseconds
    cmd.basicBlockAckTimeout = 286  # Basic Block ACK timeout duration in microseconds
    cmd.compressedBlockAckTimeout = 112  # Compressed Block ACK timeout duration in microseconds
    cmd.simulationTime = 10  # simulation time in seconds

    cmd.AddValue("slot", "Slot time in microseconds")
    cmd.AddValue("sifs", "SIFS duration in microseconds")
    cmd.AddValue("ackTimeout", "ACK timeout duration in microseconds")
    cmd.AddValue("ctsTimeout", "CTS timeout duration in microseconds")
    cmd.AddValue("rifs", "RIFS duration in microseconds")
    cmd.AddValue("basicBlockAckTimeoutTimeout",
                 "Basic Block ACK timeout duration in microseconds")
    cmd.AddValue("compressedBlockAckTimeoutTimeout",
                 "Compressed Block ACK timeout duration in microseconds")
    cmd.AddValue("simulationTime", "Simulation time in seconds")
    cmd.Parse(sys.argv)

    slot = int(cmd.slot)
    sifs = int(cmd.sifs)
    nMpdusackTimeout = int(cmd.ackTimeout)
    ctsTimeout = int(cmd.ctsTimeout)
    rifs = int(cmd.rifs)
    basicBlockAckTimeout = int(cmd.basicBlockAckTimeout)
    compressedBlockAckTimeout = int(cmd.compressedBlockAckTimeout)
    simulationTime = cmd.simulationTime

    #Since default reference loss is defined for 5 GHz, it needs to be changed when operating at 2.4 GHz
    ns.core.Config.SetDefault(
        "ns3::LogDistancePropagationLossModel::ReferenceLoss",
        ns.core.DoubleValue(40.046))

    #Create nodes
    wifiStaNodes = ns.network.NodeContainer()
    wifiStaNodes.Create(1)
    wifiApNode = ns.network.NodeContainer()
    wifiApNode.Create(1)

    #Create wireless channel
    channel = ns.wifi.YansWifiChannelHelper.Default()
    phy = ns.wifi.YansWifiPhyHelper.Default()
    phy.SetChannel(channel.Create())  # wireless range limited to 5 meters!

    #Default IEEE 802.11n (2.4 GHz)
    wifi = ns.wifi.WifiHelper.Default()
    wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211n_2_4GHZ)
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue("HtMcs7"), "ControlMode",
                                 ns.core.StringValue("HtMcs0"))
    mac = ns.wifi.HtWifiMacHelper.Default()

    #Install PHY and MAC
    ssid = ns.wifi.Ssid("ns3-wifi")
    mac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

    staDevices = ns.network.NetDeviceContainer()
    staDevices = wifi.Install(phy, mac, wifiStaNodes)

    mac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

    apDevice = ns.network.NetDeviceContainer()
    apDevice = wifi.Install(phy, mac, wifiApNode)

    #Once install is done, we overwrite the standard timing values
    ns.core.Config.Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/Slot",
                       ns.core.TimeValue(ns.core.MicroSeconds(slot)))
    ns.core.Config.Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/Sifs",
                       ns.core.TimeValue(ns.core.MicroSeconds(sifs)))
    ns.core.Config.Set(
        "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/AckTimeout",
        ns.core.TimeValue(ns.core.MicroSeconds(ackTimeout)))
    ns.core.Config.Set(
        "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/CtsTimeout",
        ns.core.TimeValue(ns.core.MicroSeconds(ctsTimeout)))
    ns.core.Config.Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/Rifs",
                       ns.core.TimeValue(ns.core.MicroSeconds(rifs)))
    ns.core.Config.Set(
        "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/BasicBlockAckTimeout",
        ns.core.TimeValue(ns.core.MicroSeconds(basicBlockAckTimeout)))
    ns.core.Config.Set(
        "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/compressedBlockAckTimeout",
        ns.core.TimeValue(ns.core.MicroSeconds(compressedBlockAckTimeout)))

    #Mobility
    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()

    positionAlloc.Add(ns.core.Vector3D(0.0, 0.0, 0.0))
    positionAlloc.Add(ns.core.Vector3D(1.0, 0.0, 0.0))
    mobility.SetPositionAllocator(positionAlloc)

    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install(wifiApNode)
    mobility.Install(wifiStaNodes)

    #Internet stack
    stack = ns.internet.InternetStackHelper()
    stack.Install(wifiApNode)
    stack.Install(wifiStaNodes)

    address = ns.internet.Ipv4AddressHelper()
    address.SetBase(ns.network.Ipv4Address("192.168.1.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    staNodeInterface = ns.internet.Ipv4InterfaceContainer()
    staNodeInterface = address.Assign(staDevices)

    apNodeInterface = ns.internet.Ipv4InterfaceContainer()
    apNodeInterface = address.Assign(apDevice)

    #Setting applications
    port = 9
    server = ns.applications.UdpServerHelper(port)
    serverApp = server.Install(wifiStaNode.Get(0))
    serverApp.Start(ns.core.Seconds(0.0))
    serverApp.Stop(ns.core.Seconds(simulationTime + 1))

    client = ns.applications.UdpClientHelper(staNodeInterface.GetAddress(0),
                                             port)
    client.SetAttribute("MaxPackets", ns.core.UintegerValue(4294967295))
    client.SetAttribute("Interval",
                        ns.core.TimeValue(ns.core.Time("0.00001")))  #packets/s
    client.SetAttribute("PacketSize", ns.core.UintegerValue(1472))  #bytes

    clientApp = client.Install(wifiApNode.Get(0))
    clientApp.Start(ns.core.Seconds(1.0))
    clientApp.Stop(ns.core.Seconds(simulationTime + 1))

    #Populate routing table
    #need to be done ###############
    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

    #Set simulation time and launch simulation
    ns.core.Simulator.Stop(ns.core.Seconds(simulationTime + 1))
    ns.core.Simulator.Run()

    totalPacketsThrough = serverApp.Get(0).GetReceived()
    throughput = totalPacketsThrough * 1472 * 8 / (simulationTime * 1000000.0
                                                   )  # Mbit/s
    print("Throughput:", throughput, "Mbit/s")

    ns.core.Simulator.Destroy()

    return 0