Exemple #1
0
def simulate(argv,nodes,time,deltaTime):
    cmd = ns.core.CommandLine()
    cmd.backboneNodes = nodes
    cmd.AddValue("backboneNodes","number of backbone nodes")
    cmd.Parse(argv)

    backboneNodes = int(cmd.backboneNodes)
    backbone = ns.network.NodeContainer()
    backbone.Create(backboneNodes)

    mobility = ns.mobility.MobilityHelper()
    mobility.SetPositionAllocator("ns3::GridPositionAllocator",
                                 "MinX", ns.core.DoubleValue (1.0),
                                 "MinY", ns.core.DoubleValue (1.0),
                                 "DeltaX",ns.core.DoubleValue (5.0),
                                 "DeltaY", ns.core.DoubleValue (5.0),
                                 "GridWidth", ns.core.UintegerValue (3),
                                 "LayoutType", ns.core.StringValue ("RowFirst"))
    mobility.SetMobilityModel("ns3::RandomWalk2dMobilityModel",
                             "Mode", ns.core.StringValue ("Time"),
                             "Time", ns.core.StringValue (str(deltaTime)+"s"),
                             "Speed", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"),
                             "Bounds", ns.mobility.RectangleValue (ns.mobility.Rectangle (0.0, 20.0, 0.0, 20.0)))
    mobility.Install(backbone)
    mobility.AssignStreams(backbone, 0)
    csma = ns.csma.CsmaHelper()
    ascii = ns.network.AsciiTraceHelper();
    mobility.EnableAsciiAll(ascii.CreateFileStream("mobility-trace.mob"));

    ns.core.Simulator.Stop(ns.core.Seconds(time))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Exemple #2
0
def main(argv):

    numEnb = 1
    numUe = 1
    stopTime = 1.05

    cmd = ns.core.CommandLine()
    cmd.Parse(argv)

    lteHelper = ns.lte.LteHelper()

    enbNodes = ns.network.NodeContainer()
    ueNodes = ns.network.NodeContainer()
    enbNodes.Create(numEnb)
    ueNodes.Create(numUe)

    mobility = ns.mobility.MobilityHelper()
    buildings = ns.buildings.BuildingsHelper()
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install(enbNodes)
    buildings.Install(enbNodes)
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install(ueNodes)
    buildings.Install(ueNodes)

    enbDevs = lteHelper.InstallEnbDevice(enbNodes)
    ueDevs = lteHelper.InstallUeDevice(enbNodes)
    lteHelper.Attach(ueDevs, enbDevs.Get(0))

    qci = ns.lte.EpsBearer.GBR_CONV_VOICE
    bearer = ns.lte.EpsBearer(qci)
    lteHelper.ActivateDataRadioBearer(ueDevs, bearer)
    lteHelper.EnableTraces()

    print("Run Simulation.")
    ns.core.Simulator.Stop(ns.core.Seconds(stopTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Exemple #3
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)
Exemple #4
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)
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
Exemple #6
0
macB.SetType("ns3::ApWifiMac","Ssid", ns.wifi.SsidValue (ssidB))
dev_apB = wifiB.Install(phyB, macB, apB)
'''

mobility = ns.mobility.MobilityHelper()
mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                              ns.core.DoubleValue(0.0), "MinY",
                              ns.core.DoubleValue(0.0), "DeltaX",
                              ns.core.DoubleValue(2.0), "DeltaY",
                              ns.core.DoubleValue(2.0), "GridWidth",
                              ns.core.UintegerValue(2), "LayoutType",
                              ns.core.StringValue("RowFirst"))

mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
mobility.Install(wifiNodes)

stack = ns.internet.InternetStackHelper()
stack.Install(wifiNodes)

address = ns.internet.Ipv4AddressHelper()

address.SetBase(ns.network.Ipv4Address("10.1.3.0"),
                ns.network.Ipv4Mask("255.255.255.0"))
wifiInterfaces = address.Assign(wifiDevices)
'''
inter_ha = address.Assign(dev_ha)
inter_apA = address.Assign(dev_apA)
inter_hb = address.Assign(dev_apA)
inter_apB = address.Assign(dev_apA)
'''
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
Exemple #8
0
#phy = ns.wifi.YansWifiPhyHelper.Default()
#phy.SetChannel(channel.Create())

#apDevices = lrpan.Install(wifiApNode)

mobility = ns.mobility.MobilityHelper()
mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                              ns.core.DoubleValue(0.0), "MinY",
                              ns.core.DoubleValue(0.0), "DeltaX",
                              ns.core.DoubleValue(distance), "DeltaY",
                              ns.core.DoubleValue(1.0), "GridWidth",
                              ns.core.UintegerValue(nWifi), "LayoutType",
                              ns.core.StringValue("RowFirst"))

mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
mobility.Install(nodes)

#print(dir(ns.core))

lrwpanhelper = ns.lr_wpan.LrWpanHelper()

lrwpandevicecontainer = lrwpanhelper.Install(nodes)

#Associate devices to specific PAN
lrwpanhelper.AssociateToPan(lrwpandevicecontainer, 0)

#Energy Model
basicEnergySourceHelper = ns.energy.BasicEnergySourceHelper()
basicEnergySourceHelper.Set("BasicEnergySourceInitialEnergyJ",
                            ns.core.DoubleValue(100))
Exemple #9
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
Exemple #10
0
def main(argv):
    ns.core.CommandLine().Parse(argv)

    ns.network.Packet.EnablePrinting()

    ns.core.Config.SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold",
                              ns.core.StringValue("0"))

    ns.core.Config.SetDefault(
        "ns3::WifiRemoteStationManager::FragmentationThreshold",
        ns.core.StringValue("2200"))

    wifi = ns.wifi.WifiHelper.Default()
    mobility = ns.mobility.MobilityHelper()
    stas = ns.network.NodeContainer()
    ap = ns.network.NodeContainer()

    packetSocket = ns.network.PacketSocketHelper()

    stas.Create(2)
    ap.Create(1)

    packetSocket.Install(stas)
    packetSocket.Install(ap)

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

    ssid = ns.wifi.Ssid("wifi-default")
    wifi.SetRemoteStationManager("ns3::ArfWifiManager")
    wifiMac = ns.wifi.NqosWifiMacHelper.Default()

    wifiMac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                    "ActiveProbing", ns.core.BooleanValue(False))
    staDevs = wifi.Install(wifiPhy, wifiMac, stas)

    wifiMac.SetType("ns3::ApWifiMac", "Ssid",
                    ns.wifi.SsidValue(ssid), "BeaconGeneration",
                    ns.core.BooleanValue(True), "BeaconInterval",
                    ns.core.TimeValue(ns.core.Seconds(2.5)))
    wifi.Install(wifiPhy, wifiMac, ap)

    mobility.Install(stas)
    mobility.Install(ap)

    ns.core.Simulator.Schedule(ns.core.Seconds(1.0), AdvancePosition,
                               ap.Get(0))

    socket = ns.network.PacketSocketAddress()
    socket.SetSingleDevice(staDevs.Get(0).GetIfIndex())
    socket.SetPhysicalAddress(staDevs.Get(1).GetAddress())
    socket.SetProtocol(1)

    onoff = ns.applications.OnOffHelper("ns3::PacketSocketFactory",
                                        ns.network.Address(socket))
    onoff.SetAttribute(
        "OnTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(42)))
    onoff.SetAttribute(
        "OffTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(0)))

    apps = onoff.Install(ns.network.NodeContainer(stas.Get(0)))
    apps.Start(ns.core.Seconds(0.5))
    apps.Stop(ns.core.Seconds(43.0))

    ns.core.Simulator.Stop(ns.core.Seconds(44.0))

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

    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
Exemple #12
0
def main(argv):
    #
    #  First, we initialize a few local variables that control some
    #  simulation parameters.
    #

    cmd = ns.core.CommandLine()
    cmd.backboneNodes = 10
    cmd.infraNodes = 2
    cmd.lanNodes = 2
    cmd.stopTime = 20

    #
    #  Simulation defaults are typically set next, before command line
    #  arguments are parsed.
    #
    ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize",
                              ns.core.StringValue("1472"))
    ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate",
                              ns.core.StringValue("100kb/s"))

    #
    #  For convenience, we add the local variables to the command line argument
    #  system so that they can be overridden with flags such as
    #  "--backboneNodes=20"
    #

    cmd.AddValue("backboneNodes", "number of backbone nodes")
    cmd.AddValue("infraNodes", "number of leaf nodes")
    cmd.AddValue("lanNodes", "number of LAN nodes")
    cmd.AddValue("stopTime", "simulation stop time(seconds)")

    #
    #  The system global variables and the local values added to the argument
    #  system can be overridden by command line arguments by using this call.
    #
    cmd.Parse(argv)

    backboneNodes = int(cmd.backboneNodes)
    infraNodes = int(cmd.infraNodes)
    lanNodes = int(cmd.lanNodes)
    stopTime = int(cmd.stopTime)

    if (stopTime < 10):
        print("Use a simulation stop time >= 10 seconds")
        exit(1)
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the backbone                                                #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #
    #  Create a container to manage the nodes of the adhoc(backbone) network.
    #  Later we'll create the rest of the nodes we'll need.
    #
    backbone = ns.network.NodeContainer()
    backbone.Create(backboneNodes)
    #
    #  Create the backbone wifi net devices and install them into the nodes in
    #  our container
    #
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.WifiMacHelper()
    mac.SetType("ns3::AdhocWifiMac")
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue("OfdmRate54Mbps"))
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    backboneDevices = wifi.Install(wifiPhy, mac, backbone)
    #
    #  Add the IPv4 protocol stack to the nodes in our container
    #
    print("Enabling OLSR routing on all backbone nodes")
    internet = ns.internet.InternetStackHelper()
    olsr = ns.olsr.OlsrHelper()
    internet.SetRoutingHelper(olsr)
    # has effect on the next Install ()
    internet.Install(backbone)
    # re-initialize for non-olsr routing.
    # internet.Reset()
    #
    #  Assign IPv4 addresses to the device drivers(actually to the associated
    #  IPv4 interfaces) we just created.
    #
    ipAddrs = ns.internet.Ipv4AddressHelper()
    ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    ipAddrs.Assign(backboneDevices)

    #
    #  The ad-hoc network nodes need a mobility model so we aggregate one to
    #  each of the nodes we just finished building.
    #
    mobility = ns.mobility.MobilityHelper()
    mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                                  ns.core.DoubleValue(20.0), "MinY",
                                  ns.core.DoubleValue(20.0), "DeltaX",
                                  ns.core.DoubleValue(20.0), "DeltaY",
                                  ns.core.DoubleValue(20.0), "GridWidth",
                                  ns.core.UintegerValue(5), "LayoutType",
                                  ns.core.StringValue("RowFirst"))
    mobility.SetMobilityModel(
        "ns3::RandomDirection2dMobilityModel", "Bounds",
        ns.mobility.RectangleValue(ns.mobility.Rectangle(-500, 500, -500,
                                                         500)), "Speed",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=2]"),
        "Pause",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.2]"))
    mobility.Install(backbone)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the LANs                                                    #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Reset the address base-- all of the CSMA networks will be in
    #  the "172.16 address space
    ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print("Configuring local area network for backbone node ", i)
        #
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        #
        newLanNodes = ns.network.NodeContainer()
        newLanNodes.Create(lanNodes - 1)
        #  Now, create the container with all nodes on this link
        lan = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), newLanNodes)
        #
        #  Create the CSMA net devices and install them into the nodes in our
        #  collection.
        #
        csma = ns.csma.CsmaHelper()
        csma.SetChannelAttribute(
            "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
        csma.SetChannelAttribute("Delay",
                                 ns.core.TimeValue(ns.core.MilliSeconds(2)))
        lanDevices = csma.Install(lan)
        #
        #  Add the IPv4 protocol stack to the new LAN nodes
        #
        internet.Install(newLanNodes)
        #
        #  Assign IPv4 addresses to the device drivers(actually to the
        #  associated IPv4 interfaces) we just created.
        #
        ipAddrs.Assign(lanDevices)
        #
        #  Assign a new network prefix for the next LAN, according to the
        #  network mask initialized above
        #
        ipAddrs.NewNetwork()
        #
        # The new LAN nodes need a mobility model so we aggregate one
        # to each of the nodes we just finished building.
        #
        mobilityLan = ns.mobility.MobilityHelper()
        positionAlloc = ns.mobility.ListPositionAllocator()
        for j in range(newLanNodes.GetN()):
            positionAlloc.Add(ns.core.Vector(0.0, (j * 10 + 10), 0.0))

        mobilityLan.SetPositionAllocator(positionAlloc)
        mobilityLan.PushReferenceMobilityModel(backbone.Get(i))
        mobilityLan.SetMobilityModel("ns3::ConstantPositionMobilityModel")
        mobilityLan.Install(newLanNodes)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the mobile networks                                         #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Reset the address base-- all of the 802.11 networks will be in
    #  the "10.0" address space
    ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print("Configuring wireless network for backbone node ", i)
        #
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        #
        stas = ns.network.NodeContainer()
        stas.Create(infraNodes - 1)
        #  Now, create the container with all nodes on this link
        infra = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), stas)
        #
        #  Create another ad hoc network and devices
        #
        ssid = ns.wifi.Ssid('wifi-infra' + str(i))
        wifiInfra = ns.wifi.WifiHelper()
        wifiPhy.SetChannel(wifiChannel.Create())
        wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager')
        macInfra = ns.wifi.WifiMacHelper()
        macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

        # setup stas
        staDevices = wifiInfra.Install(wifiPhy, macInfra, stas)
        # setup ap.
        macInfra.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid))
        apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i))
        # Collect all of these new devices
        infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices)

        #  Add the IPv4 protocol stack to the nodes in our container
        #
        internet.Install(stas)
        #
        #  Assign IPv4 addresses to the device drivers(actually to the associated
        #  IPv4 interfaces) we just created.
        #
        ipAddrs.Assign(infraDevices)
        #
        #  Assign a new network prefix for each mobile network, according to
        #  the network mask initialized above
        #
        ipAddrs.NewNetwork()
        #
        #  The new wireless nodes need a mobility model so we aggregate one
        #  to each of the nodes we just finished building.
        #
        subnetAlloc = ns.mobility.ListPositionAllocator()
        for j in range(infra.GetN()):
            subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0))

        mobility.PushReferenceMobilityModel(backbone.Get(i))
        mobility.SetPositionAllocator(subnetAlloc)
        mobility.SetMobilityModel(
            "ns3::RandomDirection2dMobilityModel", "Bounds",
            ns.mobility.RectangleValue(ns.mobility.Rectangle(-10, 10, -10,
                                                             10)), "Speed",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=3]"),
            "Pause",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.4]"))
        mobility.Install(stas)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Application configuration                                             #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Create the OnOff application to send UDP datagrams of size
    #  210 bytes at a rate of 448 Kb/s, between two nodes
    print("Create Applications.")
    port = 9  #  Discard port(RFC 863)

    appSource = ns.network.NodeList.GetNode(backboneNodes)
    lastNodeIndex = backboneNodes + backboneNodes * (
        lanNodes - 1) + backboneNodes * (infraNodes - 1) - 1
    appSink = ns.network.NodeList.GetNode(lastNodeIndex)
    # Let's fetch the IP address of the last node, which is on Ipv4Interface 1
    remoteAddr = appSink.GetObject(ns.internet.Ipv4.GetTypeId()).GetAddress(
        1, 0).GetLocal()

    onoff = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port)))
    apps = onoff.Install(ns.network.NodeContainer(appSource))
    apps.Start(ns.core.Seconds(3))
    apps.Stop(ns.core.Seconds(stopTime - 1))

    #  Create a packet sink to receive these packets
    sink = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory",
        ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port))
    apps = sink.Install(ns.network.NodeContainer(appSink))
    apps.Start(ns.core.Seconds(3))

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Tracing configuration                                                 #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    print("Configure Tracing.")
    csma = ns.csma.CsmaHelper()
    #
    #  Let's set up some ns-2-like ascii traces, using another helper class
    #
    ascii = ns.network.AsciiTraceHelper()
    stream = ascii.CreateFileStream("mixed-wireless.tr")
    wifiPhy.EnableAsciiAll(stream)
    csma.EnableAsciiAll(stream)
    internet.EnableAsciiIpv4All(stream)

    #  Csma captures in non-promiscuous mode
    csma.EnablePcapAll("mixed-wireless", False)
    #  Let's do a pcap trace on the backbone devices
    wifiPhy.EnablePcap("mixed-wireless", backboneDevices)
    wifiPhy.EnablePcap("mixed-wireless", appSink.GetId(), 0)

    #   #ifdef ENABLE_FOR_TRACING_EXAMPLE
    #     Config.Connect("/NodeList/*/$MobilityModel/CourseChange",
    #       MakeCallback(&CourseChangeCallback))
    #   #endif

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                        #
    #  Run simulation                                                        #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    print("Run Simulation.")
    ns.core.Simulator.Stop(ns.core.Seconds(stopTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
def main(argv):
    ns.core.LogComponentEnable("EdcaTxopN", ns.core.LOG_LEVEL_DEBUG)
    ns.core.LogComponentEnable("BlockAckManager", ns.core.LOG_LEVEL_INFO)

    sta = ns.network.Node()
    ap = ns.network.Node()

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

    wifi = ns.wifi.WifiHelper.Default()
    mac = ns.wifi.QosWifiMacHelper.Default()
    # disable fragmentation
    wifi.SetRemoteStationManager("ns3::AarfWifiManager",
                                 "FragmentationThreshold",
                                 ns.core.UintegerValue(2500))

    ssid = ns.wifi.Ssid("My-network")

    mac.SetType(
        "ns3::StaWifiMac",
        "QosSupported",
        ns.core.BooleanValue(True),
        "Ssid",
        ns.wifi.SsidValue(ssid),
        "ActiveProbing",
        ns.core.BooleanValue(False),
        # setting blockack threshold for sta's BE queue
        "BE_BlockAckThreshold",
        ns.core.UintegerValue(2),
        # setting block inactivity timeout to 3*1024 = 3072 microseconds
        "BE_BlockAckInactivityTimeout",
        ns.core.UintegerValue(3))

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

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

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

    # Setting mobility model
    mobility = ns.mobility.MobilityHelper()

    mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                                  ns.core.DoubleValue(0.0), "MinY",
                                  ns.core.DoubleValue(0.0), "DeltaX",
                                  ns.core.DoubleValue(5.0), "DeltaY",
                                  ns.core.DoubleValue(10.0), "GridWidth",
                                  ns.core.UintegerValue(3), "LayoutType",
                                  ns.core.StringValue("RowFirst"))

    mobility.SetMobilityModel(
        "ns3::RandomWalk2dMobilityModel", "Bounds",
        ns.mobility.RectangleValue(ns.mobility.Rectangle(-50, 50, -50, 50)))
    mobility.Install(sta)

    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install(ap)

    # Internet stack
    stack = ns.internet.InternetStackHelper()
    stack.Install(sta)
    stack.Install(ap)

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

    # Setting applications
    port = 9
    dataRate = ns.network.DataRate("1Mb/s")
    onOff = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(
            ns.network.InetSocketAddress(apIf.GetAddress(0), port)))
    onOff.SetAttribute("DataRate", ns.network.DataRateValue(dataRate))
    onOff.SetAttribute(
        "OnTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.01]"))
    onOff.SetAttribute(
        "OffTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=8]"))
    onOff.SetAttribute("PacketSize", ns.core.UintegerValue(50))

    staApps = onOff.Install(sta)

    staApps.Start(ns.core.Seconds(1.0))
    staApps.Stop(ns.core.Seconds(10.0))

    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

    ns.core.Simulator.Stop(ns.core.Seconds(10.0))

    phy.EnablePcap("wifi-blockack-py", ap.GetId(), 0)
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Exemple #14
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
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
Exemple #16
0
def main():
    if not len(sys.argv[1:]):
        print "Usage: {0} traceFile".format(sys.argv[0])
        sys.exit(0)

    traceFile = sys.argv[1]
    phyMode = "OfdmRate6MbpsBW10MHz"

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

    # ns.core.LogComponentEnable("Ns2MobilityHelper", ns.core.LOG_LEVEL_DEBUG)

    try:
        ns2 = ns.mobility.Ns2MobilityHelper(str(traceFile))
    except Exception as err:
        print "Error: %s" % str(err)
        sys.exit(0)

    mobility = ns.mobility.MobilityHelper()
    # mobility.SetPositionAllocator ("ns3::GridPositionAllocator", "MinX", ns.core.DoubleValue(0.0),
    # 								"MinY", ns.core.DoubleValue (0.0), "DeltaX", ns.core.DoubleValue(5.0), "DeltaY", ns.core.DoubleValue(10.0),
    #                                  "GridWidth", ns.core.UintegerValue(3), "LayoutType", ns.core.StringValue("RowFirst"))
    #
    # mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel")
    mobility.Install(nodes)
    ns2.Install()

    channel = ns.wifi.YansWifiChannelHelper.Default()
    channel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel")
    channel.AddPropagationLoss("ns3::NakagamiPropagationLossModel")
    phy = ns.wifi.YansWifiPhyHelper.Default()
    phy.SetChannel(channel.Create())
    phy.SetPcapDataLinkType(ns.wifi.YansWifiPhyHelper.DLT_IEEE802_11)
    phy.Set("TxGain", ns.core.DoubleValue(4.5))
    phy.Set("RxGain", ns.core.DoubleValue(4.5))
    phy.Set("EnergyDetectionThreshold", ns.core.DoubleValue(-96.0))
    # phy.EnablePcap("vanets_python",nodes)

    wifi80211pMac = ns.wave.NqosWaveMacHelper.Default()
    wifi80211p = ns.wave.Wifi80211pHelper.Default()

    wifi80211p.SetRemoteStationManager("ns3::ConstantRateWifiManager",
                                       "DataMode",
                                       ns.core.StringValue(phyMode),
                                       "ControlMode",
                                       ns.core.StringValue(phyMode))
    devices = wifi80211p.Install(phy, wifi80211pMac, nodes)

    internet = ns.internet.InternetStackHelper()
    internet.Install(nodes)

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

    interfaces = ipv4.Assign(devices)

    packetsize = 64  #bytes
    pktcount = 2
    pktinterval = 0.25  #seconds
    port = 80

    server = random.randint(0, 24)
    print "Server==> %s" % interfaces.GetAddress(server)

    appSink = ns.network.NodeList.GetNode(server)

    for x in range(4):
        client = random.randint(0, 24)
        print "Client==> %s" % interfaces.GetAddress(client)
        appSource = ns.network.NodeList.GetNode(client)

        remoteAddr = appSink.GetObject(
            ns.internet.Ipv4.GetTypeId()).GetAddress(1, 0).GetLocal()
        # sink = ns.network.Socket.CreateSocket(appSink, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
        sink = ns.network.Socket.CreateSocket(
            appSink, ns.core.TypeId.LookupByName("ns3::TcpSocketFactory"))
        sink.Bind(
            ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), 80))
        sink.Listen()
        # print dir(sink)
        sink.SetRecvCallback(RecPkt)

        # source = ns.network.Socket.CreateSocket(appSource, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
        source = ns.network.Socket.CreateSocket(
            appSource, ns.core.TypeId.LookupByName("ns3::TcpSocketFactory"))
        source.Connect(ns.network.InetSocketAddress(remoteAddr, port))
        source.SetRecvCallback(RecPkt)

    # sinkApp = ns.network.ApplicationContainer()
    # port = 50000
    # # apLocalAddress = ns.network.Address (ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), port))
    # for x in range(0,6):
    #     apLocalAddress = ns.network.Address (ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), port))
    #     packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", apLocalAddress)
    #     sinkApp.Add(packetSinkHelper.Install (nodes.Get (x)))
    #
    # sinkApp.Start (ns.core.Seconds (0.0))
    # sinkApp.Stop (ns.core.Seconds (141.0))
    #
    # 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 (2048))
    # # onoff.SetAttribute ("DataRate", ns.network.DataRateValue (ns.network.DataRate (100000))) # bit/s
    #
    # apps = ns.network.ApplicationContainer ()
    # # remoteAddress = ns.network.AddressValue (ns.network.InetSocketAddress (interfaces.GetAddress (0), port))
    #
    # for x in range(7,14):
    #     rn = random.randint(0,3)
    #     print "Server >>: {0}".format(rn)
    #     remoteAddress = ns.network.AddressValue (ns.network.InetSocketAddress (interfaces.GetAddress (rn), port))
    #     onoff.SetAttribute ("Remote", remoteAddress)
    #     apps.Add (onoff.Install (nodes.Get (x)))
    #
    # apps.Start (ns.core.Seconds (1.0))
    # apps.Stop (ns.core.Seconds (141.0))

    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

    asciitracer = ns.network.AsciiTraceHelper()
    # phy.EnableAsciiAll (asciitracer.CreateFileStream ("vanets.tr"))
    phy.EnablePcap("vanets", nodes)
    ns.core.Simulator.Schedule(ns.core.Seconds(10.0), SndPkt, source,
                               packetsize, pktcount, pktinterval)

    ns.core.Simulator.Stop(ns.core.Seconds(161.0))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Exemple #17
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
Exemple #18
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.nWifis = 2
    cmd.nStas = 2
    cmd.sendIp = True
    cmd.writeMobility = False
    cmd.AddValue("nWifis", "Number of wifi networks")
    cmd.AddValue("nStas", "Number of stations per wifi network")
    cmd.AddValue("SendIp", "Send Ipv4 or raw packets")
    cmd.AddValue("writeMobility", "Write mobility trace")
    cmd.Parse(sys.argv)

    nWifis = cmd.nWifis
    nStas = cmd.nStas
    sendIp = cmd.sendIp
    writeMobility = cmd.writeMobility

    backboneNodes = ns.network.NodeContainer()
    backboneDevices = ns.network.NetDeviceContainer()
    backboneInterfaces = ns.internet.Ipv4InterfaceContainer()

    staNodes = ns.network.NodeContainer()
    staDevices = ns.network.NetDeviceContainer()
    apDevices = ns.network.NetDeviceContainer()
    staInterfaces = ns.internet.Ipv4InterfaceContainer()
    apInterfaces = ns.internet.Ipv4InterfaceContainer()

    stack = ns.internet.InternetStackHelper()
    csma = ns.csma.CsmaHelper()
    ip = ns.internet.Ipv4AddressHelper()
    ip.SetBase(ns.network.Ipv4Address("192.168.0.0"),
               ns.network.Ipv4Mask("255.255.255.0"))

    backboneNodes.Create(cmd.nWifis)
    stack.Install(backboneNodes)

    backboneDevices = csma.Install(backboneNodes)

    wifiX = 0.0

    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiPhy.SetPcapDataLinkType(ns.wifi.YansWifiPhyHelper.DLT_IEEE802_11_RADIO)

    for i in range(0, cmd.nWifis):
        #calculate ssid for wifi subnetwork
        ssid = ns.wifi.Ssid("wifi-default-" + str(i))

        sta = ns.network.NodeContainer()
        staDev = ns.network.NetDeviceContainer()
        apDev = ns.network.NetDeviceContainer()
        staInterface = ns.internet.Ipv4InterfaceContainer()
        apInterface = ns.internet.Ipv4InterfaceContainer()
        mobility = ns.mobility.MobilityHelper()
        bridge = ns.bridge.BridgeHelper()
        wifi = ns.wifi.WifiHelper()
        wifiMac = ns.wifi.WifiMacHelper()
        wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
        wifiPhy.SetChannel(wifiChannel.Create())

        sta.Create(cmd.nStas)
        mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                                      ns.core.DoubleValue(wifiX), "MinY",
                                      ns.core.DoubleValue(0.0), "DeltaX",
                                      ns.core.DoubleValue(5.0), "DeltaY",
                                      ns.core.DoubleValue(5.0), "GridWidth",
                                      ns.core.UintegerValue(1), "LayoutType",
                                      ns.core.StringValue("RowFirst"))

        #setup the AP.
        mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
        mobility.Install(backboneNodes.Get(i))
        wifiMac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid))
        apDev = wifi.Install(wifiPhy, wifiMac, backboneNodes.Get(i))

        bridgeDev = ns.network.NetDeviceContainer()
        bridgeDev = bridge.Install(
            backboneNodes.Get(i),
            ns.network.NetDeviceContainer(apDev, backboneDevices.Get(i)))

        #assign AP IP address to bridge, not wifi
        apInterface = ip.Assign(bridgeDev)

        #setup the STAs
        stack.Install(sta)
        mobility.SetMobilityModel(
            "ns3::RandomWalk2dMobilityModel", "Mode",
            ns.core.StringValue("Time"), "Time", ns.core.StringValue("2s"),
            "Speed",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1.0]"),
            "Bounds",
            ns.core.RectangleValue(
                ns.core.Rectangle(wifiX, wifiX + 5.0, 0.0,
                                  (cmd.nStas + 1) * 5.0)))
        mobility.Install(sta)
        wifiMac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid))
        staDev = wifi.Install(wifiPhy, wifiMac, sta)
        staInterface = ip.Assign(staDev)

        #save everything in containers.
        staNodes.push_back(sta)
        apDevices.push_back(apDev)
        apInterfaces.push_back(apInterface)
        staDevices.push_back(staDev)
        staInterfaces.push_back(staInterface)

        wifiX = wifiX + 20.0

    dest = ns.network.Address()
    if cmd.sendIp:
        dest = ns.network.InetSocketAddress(
            staInterfaces(1).GetAddress(1), 1025)
        protocol = "ns3::UdpSocketFactory"
    else:
        tmp = ns.network.PacketSocketAddress()
        tmp.SetSingleDevice(staDevices[0].Get(0).GetIfIndex())
        tmp.SetPhysicalAddress(staDevices[1].Get(0).GetAddress())
        tmp.SetProtocol(0x807)
        dest = tmp
        protocol = "ns3::PacketSocketFactory"

    onoff = ns.applications.OnOffHelper(protocol, dest)
    onoff.SetConstantRate(ns.core.DataRateValue(ns.core.DataRate("500kb/s")))
    apps = ns.applications.ApplicationContainer(
        onoff.Install(staNodes[0].Get(0)))
    apps.Start(ns.core.Seconds(0.5))
    apps.Stop(ns.core.Seconds(3.0))

    wifiPhy.EnablePcap("wifi-wired-bridging", apDevices[0])
    wifiPhy.EnablePcap("wifi-wired-bridging", apDevices[1])

    if cmd.writeMobility:
        ascii = ns.network.AsciiTraceHelper()
        ns.mobility.MobilityHelper.EnableAsciiAll(
            ascii.CreateFileStream("wifi-wired-bridging.mob"))

    ns.core.Simulator.Stop(ns.core.Seconds(5.0))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
def main(argv):
    cmd = ns.core.CommandLine()

    cmd.nWifis = 2
    cmd.nStas = 2
    cmd.sendIp = "True"
    cmd.writeMobility = "False"
    cmd.AddValue("nWifis", "Number of wifi networks")
    cmd.AddValue("nStas", "Number of stations per wifi network")
    cmd.AddValue("SendIp", "Send Ipv4 or raw packets")
    cmd.AddValue("writeMobility", "Write mobility trace")
    cmd.Parse(sys.argv)

    nWifis = cmd.nWifis
    nStas = cmd.nStas
    sendIp = cmd.sendIp
    writeMobility = cmd.writeMobility

    backboneNodes = ns.network.NodeContainer()
    backboneDevices = ns.network.NetDeviceContainer()

    backboneInterfaces = ns.network.Ipv4InterfaceContainer
    #       std::vector<NodeContainer> staNodes;
    #   std::vector<NetDeviceContainer> staDevices;
    #   std::vector<NetDeviceContainer> apDevices;
    #   std::vector<Ipv4InterfaceContainer> staInterfaces;
    #   std::vector<Ipv4InterfaceContainer> apInterfaces;
    staNodes = []
    staDevices = []
    apDevices = []
    staInterfaces = []
    apInterfaces = []

    stack = ns.internet.InternetStackHelper()
    csma = ns.csma.CsmaHelper()
    ip = ns.internet.Ipv4AddressHelper()
    ip.SetBase(ns.network.Ipv4Address("192.168.0.0"),
               ns.network.Ipv4Mask("255.255.255.0"))

    backboneNodes.Create(nWifis)
    stack.Install(backboneNodes)
    backboneDevices = csma.Install(backboneNodes)

    wifiX = 0.0

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

    for i in range(0, nWifis):

        # calculate ssid for wifi subnetwork
        # std::ostringstream oss;
        # oss << "wifi-default-" << i;
        # Ssid ssid = Ssid (oss.str ());

        oss = "wifi-default-" + i
        ssid = ns.wifi.Ssid(oss)

        sta = ns.network.NodeContainer()
        staDev = ns.network.NetDeviceContainer()
        apDev = ns.network.NetDeviceContainer()
        staInterface = ns.network.Ipv4InterfaceContainer()
        apInterface = ns.network.Ipv4InterfaceContainer()
        mobility = ns.mobility.MobilityHelper()
        bridge = ns.mobility.BridgeHelper()
        wifi = ns.wifi.WifiHelper()
        wifiMac = ns.wifi.WifiMacHelper()
        wifiChannel = ns.wifi.YansWifiPhyHelper.Default()
        wifiPhy.SetChannel(wifiChannel.Create())

        sta.Create(nStas)
        mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                                      ns.core.DoubleValue(wifiX), "MinY",
                                      ns.core.DoubleValue(0.0), "DeltaX",
                                      ns.core.DoubleValue(5.0), "DeltaY",
                                      ns.core.DoubleValue(5.0), "GridWidth",
                                      ns.core.UintegerValue(1), "LayoutType",
                                      ns.core.StringValue("RowFirst"))

        mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
        mobility.Install(backboneNodes.Get(i))
        wifiMac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid))
        apDev = wifi.Install(wifiPhy, wifiMac, backboneNodes.Get(i))

        bridgeDev = ns.network.NetDeviceContainer()
        bridgeDev = bridge.Install(
            backboneNodes.Get(i),
            ns.network.NetDeviceContainer(apDev, backboneDevices.Get(i)))

        #assign AP IP address to bridge, not wifi
        apInterface = ip.Assign(bridgeDev)

        stack.Install(sta)
        mobility.SetMobilityModel(
            "ns3::RandomWalk2dMobilityModel", "Mode",
            ns.core.StringValue("Time"), "Time", ns.core.StringValue("2s"),
            "Speed",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1.0]"),
            "Bounds",
            ns.core.RectangleValue(
                ns.mobility.Rectangle(wifiX, wifiX + 5.0, 0.0,
                                      (nStas + 1) * 5.0)))
        mobility.Install(sta)
        wifiMac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid))
        staDev = wifi.Install(wifiPhy, wifiMac, sta)
        staInterface = ip.Assign(staDev)

        #save everything in containers.
        staNodes.append(sta)
        apDevices.append(apDev)
        apInterfaces.append(apInterface)
        staDevices.append(staDev)
        staInterfaces.append(staInterface)
        # staNodes.push_back (sta);
        # apDevices.push_back (apDev);
        # apInterfaces.push_back (apInterface);
        # staDevices.push_back (staDev);
        # staInterfaces.push_back (staInterface);

        wifiX += 20.0

    if sendIp:
        protocol = "ns3::TcpStartTimeSocketFactory"
        dest = ns.network.InetSocketAddress(staInterfaces[1].GetAddress(1),
                                            1025)

    # else :
    #     PacketSocketAddress tmp
    #     tmp.SetSingleDevice (staDevices[0].Get (0)->GetIfIndex ())
    #     tmp.SetPhysicalAddress (staDevices[1].Get (0)->GetAddress ())
    #     tmp.SetProtocol (0x807)
    #     dest = tmp
    #      protocol = "ns3::PacketSocketFactory"

    #  OnOffHelper onoff = OnOffHelper (protocol, dest);
    #  onoff.SetConstantRate (DataRate ("500kb/s"));
    #  ApplicationContainer apps = onoff.Install (staNodes[0].Get (0));
    #  apps.Start (Seconds (0.5));
    #  apps.Stop (Seconds (9.0));
    onoff = ns.applications.OnOffHelper(protocol, dest)
    onoff.SetAttribute("DataRate",
                       ns.network.DataRateValue(
                           ns.network.DataRate(500)))  # bit/s(check)
    apps = onoff.Install(staNodes[0].Get(0))
    apps.Start(ns.core.Seconds(0.5))
    apps.Stop(ns.core.Seconds(9.0))

    wifiPhy.EnablePcap("base_wifi-wired-bridging", apDevices[0])
    wifiPhy.EnablePcap("base_wifi-wired-bridging", apDevices[1])

    if writeMobility:
        ascii = ns.network.AsciiTraceHelper()
        mobility.EnablePcapAll("wifi-wired-bridging.moby", True)
        # pointToPoint.EnableAsciiAll (ascii.CreateFileStream ("tcp-bulk-send-py.tr"))

    # AnimationInterface anim ("base.xml")
    # anim.EnablePacketMetadata (); # Optional
    # anim.EnableIpv4L3ProtocolCounters (Seconds (0), Seconds (15)) #Optional

    ns.core.Simulator.Stop(ns.core.Seconds(15.0))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Exemple #21
0
def main(argv):
    #
    #  First, we declare and initialize a few local variables that control some
    #  simulation parameters.
    #
    backboneNodes = 10
    infraNodes = 5
    lanNodes = 5
    stopTime = 10

    #
    #  Simulation defaults are typically set next, before command line
    #  arguments are parsed.
    #
    ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize",
                              ns.core.StringValue("210"))
    ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate",
                              ns.core.StringValue("448kb/s"))

    #
    #  For convenience, we add the local variables to the command line argument
    #  system so that they can be overridden with flags such as
    #  "--backboneNodes=20"
    #
    cmd = ns.core.CommandLine()
    #cmd.AddValue("backboneNodes", "number of backbone nodes", backboneNodes)
    #cmd.AddValue("infraNodes", "number of leaf nodes", infraNodes)
    #cmd.AddValue("lanNodes", "number of LAN nodes", lanNodes)
    #cmd.AddValue("stopTime", "simulation stop time(seconds)", stopTime)

    #
    #  The system global variables and the local values added to the argument
    #  system can be overridden by command line arguments by using this call.
    #
    cmd.Parse(argv)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the backbone                                                #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #
    #  Create a container to manage the nodes of the adhoc(backbone) network.
    #  Later we'll create the rest of the nodes we'll need.
    #
    backbone = ns.network.NodeContainer()
    backbone.Create(backboneNodes)
    #
    #  Create the backbone wifi net devices and install them into the nodes in
    #  our container
    #
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.NqosWifiMacHelper.Default()
    mac.SetType("ns3::AdhocWifiMac")
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue("OfdmRate54Mbps"))
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    backboneDevices = wifi.Install(wifiPhy, mac, backbone)
    #
    #  Add the IPv4 protocol stack to the nodes in our container
    #
    print "Enabling OLSR routing on all backbone nodes"
    internet = ns.internet.InternetStackHelper()
    olsr = ns.olsr.OlsrHelper()
    internet.SetRoutingHelper(olsr)
    # has effect on the next Install ()
    internet.Install(backbone)
    # re-initialize for non-olsr routing.
    internet.Reset()
    #
    #  Assign IPv4 addresses to the device drivers(actually to the associated
    #  IPv4 interfaces) we just created.
    #
    ipAddrs = ns.internet.Ipv4AddressHelper()
    ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    ipAddrs.Assign(backboneDevices)

    #
    #  The ad-hoc network nodes need a mobility model so we aggregate one to
    #  each of the nodes we just finished building.
    #
    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()
    x = 0.0
    for i in range(backboneNodes):
        positionAlloc.Add(ns.core.Vector(x, 0.0, 0.0))
        x += 5.0
    mobility.SetPositionAllocator(positionAlloc)
    mobility.SetMobilityModel(
        "ns3::RandomDirection2dMobilityModel", "Bounds",
        ns.mobility.RectangleValue(ns.mobility.Rectangle(0, 1000, 0,
                                                         1000)), "Speed",
        ns.core.RandomVariableValue(ns.core.ConstantVariable(2000)), "Pause",
        ns.core.RandomVariableValue(ns.core.ConstantVariable(0.2)))
    mobility.Install(backbone)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the LANs                                                    #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Reset the address base-- all of the CSMA networks will be in
    #  the "172.16 address space
    ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print "Configuring local area network for backbone node ", i
        #
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        #
        newLanNodes = ns.network.NodeContainer()
        newLanNodes.Create(lanNodes - 1)
        #  Now, create the container with all nodes on this link
        lan = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), newLanNodes)
        #
        #  Create the CSMA net devices and install them into the nodes in our
        #  collection.
        #
        csma = ns.csma.CsmaHelper()
        csma.SetChannelAttribute(
            "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
        csma.SetChannelAttribute("Delay",
                                 ns.core.TimeValue(ns.core.MilliSeconds(2)))
        lanDevices = csma.Install(lan)
        #
        #  Add the IPv4 protocol stack to the new LAN nodes
        #
        internet.Install(newLanNodes)
        #
        #  Assign IPv4 addresses to the device drivers(actually to the
        #  associated IPv4 interfaces) we just created.
        #
        ipAddrs.Assign(lanDevices)
        #
        #  Assign a new network prefix for the next LAN, according to the
        #  network mask initialized above
        #
        ipAddrs.NewNetwork()

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the mobile networks                                         #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Reset the address base-- all of the 802.11 networks will be in
    #  the "10.0" address space
    ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print "Configuring wireless network for backbone node ", i
        #
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        #
        stas = ns.network.NodeContainer()
        stas.Create(infraNodes - 1)
        #  Now, create the container with all nodes on this link
        infra = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), stas)
        #
        #  Create another ad hoc network and devices
        #
        ssid = ns.wifi.Ssid('wifi-infra' + str(i))
        wifiInfra = ns.wifi.WifiHelper.Default()
        wifiPhy.SetChannel(wifiChannel.Create())
        wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager')
        macInfra = ns.wifi.NqosWifiMacHelper.Default()
        macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                         "ActiveProbing", ns.core.BooleanValue(False))

        # setup stas
        staDevices = wifiInfra.Install(wifiPhy, macInfra, stas)
        # setup ap.
        macInfra.SetType("ns3::ApWifiMac", "Ssid",
                         ns.wifi.SsidValue(ssid), "BeaconGeneration",
                         ns.core.BooleanValue(True), "BeaconInterval",
                         ns.core.TimeValue(ns.core.Seconds(2.5)))
        apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i))
        # Collect all of these new devices
        infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices)

        #  Add the IPv4 protocol stack to the nodes in our container
        #
        internet.Install(stas)
        #
        #  Assign IPv4 addresses to the device drivers(actually to the associated
        #  IPv4 interfaces) we just created.
        #
        ipAddrs.Assign(infraDevices)
        #
        #  Assign a new network prefix for each mobile network, according to
        #  the network mask initialized above
        #
        ipAddrs.NewNetwork()
        #
        #  The new wireless nodes need a mobility model so we aggregate one
        #  to each of the nodes we just finished building.
        #
        subnetAlloc = ns.mobility.ListPositionAllocator()
        for j in range(infra.GetN()):
            subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0))

        mobility.PushReferenceMobilityModel(backbone.Get(i))
        mobility.SetPositionAllocator(subnetAlloc)
        mobility.SetMobilityModel(
            "ns3::RandomDirection2dMobilityModel", "Bounds",
            ns.mobility.RectangleValue(ns.mobility.Rectangle(-25, 25, -25,
                                                             25)), "Speed",
            ns.core.RandomVariableValue(ns.core.ConstantVariable(30)), "Pause",
            ns.core.RandomVariableValue(ns.core.ConstantVariable(0.4)))
        mobility.Install(infra)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Application configuration                                             #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Create the OnOff application to send UDP datagrams of size
    #  210 bytes at a rate of 448 Kb/s, between two nodes
    print "Create Applications."
    port = 9  #  Discard port(RFC 863)

    #  Let's make sure that the user does not define too few LAN nodes
    #  to make this example work.  We need lanNodes >= 5
    assert (lanNodes >= 5)
    appSource = ns.network.NodeList.GetNode(11)
    appSink = ns.network.NodeList.GetNode(13)
    remoteAddr = ns.network.Ipv4Address("172.16.0.5")

    onoff = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port)))
    onoff.SetAttribute(
        "OnTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(1)))
    onoff.SetAttribute(
        "OffTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(0)))
    apps = onoff.Install(ns.network.NodeContainer(appSource))
    apps.Start(ns.core.Seconds(3.0))
    apps.Stop(ns.core.Seconds(20.0))

    #  Create a packet sink to receive these packets
    sink = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory",
        ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port))
    apps = sink.Install(ns.network.NodeContainer(appSink))
    apps.Start(ns.core.Seconds(3.0))

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Tracing configuration                                                 #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    print "Configure Tracing."
    #
    #  Let's set up some ns-2-like ascii traces, using another helper class
    #
    #std.ofstream ascii
    #ascii = ns.core.AsciiTraceHelper();
    #stream = ascii.CreateFileStream("mixed-wireless.tr");
    #wifiPhy.EnableAsciiAll(stream);
    #csma.EnableAsciiAll(stream);
    print "(tracing not done for Python)"
    #  Look at nodes 11, 13 only
    # WifiHelper.EnableAscii(ascii, 11, 0);
    # WifiHelper.EnableAscii(ascii, 13, 0);

    #  Let's do a pcap trace on the backbone devices
    wifiPhy.EnablePcap("mixed-wireless", backboneDevices)
    #  Let's additionally trace the application Sink, ifIndex 0
    csma = ns.csma.CsmaHelper()
    csma.EnablePcapAll("mixed-wireless", False)

    #   #ifdef ENABLE_FOR_TRACING_EXAMPLE
    #     Config.Connect("/NodeList/*/$MobilityModel/CourseChange",
    #       MakeCallback(&CourseChangeCallback))
    #   #endif

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                        #
    #  Run simulation                                                        #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    print "Run Simulation."
    ns.core.Simulator.Stop(ns.core.Seconds(stopTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Exemple #22
0
def main():
    framework.start()

    # First, we initialize a few local variables that control some
    #  simulation parameters.
    cmd = ns.core.CommandLine()
    cmd.backboneNodes = {{backbone_nodes}}
    cmd.infraNodes = {{infra_nodes}}
    cmd.lanNodes = {{lan_nodes}}
    cmd.stopTime = {{exec_time}}

    #  Simulation defaults are typically set next, before command line
    #  arguments are parsed.
    ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize",
                              ns.core.StringValue("1472"))
    ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate",
                              ns.core.StringValue("100kb/s"))

    backboneNodes = int(cmd.backboneNodes)
    infraNodes = int(cmd.infraNodes)
    lanNodes = int(cmd.lanNodes)
    stopTime = int(cmd.stopTime)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the backbone                                                #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #  Create a container to manage the nodes of the adhoc(backbone) network.
    #  Later we'll create the rest of the nodes we'll need.
    backbone = ns.network.NodeContainer()
    backbone.Create(backboneNodes)

    #  Create the backbone wifi net devices and install them into the nodes in
    #  our container
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.WifiMacHelper()
    mac.SetType("ns3::AdhocWifiMac")
    wifi.SetRemoteStationManager(
        "ns3::ConstantRateWifiManager", "DataMode",
        ns.core.StringValue("OfdmRate{}Mbps".format({{ofdm_rate}})))
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    backboneDevices = wifi.Install(wifiPhy, mac, backbone)

    #  Add the IPv4 protocol stack to the nodes in our container
    print("Enabling OLSR routing on all backbone nodes")
    internet = ns.internet.InternetStackHelper()
    olsr = ns.olsr.OlsrHelper()
    internet.SetRoutingHelper(olsr)
    # has effect on the next Install ()
    internet.Install(backbone)

    #  Assign IPv4 addresses to the device drivers(actually to the associated
    #  IPv4 interfaces) we just created.
    ipAddrs = ns.internet.Ipv4AddressHelper()
    ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    ipAddrs.Assign(backboneDevices)

    #  The ad-hoc network nodes need a mobility model so we aggregate one to
    #  each of the nodes we just finished building.
    mobility = ns.mobility.MobilityHelper()
    mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                                  ns.core.DoubleValue(20.0), "MinY",
                                  ns.core.DoubleValue(20.0), "DeltaX",
                                  ns.core.DoubleValue(20.0), "DeltaY",
                                  ns.core.DoubleValue(20.0), "GridWidth",
                                  ns.core.UintegerValue(5), "LayoutType",
                                  ns.core.StringValue("RowFirst"))
    mobility.SetMobilityModel(
        "ns3::RandomDirection2dMobilityModel", "Bounds",
        ns.mobility.RectangleValue(ns.mobility.Rectangle(-500, 500, -500,
                                                         500)), "Speed",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=2]"),
        "Pause",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.2]"))
    mobility.Install(backbone)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the LANs                                                    #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #  Reset the address base-- all of the CSMA networks will be in
    #  the "172.16 address space
    ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        newLanNodes = ns.network.NodeContainer()
        newLanNodes.Create(lanNodes - 1)
        lan = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), newLanNodes)

        #  Create the CSMA net devices and install them into the nodes in our
        #  collection.
        csma = ns.csma.CsmaHelper()
        csma.SetChannelAttribute(
            "DataRate",
            ns.network.DataRateValue(ns.network.DataRate({{datarate}})))
        csma.SetChannelAttribute(
            "Delay", ns.core.TimeValue(ns.core.MilliSeconds({{delay}})))
        lanDevices = csma.Install(lan)

        #  Add the IPv4 protocol stack to the new LAN nodes
        internet.Install(newLanNodes)

        #  Assign IPv4 addresses to the device drivers(actually to the
        #  associated IPv4 interfaces) we just created.
        ipAddrs.Assign(lanDevices)

        #  Assign a new network prefix for the next LAN, according to the
        #  network mask initialized above
        ipAddrs.NewNetwork()

        # The new LAN nodes need a mobility model so we aggregate one
        # to each of the nodes we just finished building.
        mobilityLan = ns.mobility.MobilityHelper()
        positionAlloc = ns.mobility.ListPositionAllocator()
        for j in range(newLanNodes.GetN()):
            positionAlloc.Add(ns.core.Vector(0.0, (j * 10 + 10), 0.0))

        mobilityLan.SetPositionAllocator(positionAlloc)
        mobilityLan.PushReferenceMobilityModel(backbone.Get(i))
        mobilityLan.SetMobilityModel("ns3::ConstantPositionMobilityModel")
        mobilityLan.Install(newLanNodes)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the mobile networks                                         #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #  Reset the address base-- all of the 802.11 networks will be in
    #  the "10.0" address space
    ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        stas = ns.network.NodeContainer()
        stas.Create(infraNodes - 1)
        infra = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), stas)

        #  Create another ad hoc network and devices
        ssid = ns.wifi.Ssid('wifi-infra' + str(i))
        wifiInfra = ns.wifi.WifiHelper()
        wifiPhy.SetChannel(wifiChannel.Create())
        wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager')
        macInfra = ns.wifi.WifiMacHelper()
        macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

        # setup stas
        staDevices = wifiInfra.Install(wifiPhy, macInfra, stas)
        # setup ap.
        macInfra.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                         "BeaconInterval",
                         ns.core.TimeValue(ns.core.Seconds(2.5)))
        apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i))
        # Collect all of these new devices
        infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices)

        #  Add the IPv4 protocol stack to the nodes in our container
        internet.Install(stas)

        #  Assign IPv4 addresses to the device drivers(actually to the associated
        #  IPv4 interfaces) we just created.
        ipAddrs.Assign(infraDevices)

        #  Assign a new network prefix for each mobile network, according to
        #  the network mask initialized above
        ipAddrs.NewNetwork()

        #  The new wireless nodes need a mobility model so we aggregate one
        #  to each of the nodes we just finished building.
        subnetAlloc = ns.mobility.ListPositionAllocator()
        for j in range(infra.GetN()):
            subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0))

        mobility.PushReferenceMobilityModel(backbone.Get(i))
        mobility.SetPositionAllocator(subnetAlloc)
        mobility.SetMobilityModel(
            "ns3::RandomDirection2dMobilityModel", "Bounds",
            ns.mobility.RectangleValue(ns.mobility.Rectangle(-10, 10, -10,
                                                             10)), "Speed",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=3]"),
            "Pause",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.4]"))
        mobility.Install(stas)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Application configuration                                             #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #  Create the OnOff application to send UDP datagrams of size
    #  210 bytes at a rate of 448 Kb/s, between two nodes
    port = 9  #  Discard port(RFC 863)

    appSource = ns.network.NodeList.GetNode(backboneNodes)
    lastNodeIndex = backboneNodes + backboneNodes * (
        lanNodes - 1) + backboneNodes * (infraNodes - 1) - 1
    appSink = ns.network.NodeList.GetNode(lastNodeIndex)
    # Let's fetch the IP address of the last node, which is on Ipv4Interface 1
    remoteAddr = appSink.GetObject(ns.internet.Ipv4.GetTypeId()).GetAddress(
        1, 0).GetLocal()

    onoff = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port)))
    apps = onoff.Install(ns.network.NodeContainer(appSource))
    apps.Start(ns.core.Seconds(3))
    apps.Stop(ns.core.Seconds(stopTime - 1))

    #  Create a packet sink to receive these packets
    sink = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory",
        ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port))
    apps = sink.Install(ns.network.NodeContainer(appSink))
    apps.Start(ns.core.Seconds(3))

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Tracing configuration                                                 #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    csma = ns.csma.CsmaHelper()

    #  Let's set up some ns-2-like ascii traces, using another helper class
    #
    ascii = ns.network.AsciiTraceHelper()
    stream = ascii.CreateFileStream("mixed-wireless.tr")
    wifiPhy.EnableAsciiAll(stream)
    csma.EnableAsciiAll(stream)
    internet.EnableAsciiIpv4All(stream)

    mob = ascii.CreateFileStream("mixed-wireless.mob")
    mobility.EnableAsciiAll(mob)

    #  Csma captures in non-promiscuous mode
    csma.EnablePcapAll("mixed-wireless", False)
    #  Let's do a pcap trace on the backbone devices
    wifiPhy.EnablePcap("mixed-wireless", backboneDevices)
    wifiPhy.EnablePcap("mixed-wireless", appSink.GetId(), 0)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                        #
    #  Run simulation                                                        #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    ns.core.Simulator.Stop(ns.core.Seconds(stopTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()

    framework.addBinaryFile("mixed-wireless.tr")
    framework.addBinaryFile("mixed-wireless.mob")

    path = "*.pcap"
    for filename in glob.glob(path):
        framework.addBinaryFile(filename)

    framework.stop()
Exemple #23
0
def main(argv):
    ns.core.CommandLine().Parse(argv)

    ns.network.Packet.EnablePrinting()

    # enable rts cts all the time.
    ns.core.Config.SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold",
                              ns.core.StringValue("0"))
    # disable fragmentation
    ns.core.Config.SetDefault(
        "ns3::WifiRemoteStationManager::FragmentationThreshold",
        ns.core.StringValue("2200"))

    wifi = ns.wifi.WifiHelper.Default()
    mobility = ns.mobility.MobilityHelper()
    stas = ns.network.NodeContainer()
    ap = ns.network.NodeContainer()
    #NetDeviceContainer staDevs;
    packetSocket = ns.network.PacketSocketHelper()

    stas.Create(2)
    ap.Create(1)

    # give packet socket powers to nodes.
    packetSocket.Install(stas)
    packetSocket.Install(ap)

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

    ssid = ns.wifi.Ssid("wifi-default")
    wifi.SetRemoteStationManager("ns3::ArfWifiManager")
    wifiMac = ns.wifi.WifiMacHelper()

    # setup stas.
    wifiMac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid))
    staDevs = wifi.Install(wifiPhy, wifiMac, stas)
    # setup ap.
    wifiMac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                    "BeaconInterval", ns.core.TimeValue(ns.core.Seconds(2.5)))
    wifi.Install(wifiPhy, wifiMac, ap)

    # mobility.
    mobility.Install(stas)
    mobility.Install(ap)

    ns.core.Simulator.Schedule(ns.core.Seconds(1.0), AdvancePosition,
                               ap.Get(0))

    socket = ns.network.PacketSocketAddress()
    socket.SetSingleDevice(staDevs.Get(0).GetIfIndex())
    socket.SetPhysicalAddress(staDevs.Get(1).GetAddress())
    socket.SetProtocol(1)

    onoff = ns.applications.OnOffHelper("ns3::PacketSocketFactory",
                                        ns.network.Address(socket))
    onoff.SetConstantRate(ns.network.DataRate("500kb/s"))

    apps = onoff.Install(ns.network.NodeContainer(stas.Get(0)))
    apps.Start(ns.core.Seconds(0.5))
    apps.Stop(ns.core.Seconds(43.0))

    ns.core.Simulator.Stop(ns.core.Seconds(44.0))

    #   Config::Connect("/NodeList/*/DeviceList/*/Tx", MakeCallback(&DevTxTrace));
    #   Config::Connect("/NodeList/*/DeviceList/*/Rx", MakeCallback(&DevRxTrace));
    #   Config::Connect("/NodeList/*/DeviceList/*/Phy/RxOk", MakeCallback(&PhyRxOkTrace));
    #   Config::Connect("/NodeList/*/DeviceList/*/Phy/RxError", MakeCallback(&PhyRxErrorTrace));
    #   Config::Connect("/NodeList/*/DeviceList/*/Phy/Tx", MakeCallback(&PhyTxTrace));
    #   Config::Connect("/NodeList/*/DeviceList/*/Phy/State", MakeCallback(&PhyStateTrace));

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

    return 0
Exemple #24
0
phyMode = "OfdmRate6MbpsBW10MHz"

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

ns.core.LogComponentEnable("UdpEchoClientApplication", ns.core.LOG_LEVEL_INFO)
ns.core.LogComponentEnable("UdpEchoServerApplication", ns.core.LOG_LEVEL_INFO)
# ns.core.LogComponentEnable("Ns2MobilityHelper", ns.core.LOG_LEVEL_DEBUG)

try:
    mobility = ns.mobility.Ns2MobilityHelper(str(traceFile))
except Exception as err:
    print "Error: %s" % str(err)
    sys.exit(0)

mobility.Install()

channel = ns.wifi.YansWifiChannelHelper.Default()
# channel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel")
# channel.AddPropagationLoss("ns3::NakagamiPropagationLossModel")
phy = ns.wifi.YansWifiPhyHelper.Default()
phy.SetChannel(channel.Create())
phy.SetPcapDataLinkType(ns.wifi.YansWifiPhyHelper.DLT_IEEE802_11)
phy.Set("TxGain", ns.core.DoubleValue(4.5))
phy.Set("RxGain", ns.core.DoubleValue(4.5))
# phy.Set("EnergyDetectionThreshold",ns.core.DoubleValue(-100.0))
# phy.EnablePcap("vanets_python",nodes)

wifi80211pMac = ns.wave.NqosWaveMacHelper.Default()
wifi80211p = ns.wave.Wifi80211pHelper.Default()
		    "BeaconGeneration", ns.core.BooleanValue (True),
		    "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)
Exemple #26
0
def runMain(argc, argv):

    #ns.core.LogComponentEnable("UanChannel", ns.core.LOG_ALL)
    #ns.core.LogComponentEnable("UanHelper", ns.core.LOG_ALL)
    #ns.core.LogComponentEnable("UanNetDevice", ns.core.LOG_ALL)
    ns.core.LogComponentEnable("UanPhyGen", ns.core.LOG_ALL)
    #ns.core.LogComponentEnable("UanPropModelThorp", ns.core.LOG_ALL)
    #ns.core.LogComponentEnable("OnOffApplication", ns.core.LOG_ALL)
    ns.core.LogComponentEnableAll(ns.core.LOG_PREFIX_NODE)
    ns.core.LogComponentEnableAll(ns.core.LOG_PREFIX_TIME)

    ns3.GlobalValue.Bind("SimulatorImplementationType",
                         ns3.StringValue("ns3::RealtimeSimulatorImpl"))
    ns3.GlobalValue.Bind("ChecksumEnabled", ns3.BooleanValue(True))

    nNodes = 100
    sPreadCoef = 1.5
    rxThresh = 5
    txPower = 140
    windspeed = 4.5
    shipcontri = 0.5
    ''' channel module configurations begin '''
    nodes = ns.network.NodeContainer()
    nodes.Create(nNodes)

    uan = ns.uan.UanHelper()
    chan = ns.uan.UanChannel()

    # noise configuration
    noise_object = ns.uan.UanNoiseModelDefault()
    noise_ptr = noise_object.GetObject(ns.uan.UanNoiseModelDefault.GetTypeId())
    #noise.SetWind(windspeed)
    #noise.SetShipping(shipcontri)
    #noise.Wind = ns.core.DoubleValue(windspeed)
    #noise.Shipping = ns.core.DoubleValue(shipcontri)
    #noisePtr = ns.core.PointerValue(noise)
    chan.SetNoiseModel(noise_ptr)
    #chan.SetAttribute("NoiseModel", noise_ptr)
    # propagation model configuration
    prop_object = ns.uan.UanPropModelThorp()
    prop_ptr = prop_object.GetObject(ns.uan.UanPropModelThorp.GetTypeId())
    #prop.SpreadCoef = ns.core.DoubleValue(sPreadCoef)
    #prop.SetSpreadCoef(sPreadCoef)
    #propPtr = ns.core.PointerValue(prop)
    chan.SetPropagationModel(prop_ptr)
    #chan.SetAttribute("PropagationModel", prop_ptr)

    # modulation mode configuration
    mode = ns.uan.UanTxMode()
    mode = ns.uan.UanTxModeFactory.CreateMode(
        ns.uan.UanTxMode.FSK,  # modulation type
        1624,  # data rate in BPS: 1152B/5.67s
        1624,
        24000,  # cetner frequency in Hz
        6000,  # bandwidth in Hz
        2,  # modulation constellation size, 2 for BPSK, 4 for QPSK
        "Default mode")

    myModes = ns.uan.UanModesList()
    myModes.AppendMode(mode)

    # physical layer channel configuration
    perModel = "ns3::UanPhyPerGenDefault"
    sinrModel = "ns3::UanPhyCalcSinrDefault"
    obf = ns.core.ObjectFactory()
    obf.SetTypeId(perModel)
    per = obf.Create()  # watch
    obf.SetTypeId(sinrModel)
    sinr = obf.Create()

    # watch
    uan.SetPhy("ns3::UanPhyGen", "PerModel", ns.core.PointerValue(per),
               "SinrModel", ns.core.PointerValue(sinr), "SupportedModes",
               ns.uan.UanModesListValue(myModes), "RxThreshold",
               ns.core.DoubleValue(rxThresh), "TxPower",
               ns.core.DoubleValue(txPower))

    # configure MAC module for uan channel
    uan.SetMac("ns3::UanMacAloha")

    # install wireless devices onto ghost nodes

    #devices = ns.network.NetDeviceContainer(uan.Install(nodes, chan))
    devices = uan.Install(nodes, chan)
    #devices = uan.Install(nodes)
    #mobility
    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()

    mDist = 50

    for i in range(0, nNodes):
        positionAlloc.Add(ns.core.Vector((i - nNodes / 2) * mDist, 0.0, -10.0))
    mobility.SetPositionAllocator(positionAlloc)
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install(nodes)

    mobility.SetPositionAllocator(positionAlloc)
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install(nodes)
    ''' setup tap bridges from vmuan-2km.cc '''
    tapBridge = ns3.TapBridgeHelper()
    tapBridge.SetAttribute("Mode", ns.core.StringValue("UseLocal"))
    tapBridge.SetAttribute("DeviceName", ns3.StringValue("tap-vNode1"))
    tapBridge.Install(nodes.Get(0), devices.Get(0))

    #tapBridge.SetAttribute ("DeviceName", ns3.StringValue ("tap-vNode2"));
    #tapBridge.Install (nodes.Get (1), devices.Get (1));

    #tapBridge.SetAttribute ("DeviceName", ns3.StringValue ("tap-vNode3"));
    #tapBridge.Install (nodes.Get (2), devices.Get (2));

    #tapBridge.SetAttribute ("DeviceName", ns3.StringValue ("tap-vNode4"));
    #tapBridge.Install (nodes.Get (3), devices.Get (3));

    #tapBridge.SetAttribute ("DeviceName", ns3.StringValue ("tap-vNode5"));
    #tapBridge.Install (nodes.Get (4), devices.Get (4));

    #tapBridge.SetAttribute ("DeviceName", ns3.StringValue ("tap-vNode6"));
    #tapBridge.Install (nodes.Get (5), devices.Get (5));
    '''
	pktskth=ns.network.PacketSocketHelper()
	pktskth.Install(nodes)
	appsocket=ns.network.PacketSocketAddress()

	appsocket.SetSingleDevice(devices.Get(nNodes-1).GetIfIndex())
	appsocket.SetPhysicalAddress(devices.Get (nNodes-1).GetAddress())
	appsocket.SetProtocol(0)
	
	app=ns.applications.OnOffHelper("ns3::PacketSocketFactory",appsocket.GetPhysicalAddress())
	app.SetAttribute("OnTime",ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
	app.SetAttribute("OffTime",ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))
	app.SetAttribute("DataRate",ns.network.DataRateValue(ns.network.DataRate(1300)))
	app.SetAttribute("PacketSize",ns.core.UintegerValue(1000))
	apps=ns.network.ApplicationContainer(app.Install(nodes.Get(0)))

	sinkNode=nodes.Get(nNodes-1)
    #Ptr<Node> sinkNode = nodes.Get (nNodes-1);
  	psfid = ns3.TypeId.LookupByName("ns3::PacketSocketFactory")
  	sinkSocket = ns3.Socket.CreateSocket(sinkNode, psfid)
  	sinkSocket.Bind (appsocket)
  	#sinkSocket.SetRecvCallback(ns.core.MakeCallback(ReceivePacket));
	
  	apps.Start(ns.core.Seconds(0.5))
	apps.Stop(ns.core.Seconds(100.5))
	'''
    #NS_LOG_INFO ("Run Simulation.");
    #ns3.Simulator.Stop(ns.core.Seconds(100.))
    ns3.Simulator.Run()
    ns3.Simulator.Destroy()
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
Exemple #28
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
Exemple #29
0
def main(argv):
    cmd = ns.core.CommandLine()
    cmd.payloadSize =  1472 
    cmd.simulationTime = 5;
    cmd.nMpdus =  1;
    cmd.maxAmpduSize = 0;
    cmd.enableRts = False
    cmd.minExpectedThroughput = 0;
    cmd.maxExpectedThroughput = 0;
    cmd.nAPs = 9; 
    cmd.nSTAs = 27; 
    cmd.area = 50;
    cmd.MCS = 7;

    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.AddValue("nAPs","Number of APs")
    cmd.AddValue("nSTAs","Number of STAs")
    cmd.AddValue("area","Network area")
    cmd.AddValue("MCS","MCS value for al APs")
    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
    nAPs = int(cmd.nAPs);
    nSTAs= int (cmd.nSTAs);
    area = int(cmd.area);
    MCS =  int(cmd.MCS);
    
    band = 5; # 5GHz band
    if enableRts:
        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 node scenario
    ns.core.Config.SetDefault("ns3::RangePropagationLossModel::MaxRange", ns.core.DoubleValue (20))
    
    wifiStaNodes = ns.network.NodeContainer ()
    wifiStaNodes.Create (nSTAs)

    wifiApNode = ns.network.NodeContainer ()
    wifiApNode.Create (nAPs)

    ''' Add mobility condition for APs and STAs '''
    mobility = ns.mobility.MobilityHelper ()
    positionAlloc = ns.mobility.ListPositionAllocator ()


    ''' Import data from the CSV file about AP location , Station location and STation maps '''
    inputs   =  pd.read_csv('inputs.csv')
    AP_xloc  =  inputs['AP_xloc']
    AP_yloc  =  inputs['AP_yloc']
    STA_xloc =  inputs['STA_xloc']
    STA_yloc =  inputs['STA_yloc']
    STA_map  =  inputs['STA_map']
    UL_R     =  inputs['UL_Rate']
    DL_R     =  inputs['DL_Rate']


    ''' mobility pattern for APs: considering 9 APs '''
    for i in range(nAPs):
        positionAlloc.Add (ns.core.Vector(AP_xloc[i],AP_yloc[i],0))

    ''' mobility pattern for STAs , randomly disbtributed STAs '''
    mobility.SetPositionAllocator (positionAlloc)
    mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    mobility.Install (wifiApNode)

    positionAlloc1 = ns.mobility.ListPositionAllocator ()
    for j in range(nSTAs):
        positionAlloc1.Add(ns.core.Vector(STA_xloc[j],STA_yloc[j],0))

    mobility.SetPositionAllocator (positionAlloc1)
    mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel")
    mobility.Install (wifiStaNodes)


    ''' set up ipv4 address  '''
    address = ns.internet.Ipv4AddressHelper()
    address.SetBase (ns.network.Ipv4Address ("192.168.1.0"), ns.network.Ipv4Mask ("255.255.255.0"))
    stack = ns.internet.InternetStackHelper ()
    stack.Install (wifiApNode)
    stack.Install (wifiStaNodes)

    ''' create dictionary to add APs and STAs connection info '''
    AP ={};
    STA = {}
    ApInterface  = {};
    StaInterface  = {};

    ''' assuming client data is sent to every STA from their respective APs  '''
    port = 9;  
    server = ns.applications.UdpServerHelper (port)
    serverAp = server.Install(wifiApNode)# (ns.network.NodeContainer(wifiApNode.Get(i)))
    serverAp.Start (ns.core.Seconds (0.0))
    serverAp.Stop (ns.core.Seconds (simulationTime + 1))

    ''' assuming STA is the server in this section '''
    port1 = 90;  
    server1 = ns.applications.UdpServerHelper (port1)
    serverSta = server1.Install(wifiStaNodes)# (ns.network.NodeContainer(wifiApNode.Get(i)))
    serverSta.Start (ns.core.Seconds (0.0))
    serverSta.Stop (ns.core.Seconds (simulationTime + 1))

    ''' setup wifi parameters for APs and STAs '''
    WIFI =  Wifi_setup(maxAmpduSize) # call  wifi setup class
    if abs(MCS)==MCS:
        print('== Network with Similar AP capacities ==')
        MCS =   np.array([MCS]*nAPs)#
    else:
        print('== Network with different AP capacities ==')
        MCS = random.randint(8,size=nAPs) # generate different MCS values for different APs 
        print('MCS for APs: {}'.format(MCS))

    ''' build connection between APs and STAs '''
    for i in range(nAPs):
        print(" building network for AP-{}".format(i+1));
        ssid = ns.wifi.Ssid("AP-"+str(i+1))
        AP[str(i)],Phy =  WIFI.wifi_phy(MCS[i],band,wifiApNode.Get(i),ssid)#wifi.Install (phy, mac, wifiApNode.Get(i))
        ApInterface[str(i)] = ns.internet.Ipv4InterfaceContainer ()
        ApInterface[str(i)] = address.Assign (AP[str(i)])

        k, = np.where(STA_map==i) # m corresponds to row and k corresponds to column position

        ''' create client application for ap where AP is a server'''
        client = ns.applications.UdpClientHelper (ApInterface[str(i)].GetAddress (0), port) 
        Phy.EnablePcap ("SimpleHtHiddenStations_py_Ap_"+str(i),ns.network.NodeContainer 
                        (wifiApNode.Get(i)) )

        for j in k: # establish connection with AP-i and STA-j as predicted in the algorithm
            STA[str(j)],Phy = WIFI.link_sta(wifiStaNodes.Get(j)) 
            StaInterface[str(j)] = ns.internet.Ipv4InterfaceContainer()
            StaInterface[str(j)] = address.Assign(STA[str(j)])
            if UL_R[j]>0:
                UL_pack = (UL_R[j]*8)/payloadSize
                client.SetAttribute ("MaxPackets", ns.core.UintegerValue (UL_pack))
                client.SetAttribute ("Interval", ns.core.TimeValue (ns.core.Time ("0.0002")))
                client.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))
                clientSta = client.Install (ns.network.NodeContainer (wifiStaNodes.Get(j)))
                clientSta.Start(ns.core.Seconds(1.0))
                clientSta.Stop(ns.core.Seconds(simulationTime + 1))

            if DL_R[j]>0:
                DL_pack = (DL_R[j]*8)/payloadSize
                client2 = ns.applications.UdpClientHelper(StaInterface[str(j)].GetAddress (0), port1)
                client2.SetAttribute ("MaxPackets", ns.core.UintegerValue (DL_pack))
                client2.SetAttribute ("Interval", ns.core.TimeValue (ns.core.Time  
                                                                     ("0.0002")))#
                client2.SetAttribute ("PacketSize", ns.core.UintegerValue (payloadSize))
                clientAp = client2.Install (ns.network.NodeContainer (wifiApNode.Get(i)))
                clientAp.Start (ns.core.Seconds (1.0))
                clientAp.Stop (ns.core.Seconds (simulationTime + 1))
                Phy.EnablePcap ("SimpleHtHiddenStations_py_Sta"+str(j),             
                                ns.network.NodeContainer(wifiStaNodes.Get(j)))
                
    ''' run simulation '''
    ns.core.Simulator.Stop(ns.core.Seconds (simulationTime + 1))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()

           
    ''' Upload and Download Throughput calculation '''
    
    ''' Upload throughput determined at AP side '''
    UL_th =[]; DL_th = []
    for i in range(nAPs):
        totalPacketsThrough = serverAp.Get(i).GetReceived()
        U_th = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0)
        UL_th.append(U_th)
    
    UL_ap = np.zeros(shape=nAPs)
    ''' Download throughput determined at STA side '''
    for j in range(nSTAs):
        totalPacketsThrough = serverSta.Get(j).GetReceived()
        D_th = totalPacketsThrough * payloadSize * 8 / (simulationTime * 1000000.0)
        UL_ap[int(STA_map[j])] = UL_ap[int(STA_map[j])] + D_th; 
        DL_th.append(D_th)
        
    ''' Store it in pandas format and write the data to a csv file '''
    res = {
           'U_Throughput_AP': pd.Series(UL_th),
           'D_Throughput_AP': pd.Series(UL_ap)
          }
#            , 'D_Throughput': pd.Series(DL_th)
#           }

    df = pd.DataFrame(res)
    df.to_csv('NW_th.csv') # this file is saved in the directory where waf and 
    
    print('=========================================================')
    print('===== Finished Simulation for the current time slot =====')#scratch file are located   
    print('=========================================================')
    
    return 0
Exemple #30
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