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 setup(self): wifi = ns.wifi.WifiHelper.Default() wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a) wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue("OfdmRate54Mbps")) wifiMac = ns.wifi.NqosWifiMacHelper.Default() wifiMac.SetType("ns3::AdhocWifiMac") wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) nodes = ns.network.NodeContainer() for i in xrange(self.options.numnodes): name = "n%s" % i n = NetnsNode(name, logfile="/tmp/%s.log" % name) self.nodes.append(n) nodes.Add(n) mobility = ns.mobility.MobilityHelper() positionAlloc = ns.mobility.ListPositionAllocator() for i in xrange(self.options.numnodes): positionAlloc.Add(ns.core.Vector(1.0 * i, 0.0, 0.0)) mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(nodes) devices = wifi.Install(wifiPhy, wifiMac, nodes) tapbridge = ns.tap_bridge.TapBridgeHelper() addrhelper, mask = parseprefix("10.0.0.0/8") for i in xrange(nodes.GetN()): n = nodes.Get(i) dev = devices.Get(i) tap = tapbridge.Install(n, dev) tap.SetMode(ns.tap_bridge.TapBridge.CONFIGURE_LOCAL) tapname = "ns3tap%d" % i tap.SetAttribute("DeviceName", ns.core.StringValue(tapname)) addr = addrhelper.NewAddress() tap.SetAttribute("IpAddress", ns.network.Ipv4AddressValue(addr)) tap.SetAttribute("Netmask", ns.network.Ipv4MaskValue(mask)) n.addnetif(tapname, ipaddrs=["%s/%s" % (addr, mask.GetPrefixLength())], rename="ath0") n.ipaddr = str(addr)
def main(argv): ns.core.GlobalValue.Bind("SimulatorImplementationType", ns.core.StringValue("ns3::RealtimeSimulatorImpl")) ns.core.GlobalValue.Bind("ChecksumEnabled", ns.core.BooleanValue("true")) nodes = ns.network.NodeContainer() nodes.Create(2) wifi = ns.wifi.WifiHelper.Default() wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a) wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue("OfdmRate54Mbps")) wifiMac = ns.wifi.NqosWifiMacHelper.Default() wifiMac.SetType("ns3::AdhocWifiMac") wifiChannel = ns.wifi.YansWifiChannelHelper.Default() wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) devices = wifi.Install(wifiPhy, wifiMac, nodes) mobility = ns.mobility.MobilityHelper() positionAlloc = ns.mobility.ListPositionAllocator() positionAlloc.Add(ns.core.Vector(0.0, 0.0, 0.0)) positionAlloc.Add(ns.core.Vector(5.0, 0.0, 0.0)) mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(nodes) tapBridge = ns.tap_bridge.TapBridgeHelper() tapBridge.SetAttribute("Mode", ns.core.StringValue("UseLocal")) tapBridge.SetAttribute("DeviceName", ns.core.StringValue("tap-left")) tapBridge.Install(nodes.Get(0), devices.Get(0)) tapBridge.SetAttribute("DeviceName", ns.core.StringValue("tap-right")) tapBridge.Install(nodes.Get(1), devices.Get(1)) ns.core.Simulator.Stop(ns.core.Seconds(600)) ns.core.Simulator.Run(signal_check_frequency=-1) ns.core.Simulator.Destroy() return 0
csma = ns.csma.CsmaHelper() csma.SetChannelAttribute("DataRate", ns.core.StringValue("100Mbps")) csma.SetChannelAttribute("Delay", ns.core.TimeValue(ns.core.NanoSeconds(6560))) csmaDevices = csma.Install(csmaNodes) wifiStaNodes = ns.network.NodeContainer() wifiStaNodes.Create(nWifi) wifiApNode = p2pNodes.Get(0) channel = ns.wifi.YansWifiChannelHelper.Default() phy = ns.wifi.YansWifiPhyHelper.Default() phy.SetChannel(channel.Create()) wifi = ns.wifi.WifiHelper.Default() wifi.SetRemoteStationManager("ns3::AarfWifiManager") mac = ns.wifi.NqosWifiMacHelper.Default() ssid = ns.wifi.Ssid("ns-3-ssid") mac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid), "ActiveProbing", ns.core.BooleanValue(False)) staDevices = wifi.Install(phy, mac, wifiStaNodes) mac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) apDevices = wifi.Install(phy, mac, wifiApNode) mobility = ns.mobility.MobilityHelper() mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX", ns.core.DoubleValue(0.0), "MinY", ns.core.DoubleValue(0.0), "DeltaX",
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
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): backboneNodes = 10 infraNodes = 5 lanNodes = 5 stopTime = 10 ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.StringValue("210")) ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue("448kb/s")) cmd = ns.core.CommandLine() cmd.Parse(argv) backbone = ns.network.NodeContainer() backbone.Create(backboneNodes) 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) print "Enabling OLSR routing on all backbone nodes" internet = ns.internet.InternetStackHelper() olsr = ns.olsr.OlsrHelper() internet.SetRoutingHelper(olsr); internet.Install(backbone); internet.Reset() ipAddrs = ns.internet.Ipv4AddressHelper() ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"), ns.network.Ipv4Mask("255.255.255.0")) ipAddrs.Assign(backboneDevices) 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) 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 newLanNodes = ns.network.NodeContainer() newLanNodes.Create(lanNodes - 1) lan = ns.network.NodeContainer(ns.network.NodeContainer(backbone.Get(i)), newLanNodes) 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) internet.Install(newLanNodes) ipAddrs.Assign(lanDevices) ipAddrs.NewNetwork() 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 stas = ns.network.NodeContainer() stas.Create(infraNodes - 1) infra = ns.network.NodeContainer(ns.network.NodeContainer(backbone.Get(i)), stas) 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)) staDevices = wifiInfra.Install(wifiPhy, macInfra, stas) 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)) infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices) internet.Install(stas) ipAddrs.Assign(infraDevices) ipAddrs.NewNetwork() 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) print "Create Applications." port = 9 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)) 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)) print "Configure Tracing." print "(tracing not done for Python)" wifiPhy.EnablePcap("mixed-wireless", backboneDevices) csma = ns.csma.CsmaHelper() csma.EnablePcapAll("mixed-wireless", False) print "Run Simulation." ns.core.Simulator.Stop(ns.core.Seconds(stopTime)) ns.core.Simulator.Run() ns.core.Simulator.Destroy()
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
def main(argv): cmd = ns.core.CommandLine() cmd.simulationTime = 10 #seconds cmd.distance = 0.0 #meters cmd.frequency = 2.4 #whether 2.4 or 5.0 GHz simulationTime = float(cmd.simulationTime) distance = float(cmd.distance) frequency = float(cmd.frequency) #Configuration arguments bandwidth = 20 mcs = 3 gi = True print("\n Configured BW:", bandwidth, "MCS:", mcs, "GI:", gi) channel = ns.wifi.YansWifiChannelHelper.Default() phy = ns.wifi.YansWifiPhyHelper.Default() wifi = ns.wifi.WifiHelper() mac = ns.wifi.NqosWifiMacHelper.Default() phy.SetChannel(channel.Create()) payloadSize = 1448 #bytes ns.core.Config.SetDefault("ns3::TcpSocket::SegmentSize", ns.core.UintegerValue(payloadSize)) wifiStaNode = ns.network.NodeContainer() wifiStaNode.Create(1) wifiApNode = ns.network.NodeContainer() wifiApNode.Create(1) wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211n_2_4GHZ) ns.core.Config.SetDefault( "ns3::LogDistancePropagationLossModel::ReferenceLoss", ns.core.DoubleValue(40.046)) # Set guard interval phy.Set("ShortGuardEnabled", ns.core.BooleanValue(gi)) mac = ns.wifi.HtWifiMacHelper.Default() DataRate = ns.wifi.HtWifiMacHelper.DataRateForMcs(mcs) wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", DataRate, "ControlMode", DataRate) ssid = ns.wifi.Ssid("wifi-80211n") mac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid), "ActiveProbing", ns.core.BooleanValue(False)) staDevice = wifi.Install(phy, mac, wifiStaNode) mac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) apDevice = wifi.Install(phy, mac, wifiApNode) # Set channel width ns.core.Config.Set( "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue(bandwidth)) # mobility mobility = ns.mobility.MobilityHelper() positionAlloc = ns.mobility.ListPositionAllocator() positionAlloc.Add(ns.core.Vector3D(0.0, 0.0, 0.0)) positionAlloc.Add(ns.core.Vector3D(distance, 0.0, 0.0)) mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(wifiApNode) mobility.Install(wifiStaNode) # Internet stack stack = ns.internet.InternetStackHelper() stack.Install(wifiApNode) stack.Install(wifiStaNode) address = ns.internet.Ipv4AddressHelper() address.SetBase(ns.network.Ipv4Address("192.168.1.0"), ns.network.Ipv4Mask("255.255.255.0")) staNodeInterface = address.Assign(staDevice) apNodeInterface = address.Assign(apDevice) # Setting applications serverApp = ns.network.ApplicationContainer() sinkApp = ns.network.ApplicationContainer() port = 50000 apLocalAddress = ns.network.Address( ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port)) packetSinkHelper = ns.applications.PacketSinkHelper( "ns3::TcpSocketFactory", apLocalAddress) sinkApp = packetSinkHelper.Install(wifiStaNode.Get(0)) print("\n Application is starting ! \n") sinkApp.Start(ns.core.Seconds(0.0)) sinkApp.Stop(ns.core.Seconds(simulationTime + 1)) onoff = ns.applications.OnOffHelper("ns3::TcpSocketFactory", ns.network.Ipv4Address.GetAny()) onoff.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")) onoff.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")) onoff.SetAttribute("PacketSize", ns.core.UintegerValue(payloadSize)) onoff.SetAttribute("DataRate", ns.network.DataRateValue( ns.network.DataRate(1000000000))) # bit/s apps = ns.network.ApplicationContainer() remoteAddress = ns.network.AddressValue( ns.network.InetSocketAddress(staNodeInterface.GetAddress(0), port)) onoff.SetAttribute("Remote", remoteAddress) apps.Add(onoff.Install(wifiApNode.Get(0))) apps.Start(ns.core.Seconds(1.0)) apps.Stop(ns.core.Seconds(simulationTime + 1)) ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables() ns.core.Simulator.Stop(ns.core.Seconds(simulationTime + 1)) ns.core.Simulator.Run() ns.core.Simulator.Destroy() throughput = 0 # TCP totalPacketsThrough = sinkApp.Get(0).GetTotalRx() throughput = totalPacketsThrough * 8 / (simulationTime * 1000000.0 ) # Mbit/s print "*** Throughput: ", throughput, " Mbit/s***" return 0
def main(argv): 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()
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): 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(): 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()
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
cmd.Parse(sys.argv) nodeNum = int(cmd.nodeNum) duration = float(cmd.duration) tmin = float(cmd.tmin) tmax = float(cmd.tmax) traceFile = cmd.traceFile wifiNodes = ns.network.NodeContainer() wifiNodes.Create(nodeNum) 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()) wifiDevices = wifi.Install(wifiPhy, mac, wifiNodes) # # Add the IPv4 protocol stack to the nodes in our container # internet = ns.internet.InternetStackHelper() internet.Install(wifiNodes) # Assign IPv4 addresses to the device drivers(actually to the associated # IPv4 interfaces) we just created.
def main(argv): simulationTime = 40 #seconds distance = 0.0 #meters simulationTime = float(simulationTime) distance = float(distance) #Configuration arguments bandwidth = 40 mcs = 3 gi = False expected_val = 54 channel = ns.wifi.YansWifiChannelHelper.Default() phy = ns.wifi.YansWifiPhyHelper.Default() wifi = ns.wifi.WifiHelper() mac = ns.wifi.WifiMacHelper() phy.SetPcapDataLinkType(ns.wifi.WifiPhyHelper.DLT_IEEE802_11_RADIO) phy.SetChannel(channel.Create()) wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211ac) wifiStaNode = ns.network.NodeContainer() wifiStaNode.Create(1) wifiApNode = ns.network.NodeContainer() wifiApNode.Create(1) # Set guard interval #phy.Set ("ShortGuardEnabled", ns.core.BooleanValue (gi)) #mac = ns.wifi.VhtWifiMacHelper.Default () DataRate = "VhtMcs" + str(mcs) wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue(DataRate), "ControlMode", ns.core.StringValue(DataRate)) ssid = ns.wifi.Ssid("wifi-80211ac") mac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid), "QosSupported", ns.core.BooleanValue(True), "ActiveProbing", ns.core.BooleanValue(False), "BE_MaxAmsduSize", ns.core.UintegerValue(0), "BK_MaxAmsduSize", ns.core.UintegerValue(0), "VI_MaxAmsduSize", ns.core.UintegerValue(0), "VO_MaxAmsduSize", ns.core.UintegerValue(0), "BE_MaxAmpduSize", ns.core.UintegerValue(65535), "BK_MaxAmpduSize", ns.core.UintegerValue(0), "VI_MaxAmpduSize", ns.core.UintegerValue(65535), "VO_MaxAmpduSize", ns.core.UintegerValue(0)) #Default settings #mac.SetType ("ns3::StaWifiMac", "QosSupported", ns.core.BooleanValue (True), "Ssid", ns.wifi.SsidValue (ssid)) staDevice = wifi.Install(phy, mac, wifiStaNode.Get(0)) mac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid), "QosSupported", ns.core.BooleanValue(True), "BE_MaxAmsduSize", ns.core.UintegerValue(0), "BK_MaxAmsduSize", ns.core.UintegerValue(0), "VI_MaxAmsduSize", ns.core.UintegerValue(0), "VO_MaxAmsduSize", ns.core.UintegerValue(0), "BE_MaxAmpduSize", ns.core.UintegerValue(65535), "BK_MaxAmpduSize", ns.core.UintegerValue(0), "VI_MaxAmpduSize", ns.core.UintegerValue(65535), "VO_MaxAmpduSize", ns.core.UintegerValue(0)) #Default settings apDevice = wifi.Install(phy, mac, wifiApNode.Get(0)) # Set channel width ns.core.Config.Set( "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue(bandwidth)) # mobility mobility = ns.mobility.MobilityHelper() positionAlloc = ns.mobility.ListPositionAllocator() positionAlloc.Add(ns.core.Vector3D(0.0, 0.0, 0.0)) positionAlloc.Add(ns.core.Vector3D(distance, 0.0, 0.0)) mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(wifiApNode) mobility.Install(wifiStaNode) # Internet stack stack = ns.internet.InternetStackHelper() stack.Install(wifiApNode) stack.Install(wifiStaNode) address = ns.internet.Ipv4AddressHelper() address.SetBase(ns.network.Ipv4Address("192.168.1.0"), ns.network.Ipv4Mask("255.255.255.0")) staNodeInterface = address.Assign(staDevice) apNodeInterface = address.Assign(apDevice) ns.core.Config.SetDefault("ns3::TcpSocket::SegmentSize", ns.core.UintegerValue(1452)) print(staNodeInterface) print(apNodeInterface) # Setting applications serverApp = ns.network.ApplicationContainer() sinkApp = ns.network.ApplicationContainer() viPort_1 = 9999 viPort_2 = 9996 voPort_1 = 9998 voPort_2 = 9997 bePort = 9994 #ToS values: {0x70, 0x28, 0xb8, 0xc0}; //AC_BE, AC_BK, AC_VI, AC_VO #Video 1 ipv4 = wifiStaNode.Get(0).GetObject(ns.internet.Ipv4.GetTypeId()) adr = ipv4.GetAddress(1, 0).GetLocal() print("Sta IP Addr:") print(adr) sinkSocket = ns.network.InetSocketAddress(adr, viPort_1) sinkSocket.SetTos(0xb8) onOffHelper = ns.applications.OnOffHelper("ns3::TcpSocketFactory", sinkSocket) onOffHelper.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute("DataRate", ns.core.StringValue("11Mbps")) onOffHelper.SetAttribute("PacketSize", ns.core.UintegerValue(1452)) onOffHelper.SetAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(1.001))) serverApp.Add(onOffHelper.Install(wifiApNode.Get(0))) packetSinkHelper = ns.applications.PacketSinkHelper( "ns3::TcpSocketFactory", sinkSocket) sinkApp.Add(packetSinkHelper.Install(wifiStaNode.Get(0))) #Voice-1 ipv4 = wifiStaNode.Get(0).GetObject(ns.internet.Ipv4.GetTypeId()) adr = ipv4.GetAddress(1, 0).GetLocal() sinkSocket = ns.network.InetSocketAddress(adr, voPort_1) sinkSocket.SetTos(0xc0) onOffHelper = ns.applications.OnOffHelper("ns3::UdpSocketFactory", sinkSocket) onOffHelper.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute("DataRate", ns.core.StringValue("90Kbps")) onOffHelper.SetAttribute("PacketSize", ns.core.UintegerValue(160)) onOffHelper.SetAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(10.001))) serverApp.Add(onOffHelper.Install(wifiApNode.Get(0))) packetSinkHelper = ns.applications.PacketSinkHelper( "ns3::UdpSocketFactory", sinkSocket) sinkApp.Add(packetSinkHelper.Install(wifiStaNode.Get(0))) ## ipv4 = wifiApNode.Get(0).GetObject(ns.internet.Ipv4.GetTypeId()) adr = ipv4.GetAddress(1, 0).GetLocal() sinkSocket = ns.network.InetSocketAddress(adr, voPort_2) sinkSocket.SetTos(0xc0) onOffHelper = ns.applications.OnOffHelper("ns3::UdpSocketFactory", sinkSocket) onOffHelper.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute("DataRate", ns.core.StringValue("90Kbps")) onOffHelper.SetAttribute("PacketSize", ns.core.UintegerValue(160)) onOffHelper.SetAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(10.001))) serverApp.Add(onOffHelper.Install(wifiStaNode.Get(0))) packetSinkHelper = ns.applications.PacketSinkHelper( "ns3::UdpSocketFactory", sinkSocket) sinkApp.Add(packetSinkHelper.Install(wifiApNode.Get(0))) #BestEffort ipv4 = wifiStaNode.Get(0).GetObject(ns.internet.Ipv4.GetTypeId()) adr = ipv4.GetAddress(1, 0).GetLocal() sinkSocket = ns.network.InetSocketAddress(adr, bePort) sinkSocket.SetTos(0x70) onOffHelper = ns.applications.OnOffHelper("ns3::TcpSocketFactory", sinkSocket) onOffHelper.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute("DataRate", ns.core.StringValue("1Mbps")) onOffHelper.SetAttribute("PacketSize", ns.core.UintegerValue(750)) onOffHelper.SetAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(30.001))) serverApp.Add(onOffHelper.Install(wifiApNode.Get(0))) packetSinkHelper = ns.applications.PacketSinkHelper( "ns3::TcpSocketFactory", sinkSocket) sinkApp.Add(packetSinkHelper.Install(wifiStaNode.Get(0))) ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables() phy.EnablePcap("AP_Scen4_NS3.pcap", apDevice.Get(0)) phy.EnablePcap("AP_Scen4STA_NS3.pcap", staDevice.Get(0)) ns.core.Config.SetDefault("ns3::ConfigStore::Filename", ns.core.StringValue("output-attr.txt")) ns.core.Config.SetDefault("ns3::ConfigStore::FileFormat", ns.core.StringValue("RawText")) ns.core.Config.SetDefault("ns3::ConfigStore::Mode", ns.core.StringValue("Save")) outputConfig = ns.config_store.ConfigStore() outputConfig.ConfigureDefaults() outputConfig.ConfigureAttributes() ns.core.Simulator.Stop(ns.core.Seconds(simulationTime + 1)) ns.core.Simulator.Run() ns.core.Simulator.Destroy() return 0
def main(argv): 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
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
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
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): # # 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()
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
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
def experiment(enableCtsRts): # 0. Enable or disable CTS/RTS ctsThr = 100 if enableCtsRts else 2200 ns.core.Config.SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", ns.core.UintegerValue (ctsThr)) # 1. Create 3 nodes nodes = ns.network.NodeContainer () nodes.Create (3) # 2. Place nodes somehow, this is required by every wireless simulation i = 0 while i < 3: nodes.Get (i).AggregateObject (ns.mobility.ConstantPositionMobilityModel ()) i += 1 # 3. Create propagation loss matrix lossModel = ns.propagation.MatrixPropagationLossModel () lossModel.SetDefaultLoss (200) #set default loss to 200 dB (no link) lossModel.SetLoss (nodes.Get (0).GetObject (ns.mobility.MobilityModel.GetTypeId ()), nodes.Get (1).GetObject (ns.mobility.MobilityModel.GetTypeId ()), 50) lossModel.SetLoss (nodes.Get (2).GetObject (ns.mobility.MobilityModel.GetTypeId ()), nodes.Get (1).GetObject (ns.mobility.MobilityModel.GetTypeId ()), 50) # 4. Create & setup wifi channel wifiChannel = ns.wifi.YansWifiChannel () wifiChannel.SetPropagationLossModel (lossModel) wifiChannel.SetPropagationDelayModel (ns.propagation.ConstantSpeedPropagationDelayModel ()) # 5. Install wireless devices wifi = ns.wifi.WifiHelper () wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211b) wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue ("DsssRate2Mbps"), "ControlMode", ns.core.StringValue ("DsssRate1Mbps")) wifiPhy = ns.wifi.YansWifiPhyHelper.Default () wifiPhy.SetChannel (wifiChannel) wifiMac = ns.wifi.NqosWifiMacHelper.Default () wifiMac.SetType ("ns3::AdhocWifiMac") # use ad-hoc MAC devices = wifi.Install (wifiPhy,wifiMac,nodes) # uncomment the following to have athstats output # athstats=ns3.AthstatsHelper () # athstats.EnableAthstats ("rtscts-athstats-node-py" if enableCtsRts else "basic-athstats-node-py", nodes) # uncomment the following to have pcap output # wifiPhy.EnablePcap ("rtscts-pcap-node-py" if enableCtsRts else "basic-pcap-node-py",nodes) # 6. Install TCP/IP stack & assign IP addresses internet = ns.internet.InternetStackHelper () internet.Install (nodes) ipv4 = ns.internet.Ipv4AddressHelper () ipv4.SetBase (ns.network.Ipv4Address ("10.0.0.0"), ns.network.Ipv4Mask ("255.0.0.0")) ipv4.Assign (devices) # 7. Install applications: two CBR streams each saturating the channel cbrApps = ns.network.ApplicationContainer () cbrPort = 12345 onOffHelper = ns.applications.OnOffHelper ("ns3::UdpSocketFactory", ns.network.InetSocketAddress (ns.network.Ipv4Address ("10.0.0.2"), cbrPort)) onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (1400)) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) # flow 1: node 0 -> node 1 onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("3000000bps")) onOffHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (1.000000))) cbrApps.Add (onOffHelper.Install (nodes.Get (0))) # flow 2: node 2 -> node 1 # \internal # The slightly different start times and data rates are a workaround # for \bugid{388} and \bugid{912} # onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("3001100bps")) onOffHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (1.001))) cbrApps.Add (onOffHelper.Install (nodes.Get (2))) # \internal # We also use separate UDP applications that will send a single # packet before the CBR flows start. # This is a workaround for the lack of perfect ARP, see \bugid{187} # echoPort = 9 echoClientHelper = ns.applications.UdpEchoClientHelper (ns.network.Ipv4Address ("10.0.0.2"), echoPort) echoClientHelper.SetAttribute ("MaxPackets", ns.core.UintegerValue (1)) echoClientHelper.SetAttribute ("Interval", ns.core.TimeValue (ns.core.Seconds (0.1))) echoClientHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (10)) pingApps = ns.network.ApplicationContainer () # again using different start times to workaround Bug 388 and Bug 912 echoClientHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (0.001))) pingApps.Add (echoClientHelper.Install(nodes.Get (0))) echoClientHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (0.006))) pingApps.Add (echoClientHelper.Install (nodes.Get (2))) # 8. Install FlowMonitor on all nodes flowmon = ns.flow_monitor.FlowMonitorHelper () monitor = flowmon.InstallAll () # 9. Run simulation for 10 seconds ns.core.Simulator.Stop (ns.core.Seconds (10)) ns.core.Simulator.Run () # 10. Print per flow statistics monitor.CheckForLostPackets () classifier = ns.flow_monitor.Ipv4FlowClassifier () classifier = flowmon.GetClassifier () stats = monitor.GetFlowStats () for flow_id, flow_stats in monitor.GetFlowStats (): # first 2 FlowIds are for ECHO apps, we don't want to display them # Duration for throughput measurement is 9.0 seconds, since # StartTime of the OnOffApplication is at about "second 1" # and # Simulator::Stops at "second 10". t = classifier.FindFlow(flow_id) if flow_id > 2: print "FlowID %i (%s -> %s)" % \ (flow_id-2, t.sourceAddress, t.destinationAddress) print >> sys.stdout, " Tx Packets: ", flow_stats.txPackets print >> sys.stdout, " Tx Bytes: ", flow_stats.txBytes print >> sys.stdout, " TxOffered: ", flow_stats.txBytes * 8.0 / 9.0 / 1000 / 1000 , " Mbps" print >> sys.stdout, " Rx Packets: ", flow_stats.rxPackets print >> sys.stdout, " Rx Bytes: ", flow_stats.rxBytes print >> sys.stdout, " Throughput: ", flow_stats.rxBytes * 8.0 / 9.0 / 1000 / 1000 , " Mbps" # 11. Cleanup ns.core.Simulator.Destroy ()
wifiStaNodes = ns.network.NodeContainer () wifiStaNodes.Create (2) wifiApNode = ns.network.NodeContainer () wifiApNode.Create (1) channel = ns.wifi.YansWifiChannelHelper.Default () channel.AddPropagationLoss ("ns3::RangePropagationLossModel") # wireless range limited to 5 meters! phy = ns.wifi.YansWifiPhyHelper.Default () phy.SetPcapDataLinkType (ns.wifi.YansWifiPhyHelper.DLT_IEEE802_11_RADIO) phy.SetChannel (channel.Create ()) wifi = ns.wifi.WifiHelper.Default () wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211n_5GHZ) wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue ("HtMcs7"), "ControlMode", ns.core.StringValue ("HtMcs0")) mac = ns.wifi.HtWifiMacHelper.Default () ssid = ns.wifi.Ssid ("simple-mpdu-aggregation") mac.SetType ("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue (ssid), "ActiveProbing", ns.core.BooleanValue (False), "BE_MaxAmpduSize", ns.core.UintegerValue (maxAmpduSize)) staDevices = ns.network.NetDeviceContainer () staDevices = wifi.Install (phy, mac, wifiStaNodes) mac.SetType ("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue (ssid), "BeaconInterval", ns.core.TimeValue (ns.core.MicroSeconds (102400)), "BeaconGeneration", ns.core.BooleanValue (True),
def main(argv): simulationTime = 15 #seconds distance = 0.0 #meters simulationTime = float(simulationTime) distance = float(distance) #Configuration arguments bandwidth = 40 mcs = 3 gi = False expected_val= 54 channel = ns.wifi.YansWifiChannelHelper.Default () phy = ns.wifi.YansWifiPhyHelper.Default () wifi = ns.wifi.WifiHelper () mac = ns.wifi.WifiMacHelper () phy.SetPcapDataLinkType (ns.wifi.WifiPhyHelper.DLT_IEEE802_11_RADIO) phy.SetChannel (channel.Create ()) wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211ac) wifiStaNode = ns.network.NodeContainer () wifiStaNode.Create (5) wifiApNode = ns.network.NodeContainer () wifiApNode.Create (1) # Set guard interval #phy.Set ("ShortGuardEnabled", ns.core.BooleanValue (gi)) #mac = ns.wifi.VhtWifiMacHelper.Default () DataRate = "VhtMcs"+str(mcs) wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager","DataMode", ns.core.StringValue(DataRate), "ControlMode", ns.core.StringValue(DataRate)) ssid = ns.wifi.Ssid ("wifi-80211ac") mac.SetType ("ns3::StaWifiMac", "QosSupported", ns.core.BooleanValue (True), "Ssid", ns.wifi.SsidValue (ssid)) staDevice = wifi.Install (phy, mac, wifiStaNode) mac.SetType ("ns3::ApWifiMac","QosSupported", ns.core.BooleanValue (True), "Ssid", ns.wifi.SsidValue (ssid)) apDevice = wifi.Install (phy, mac, wifiApNode) # Set channel width ns.core.Config.Set ("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth", ns.core.UintegerValue (bandwidth)) # mobility mobility = ns.mobility.MobilityHelper () positionAlloc = ns.mobility.ListPositionAllocator () positionAlloc.Add (ns.core.Vector3D (0.0, 0.0, 0.0)) positionAlloc.Add (ns.core.Vector3D (distance, 0.0, 0.0)) mobility.SetPositionAllocator (positionAlloc) mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel") mobility.Install (wifiApNode) mobility.Install (wifiStaNode) # Internet stack stack = ns.internet.InternetStackHelper () stack.Install (wifiApNode) stack.Install (wifiStaNode) address = ns.internet.Ipv4AddressHelper () address.SetBase (ns.network.Ipv4Address ("192.168.1.0"), ns.network.Ipv4Mask ("255.255.255.0")) staNodeInterface = address.Assign (staDevice) apNodeInterface = address.Assign (apDevice) ns.core.Config.SetDefault ("ns3::TcpSocket::SegmentSize", ns.core.UintegerValue (1024)) # Setting applications serverApp = ns.network.ApplicationContainer () sinkApp = ns.network.ApplicationContainer () viPort = 9999 voPort_1 = 9998 voPort_2 = 9997 voPort_3 = 9996 voPort_4 = 9995 bePort = 9994 bkPort = 9993 ipv4 = wifiStaNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ()) adr = ipv4.GetAddress (1,0).GetLocal () print("Sta IP Addr:") print(adr) sinkSocket = ns.network.InetSocketAddress (adr, viPort) sinkSocket.SetTos (0x4) onOffHelper = ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("20Mbps")) #20Mbps onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (1024)) onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (1.001 + random.uniform(0,0.1)))) serverApp.Add (onOffHelper.Install(wifiApNode.Get(0))) packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket) sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (0))) #Voice - 1 ipv4 = wifiStaNode.Get (1).GetObject(ns.internet.Ipv4.GetTypeId ()) adr = ipv4.GetAddress (1,0).GetLocal () sinkSocket = ns.network.InetSocketAddress (adr, voPort_1) sinkSocket.SetTos (0x6) onOffHelper=ns.applications.OnOffHelper ("ns3::UdpSocketFactory", sinkSocket) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("64Kbps")) onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (160)) onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (5.001))) serverApp.Add (onOffHelper.Install(wifiApNode.Get(0))) packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::UdpSocketFactory", sinkSocket) sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (1))) ## ipv4 = wifiApNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ()) adr = ipv4.GetAddress (1,0).GetLocal () sinkSocket = ns.network.InetSocketAddress (adr, voPort_1) sinkSocket.SetTos (0x6) onOffHelper=ns.applications.OnOffHelper ("ns3::UdpSocketFactory", sinkSocket) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("64Kbps")) onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (160)) onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (5.001+random.uniform(0,0.1)))) serverApp.Add (onOffHelper.Install(wifiStaNode.Get(1))) packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::UdpSocketFactory", sinkSocket) sinkApp.Add (packetSinkHelper.Install (wifiApNode.Get (0))) #Voice - 2 ipv4 = wifiStaNode.Get (2).GetObject(ns.internet.Ipv4.GetTypeId ()) adr = ipv4.GetAddress (1,0).GetLocal () sinkSocket = ns.network.InetSocketAddress (adr, voPort_2) sinkSocket.SetTos (0x6) onOffHelper=ns.applications.OnOffHelper ("ns3::UdpSocketFactory", sinkSocket) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("64Kbps")) onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (160)) onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (5.001))) serverApp.Add (onOffHelper.Install(wifiApNode.Get(0))) packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::UdpSocketFactory", sinkSocket) # sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (2))) ## ipv4 = wifiApNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ()) adr = ipv4.GetAddress (1,0).GetLocal () sinkSocket = ns.network.InetSocketAddress (adr, voPort_2) sinkSocket.SetTos (0x6) onOffHelper=ns.applications.OnOffHelper ("ns3::UdpSocketFactory", sinkSocket) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("64Kbps")) onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (160)) onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (5.001+random.uniform(0,0.1)))) serverApp.Add (onOffHelper.Install(wifiStaNode.Get(2))) packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::UdpSocketFactory", sinkSocket) sinkApp.Add (packetSinkHelper.Install (wifiApNode.Get (0))) #BestEffort ipv4 = wifiStaNode.Get (3).GetObject(ns.internet.Ipv4.GetTypeId ()) adr = ipv4.GetAddress (1,0).GetLocal () sinkSocket = ns.network.InetSocketAddress (adr, bePort) sinkSocket.SetTos (0x0) onOffHelper=ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("161Kbps")) onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (501)) onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (10.001+random.uniform(0,0.1)))) serverApp.Add (onOffHelper.Install(wifiApNode.Get(0))) packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket) sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (3))) ## ipv4 = wifiApNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ()) adr = ipv4.GetAddress (1,0).GetLocal () sinkSocket = ns.network.InetSocketAddress (adr, bePort) sinkSocket.SetTos (0x0) onOffHelper=ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("161Kbps")) onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (501)) onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (10.001+random.uniform(0,0.1)))) serverApp.Add (onOffHelper.Install(wifiStaNode.Get(3))) packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket) sinkApp.Add (packetSinkHelper.Install (wifiApNode.Get (0))) #BackGroun ipv4 = wifiStaNode.Get (4).GetObject(ns.internet.Ipv4.GetTypeId ()) adr = ipv4.GetAddress (1,0).GetLocal () sinkSocket = ns.network.InetSocketAddress (adr, bkPort) sinkSocket.SetTos (0x1) onOffHelper=ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("250Kbps")) onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (750)) onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (10.001+random.uniform(0,0.1)))) serverApp.Add (onOffHelper.Install(wifiApNode.Get(0))) packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket) sinkApp.Add (packetSinkHelper.Install (wifiStaNode.Get (4))) ## ipv4 = wifiApNode.Get (0).GetObject(ns.internet.Ipv4.GetTypeId ()) adr = ipv4.GetAddress (1,0).GetLocal () sinkSocket = ns.network.InetSocketAddress (adr, bkPort) sinkSocket.SetTos (0x1) onOffHelper=ns.applications.OnOffHelper ("ns3::TcpSocketFactory", sinkSocket) onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]")) onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("250Kbps")) onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (750)) onOffHelper.SetAttribute ("StartTime" , ns.core.TimeValue (ns.core.Seconds (10.001+random.uniform(0,0.1)))) serverApp.Add (onOffHelper.Install(wifiStaNode.Get(4))) packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", sinkSocket) sinkApp.Add (packetSinkHelper.Install (wifiApNode.Get (0))) ## ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables () phy.EnablePcap( "AP.pcap", apDevice.Get (0)) ns.core.Simulator.Stop (ns.core.Seconds (simulationTime+1)) ns.core.Simulator.Run () ns.core.Simulator.Destroy () return 0
def main(argv): cmd = ns.core.CommandLine() cmd.NumNodesSide = None cmd.AddValue( "NumNodesSide", "Grid side number of nodes (total number of nodes will be this number squared)" ) cmd.Results = None cmd.AddValue("Results", "Write XML results to file") cmd.Plot = None cmd.AddValue("Plot", "Plot the results using the matplotlib python module") cmd.Parse(argv) wifi = ns.wifi.WifiHelper.Default() wifiMac = ns.wifi.NqosWifiMacHelper.Default() 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.SetType("ns3::AdhocWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) internet = ns.internet.InternetStackHelper() list_routing = ns.internet.Ipv4ListRoutingHelper() olsr_routing = ns.olsr.OlsrHelper() static_routing = ns.internet.Ipv4StaticRoutingHelper() list_routing.Add(static_routing, 0) list_routing.Add(olsr_routing, 100) internet.SetRoutingHelper(list_routing) ipv4Addresses = ns.internet.Ipv4AddressHelper() ipv4Addresses.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0")) port = 9 # Discard port(RFC 863) onOffHelper = ns.applications.OnOffHelper( "ns3::UdpSocketFactory", ns.network.Address( ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"), port))) onOffHelper.SetAttribute( "DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps"))) onOffHelper.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")) addresses = [] nodes = [] if cmd.NumNodesSide is None: num_nodes_side = NUM_NODES_SIDE else: num_nodes_side = int(cmd.NumNodesSide) for xi in range(num_nodes_side): for yi in range(num_nodes_side): node = ns.network.Node() nodes.append(node) internet.Install(ns.network.NodeContainer(node)) mobility = ns.mobility.ConstantPositionMobilityModel() mobility.SetPosition( ns.core.Vector(xi * DISTANCE, yi * DISTANCE, 0)) node.AggregateObject(mobility) devices = wifi.Install(wifiPhy, wifiMac, node) ipv4_interfaces = ipv4Addresses.Assign(devices) addresses.append(ipv4_interfaces.GetAddress(0)) for i, node in enumerate(nodes): destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)] #print i, destaddr onOffHelper.SetAttribute( "Remote", ns.network.AddressValue( ns.network.InetSocketAddress(destaddr, port))) app = onOffHelper.Install(ns.network.NodeContainer(node)) urv = ns.core.UniformRandomVariable() app.Start(ns.core.Seconds(urv.GetValue(20, 30))) #internet.EnablePcapAll("wifi-olsr") flowmon_helper = ns.flow_monitor.FlowMonitorHelper() #flowmon_helper.SetMonitorAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(31))) monitor = flowmon_helper.InstallAll() monitor = flowmon_helper.GetMonitor() monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) ns.core.Simulator.Stop(ns.core.Seconds(44.0)) ns.core.Simulator.Run() def print_stats(os, st): print >> os, " Tx Bytes: ", st.txBytes print >> os, " Rx Bytes: ", st.rxBytes print >> os, " Tx Packets: ", st.txPackets print >> os, " Rx Packets: ", st.rxPackets print >> os, " Lost Packets: ", st.lostPackets if st.rxPackets > 0: print >> os, " Mean{Delay}: ", (st.delaySum.GetSeconds() / st.rxPackets) print >> os, " Mean{Jitter}: ", (st.jitterSum.GetSeconds() / (st.rxPackets - 1)) print >> os, " Mean{Hop Count}: ", float( st.timesForwarded) / st.rxPackets + 1 if 0: print >> os, "Delay Histogram" for i in range(st.delayHistogram.GetNBins()): print >> os, " ",i,"(", st.delayHistogram.GetBinStart (i), "-", \ st.delayHistogram.GetBinEnd (i), "): ", st.delayHistogram.GetBinCount (i) print >> os, "Jitter Histogram" for i in range(st.jitterHistogram.GetNBins()): print >> os, " ",i,"(", st.jitterHistogram.GetBinStart (i), "-", \ st.jitterHistogram.GetBinEnd (i), "): ", st.jitterHistogram.GetBinCount (i) print >> os, "PacketSize Histogram" for i in range(st.packetSizeHistogram.GetNBins()): print >> os, " ",i,"(", st.packetSizeHistogram.GetBinStart (i), "-", \ st.packetSizeHistogram.GetBinEnd (i), "): ", st.packetSizeHistogram.GetBinCount (i) for reason, drops in enumerate(st.packetsDropped): print " Packets dropped by reason %i: %i" % (reason, drops) #for reason, drops in enumerate(st.bytesDropped): # print "Bytes dropped by reason %i: %i" % (reason, drops) monitor.CheckForLostPackets() classifier = flowmon_helper.GetClassifier() if cmd.Results is None: for flow_id, flow_stats in monitor.GetFlowStats(): t = classifier.FindFlow(flow_id) proto = {6: 'TCP', 17: 'UDP'}[t.protocol] print "FlowID: %i (%s %s/%s --> %s/%i)" % \ (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort) print_stats(sys.stdout, flow_stats) else: print monitor.SerializeToXmlFile(cmd.Results, True, True) if cmd.Plot is not None: import pylab delays = [] for flow_id, flow_stats in monitor.GetFlowStats(): tupl = classifier.FindFlow(flow_id) if tupl.protocol == 17 and tupl.sourcePort == 698: continue delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets) pylab.hist(delays, 20) pylab.xlabel("Delay (s)") pylab.ylabel("Number of Flows") pylab.show() return 0
def Run(self, *positional_parameters, **keyword_parameters): ns.network.Packet.EnablePrinting() if "SINKS" in os.environ: self.m_nSinks = int(os.environ["SINKS"]) if "TXP" in os.environ: self.m_txp = float(os.environ["TXP"]) if "TOTAL_TIME" in os.environ: self.m_total_time = int(os.environ["TOTAL_TIME"]) if "NODES" in os.environ: self.m_nodes = int(os.environ["NODES"]) if "PROTOCOL" in os.environ: self.m_protocol = int(os.environ["PROTOCOL"]) if "NODE_SPEED" in os.environ: self.m_node_speed = int(os.environ["NODE_SPEED"]) if "NODE_PAUSE" in os.environ: self.m_node_pause = int(os.environ["NODE_PAUSE"]) if "FILE_NAME" in os.environ: self.m_CSVfileName = os.environ["FILE_NAME"] if 'nSinks' in keyword_parameters: self.m_nSinks = keyword_parameters['nSinks'] if 'txp' in keyword_parameters: self.m_txp = keyword_parameters['txp'] if 'TotalTime' in keyword_parameters: self.m_total_time = keyword_parameters['TotalTime'] if 'Nodes' in keyword_parameters: self.m_nodes = keyword_parameters['Nodes'] if 'Protocol' in keyword_parameters: self.m_protocol = keyword_parameters['Protocol'] if 'NodeSpeed' in keyword_parameters: self.m_node_speed = keyword_parameters['NodeSpeed'] if 'NodePause' in keyword_parameters: self.m_node_pause = keyword_parameters['NodePause'] if 'CSVfileName' in keyword_parameters: self.m_CSVfileName = keyword_parameters['CSVfileName'] self.m_CSVfileName += "." + str(time.time()) rate = "2048bps" phyMode = "DsssRate11Mbps" tr_name = self.m_CSVfileName + "-compare" self.m_protocolName = "protocol" ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.StringValue("64")) ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue(rate)) ns.core.Config.SetDefault( "ns3::WifiRemoteStationManager::NonUnicastMode", ns.core.StringValue(phyMode)) adhocNodes = ns.network.NodeContainer() adhocNodes.Create(self.m_nodes) wifi = ns.wifi.WifiHelper() wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211b) wifiPhy = ns.wifi.YansWifiPhyHelper.Default() wifiChannel = ns.wifi.YansWifiChannelHelper() wifiChannel.SetPropagationDelay( "ns3::ConstantSpeedPropagationDelayModel") wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel") wifiPhy.SetChannel(wifiChannel.Create()) wifiMac = ns.wifi.WifiMacHelper() wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue(phyMode), "ControlMode", ns.core.StringValue(phyMode)) wifiPhy.Set("TxPowerStart", ns.core.DoubleValue(self.m_txp)) wifiPhy.Set("TxPowerEnd", ns.core.DoubleValue(self.m_txp)) wifiMac.SetType("ns3::AdhocWifiMac") adhocDevices = wifi.Install(wifiPhy, wifiMac, adhocNodes) # type: NetDeviceContainer mobilityAdhoc = ns.mobility.MobilityHelper() streamIndex = 0 # used to get consistent mobility across scenarios pos = ns.core.ObjectFactory() pos.SetTypeId("ns3::RandomRectanglePositionAllocator") pos.Set( "X", ns.core.StringValue( "ns3::UniformRandomVariable[Min=0.0|Max=300.0]")) pos.Set( "Y", ns.core.StringValue( "ns3::UniformRandomVariable[Min=0.0|Max=1500.0]")) # Same as: Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> (); taPositionAlloc = pos.Create().GetObject( ns.mobility.PositionAllocator.GetTypeId( )) # type: Ptr<PositionAllocator> streamIndex += taPositionAlloc.AssignStreams(streamIndex) ssSpeed = "ns3::UniformRandomVariable[Min=0.0|Max=%s]" % self.m_node_speed ssPause = "ns3::ConstantRandomVariable[Constant=%s]" % self.m_node_pause mobilityAdhoc.SetMobilityModel("ns3::RandomWaypointMobilityModel", "Speed", ns.core.StringValue(ssSpeed), "Pause", ns.core.StringValue(ssPause), "PositionAllocator", ns.core.PointerValue(taPositionAlloc)) mobilityAdhoc.SetPositionAllocator(taPositionAlloc) mobilityAdhoc.Install(adhocNodes) streamIndex += mobilityAdhoc.AssignStreams(adhocNodes, streamIndex) # NS_UNUSED(streamIndex) # From this point, streamIndex is unused aodv = ns.aodv.AodvHelper() olsr = ns.olsr.OlsrHelper() dsdv = ns.dsdv.DsdvHelper() dsr = ns.dsr.DsrHelper() dsrMain = ns.dsr.DsrMainHelper() list = ns.internet.Ipv4ListRoutingHelper() internet = ns.internet.InternetStackHelper() if self.m_protocol == 1: list.Add(olsr, 100) self.m_protocolName = "OLSR" elif self.m_protocol == 2: list.Add(aodv, 100) self.m_protocolName = "AODV" elif self.m_protocol == 3: list.Add(dsdv, 100) self.m_protocolName = "DSDV" elif self.m_protocol == 4: self.m_protocolName = "DSR" else: print("No such protocol:%s" % str(self.m_protocol) ) # NS_FATAL_ERROR ("No such protocol:" << m_protocol); if self.m_protocol < 4: internet.SetRoutingHelper(list) internet.Install(adhocNodes) elif self.m_protocol == 4: internet.Install(adhocNodes) dsrMain.Install(dsr, adhocNodes) print("assigning ip address") addressAdhoc = ns.internet.Ipv4AddressHelper() addressAdhoc.SetBase(ns.network.Ipv4Address("10.1.1.0"), ns.network.Ipv4Mask("255.255.255.0")) adhocInterfaces = addressAdhoc.Assign(adhocDevices) onoff1 = ns.applications.OnOffHelper("ns3::UdpSocketFactory", ns.network.Address()) onoff1.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1.0]")) onoff1.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.0]")) for i in range(0, self.m_nSinks): # Ptr<Socket> sink = SetupPacketReceive (adhocInterfaces.GetAddress (i), adhocNodes.Get (i)); sink = self.SetupPacketReceive(adhocInterfaces.GetAddress(i), adhocNodes.Get(i)) remoteAddress = ns.network.AddressValue( ns.network.InetSocketAddress(adhocInterfaces.GetAddress(i), self.port)) onoff1.SetAttribute("Remote", remoteAddress) # Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> (); posURV = ns.core.ObjectFactory() posURV.SetTypeId("ns3::UniformRandomVariable") var = posURV.Create().GetObject( ns.core.UniformRandomVariable.GetTypeId()) temp = onoff1.Install( adhocNodes.Get(i + self.m_nSinks)) # type: ApplicationContainer temp.Start(ns.core.Seconds(var.GetValue(100.0, 101.0))) temp.Stop(ns.core.Seconds(self.m_total_time)) ss = self.m_nSinks nodes = str(ss) ss2 = self.m_node_speed sNodeSpeed = str(ss2) ss3 = self.m_node_pause sNodePause = str(ss3) ss4 = rate sRate = str(ss4) tr_name = tr_name + "_" + \ self.m_protocolName + "_" + \ nodes + "sinks_" + \ sNodeSpeed + "speed_" + \ sNodePause + "pause_" + \ sRate + "rate" self.m_CSVfileName = tr_name ascii = ns.network.AsciiTraceHelper() ns.mobility.MobilityHelper.EnableAsciiAll( ascii.CreateFileStream( os.path.join(__workdir__, "%s.mob" % tr_name))) flowmon_helper = ns.flow_monitor.FlowMonitorHelper() monitor = flowmon_helper.InstallAll() monitor = flowmon_helper.GetMonitor() monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) print("Run Simulation.") self.WriteHeaderCsv() self.CheckThroughput() ns.core.Simulator.Stop(ns.core.Seconds(self.m_total_time)) ns.core.Simulator.Run() monitor.CheckForLostPackets() classifier = flowmon_helper.GetClassifier() if self.m_debugger: for flow_id, flow_stats in monitor.GetFlowStats(): with open( os.path.join(__workdir__, (self.m_CSVfileName + ".txt")), 'a') as file: t = classifier.FindFlow(flow_id) proto = {6: 'TCP', 17: 'UDP'}[t.protocol] file.write("FlowID: %i (%s %s/%s --> %s/%i)\n" % \ (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort)) self.print_stats(file, flow_stats) file.close() monitor.SerializeToXmlFile( os.path.join(__workdir__, "%s.flowmon" % tr_name), True, True) delays = [] for flow_id, flow_stats in monitor.GetFlowStats(): tupl = classifier.FindFlow(flow_id) if tupl.protocol == 17 and tupl.sourcePort == 698: continue if flow_stats.rxPackets == 0: delays.append(0) else: delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets) plt.hist(delays, 20) plt.xlabel("Delay (s)") plt.ylabel("Number of Flows") plt.savefig(os.path.join(__workdir__, '%s.png' % tr_name), dpi=75) plt.show() ns.core.Simulator.Destroy()
def main(argv): cmd = ns.core.CommandLine() cmd.NumNodesSide = None cmd.AddValue( "NumNodesSide", "Grid side number of nodes (total number of nodes will be this number squared)" ) cmd.Results = None cmd.AddValue("Results", "Write XML results to file") cmd.Plot = None cmd.AddValue("Plot", "Plot the results using the matplotlib python module") cmd.Parse(argv) wifi = ns.wifi.WifiHelper.Default() wifiMac = ns.wifi.NqosWifiMacHelper.Default() 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.SetType("ns3::AdhocWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) internet = ns.internet.InternetStackHelper() list_routing = ns.internet.Ipv4ListRoutingHelper() olsr_routing = ns.olsr.OlsrHelper() static_routing = ns.internet.Ipv4StaticRoutingHelper() list_routing.Add(static_routing, 0) list_routing.Add(olsr_routing, 100) internet.SetRoutingHelper(list_routing) ipv4Addresses = ns.internet.Ipv4AddressHelper() ipv4Addresses.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0")) port = 9 onOffHelper = ns.applications.OnOffHelper( "ns3::UdpSocketFactory", ns.network.Address( ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"), port))) onOffHelper.SetAttribute( "DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps"))) onOffHelper.SetAttribute( "OnTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]")) onOffHelper.SetAttribute( "OffTime", ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]")) addresses = [] nodes = [] num_nodes_side = NUM_NODES_SIDE for xi in range(num_nodes_side): for yi in range(num_nodes_side): node = ns.network.Node() nodes.append(node) internet.Install(ns.network.NodeContainer(node)) mobility = ns.mobility.ConstantPositionMobilityModel() mobility.SetPosition( ns.core.Vector(xi * DISTANCE, yi * DISTANCE, 0)) node.AggregateObject(mobility) devices = wifi.Install(wifiPhy, wifiMac, node) ipv4_interfaces = ipv4Addresses.Assign(devices) addresses.append(ipv4_interfaces.GetAddress(0)) for e in range(500): for i, node in enumerate(nodes): destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)] onOffHelper.SetAttribute( "Remote", ns.network.AddressValue( ns.network.InetSocketAddress(destaddr, port))) app = onOffHelper.Install(ns.network.NodeContainer(node)) urv = ns.core.UniformRandomVariable() app.Start(ns.core.Seconds(urv.GetValue(20, 30))) flowmon_helper = ns.flow_monitor.FlowMonitorHelper() monitor = flowmon_helper.InstallAll() monitor = flowmon_helper.GetMonitor() monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) ns.core.Simulator.Stop(ns.core.Seconds(44.0)) ns.core.Simulator.Run() monitor.CheckForLostPackets() classifier = flowmon_helper.GetClassifier() monitor.SerializeToXmlFile("wififlow.xml", True, True) flow_stats_inputs = monitor.GetFlowStats() flow_array = [ ] # this is original array which store the original inputs to the model # this are the inputs to the model which will stored in flow_array flow_array.append(flow_stat_inputs.txBytes) flow_array.append(flow_stat_inputs.rxBytes) flow_array.append(flow_stat_inputs.txPackets) flow_array.append(flow_stat_inputs.rxPackets) flow_array.append(flow_stat_inputs.lostPackets) if st.rxPackets > 0: mean_delay = (flow_stat_inputs.delaySum.GetSeconds() / flow_stat_inputs.rxPackets) flow_array.append(mean_delay) mean_jitter = (flow_stat_inputs.jitterSum.GetSeconds() / (flow_stat_inputs.rxPackets - 1)) flow_array.append(mean_jitter) np.array( flow_array ) # then convert the flow array to numpy array reason to convert is numpy array will be a matrix and our model will only accept matrix inputs # data preprocessing part here we normalized the dataset into range between 1 and 0 and then convert to time sequence dataset since our model is recurrent network it only accept time sequence data df = DataFrame(data=d, index=index) min_max_scaler = preprocessing.MinMaxScaler() np_scaled = min_max_scaler.fit_transform(df) df_normalized = pd.DataFrame(np_scaled) X_train = sequence.pad_sequences(df_normalized, 10) actor = DQNAgent(X_train.shape[1], num_nodes_side) for t in range(500): action = actor.act(X_train) for i, node in enumerate(nodes): destaddr = addresses[action] onOffHelper.SetAttribute( "Remote", ns.network.AddressValue( ns.network.InetSocketAddress(destaddr, port))) app = onOffHelper.Install(ns.network.NodeContainer(node)) urv = ns.core.UniformRandomVariable() app.Start(ns.core.Seconds(urv.GetValue(20, 30))) flowmon_helper = ns.flow_monitor.FlowMonitorHelper() monitor = flowmon_helper.InstallAll() monitor = flowmon_helper.GetMonitor() monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) ns.core.Simulator.Stop(ns.core.Seconds(44.0)) ns.core.Simulator.Run() monitor.CheckForLostPackets() classifier = flowmon_helper.GetClassifier() monitor.SerializeToXmlFile("wififlow.xml", True, True) # similar process describe in ahead happens here inside the loop flow_stats_inputs_next = monitor.GetFlowStats() flow_array_next = [] flow_array_next.append(flow_stat_inputs_next.txBytes) flow_array_next.append(flow_stat_inputs_next.rxBytes) flow_array_next.append(flow_stat_inputs_next.txPackets) flow_array_next.append(flow_stat_inputs_next.rxPackets) flow_array_next.append(flow_stat_inputs_next.lostPackets) if st.rxPackets > 0: mean_delay = (flow_stat_inputs_next.delaySum.GetSeconds() / flow_stat_inputs.rxPackets) flow_array.append(mean_delay) mean_jitter = (flow_stat_inputs_next.jitterSum.GetSeconds() / (flow_stat_inputs.rxPackets - 1)) flow_array_next.append(mean_jitter) np.array(flow_array_next) df_next = DataFrame(data=d, index=index) min_max_scaler_next = preprocessing.MinMaxScaler() np_scaled_next = min_max_scaler_next.fit_transform(df_next) df_normalized_next = pd.DataFrame(np_scaled_next) X_next = sequence.pad_sequences(df_normalized_next, 10) # here we calculate the reward this has to be improve here i calculate the reward based only on loss packets which is not good way another few factors to be added it has to be discussed if (flow_stat_inputs_next.lostPackets > 10): reward = -10 else: reward = 20 actor.remember( X_train, action, X_next ) # finally saved the current step in model memory for experience replay module print("episode: {}/{}, score: {}".format(e, 500, t)) actor.replay( 32 ) # after 500 times of training then apply the experiece replay task to use what it learn so far import pylab delays = [] for flow_id, flow_stats in monitor.GetFlowStats(): tupl = classifier.FindFlow(flow_id) if tupl.protocol == 17 and tupl.sourcePort == 698: continue delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets) pylab.hist(delays, 20) pylab.xlabel("Delay (s)") pylab.ylabel("Number of Flows") pylab.show() return 0
def main(argv): cmd = ns.core.CommandLine() cmd.slot = 9 # slot time in microseconds cmd.sifs = 10 # SIFS duration in microseconds cmd.ackTimeout = 88 # ACK timeout duration in microseconds cmd.ctsTimeout = 88 # CTS timeout duration in microseconds cmd.rifs = 2 # RIFS duration in microseconds cmd.basicBlockAckTimeout = 286 # Basic Block ACK timeout duration in microseconds cmd.compressedBlockAckTimeout = 112 # Compressed Block ACK timeout duration in microseconds cmd.simulationTime = 10 # simulation time in seconds cmd.AddValue("slot", "Slot time in microseconds") cmd.AddValue("sifs", "SIFS duration in microseconds") cmd.AddValue("ackTimeout", "ACK timeout duration in microseconds") cmd.AddValue("ctsTimeout", "CTS timeout duration in microseconds") cmd.AddValue("rifs", "RIFS duration in microseconds") cmd.AddValue("basicBlockAckTimeoutTimeout", "Basic Block ACK timeout duration in microseconds") cmd.AddValue("compressedBlockAckTimeoutTimeout", "Compressed Block ACK timeout duration in microseconds") cmd.AddValue("simulationTime", "Simulation time in seconds") cmd.Parse(sys.argv) slot = int(cmd.slot) sifs = int(cmd.sifs) nMpdusackTimeout = int(cmd.ackTimeout) ctsTimeout = int(cmd.ctsTimeout) rifs = int(cmd.rifs) basicBlockAckTimeout = int(cmd.basicBlockAckTimeout) compressedBlockAckTimeout = int(cmd.compressedBlockAckTimeout) simulationTime = cmd.simulationTime #Since default reference loss is defined for 5 GHz, it needs to be changed when operating at 2.4 GHz ns.core.Config.SetDefault( "ns3::LogDistancePropagationLossModel::ReferenceLoss", ns.core.DoubleValue(40.046)) #Create nodes wifiStaNodes = ns.network.NodeContainer() wifiStaNodes.Create(1) wifiApNode = ns.network.NodeContainer() wifiApNode.Create(1) #Create wireless channel channel = ns.wifi.YansWifiChannelHelper.Default() phy = ns.wifi.YansWifiPhyHelper.Default() phy.SetChannel(channel.Create()) # wireless range limited to 5 meters! #Default IEEE 802.11n (2.4 GHz) wifi = ns.wifi.WifiHelper.Default() wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211n_2_4GHZ) wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns.core.StringValue("HtMcs7"), "ControlMode", ns.core.StringValue("HtMcs0")) mac = ns.wifi.HtWifiMacHelper.Default() #Install PHY and MAC ssid = ns.wifi.Ssid("ns3-wifi") mac.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) staDevices = ns.network.NetDeviceContainer() staDevices = wifi.Install(phy, mac, wifiStaNodes) mac.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid)) apDevice = ns.network.NetDeviceContainer() apDevice = wifi.Install(phy, mac, wifiApNode) #Once install is done, we overwrite the standard timing values ns.core.Config.Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/Slot", ns.core.TimeValue(ns.core.MicroSeconds(slot))) ns.core.Config.Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/Sifs", ns.core.TimeValue(ns.core.MicroSeconds(sifs))) ns.core.Config.Set( "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/AckTimeout", ns.core.TimeValue(ns.core.MicroSeconds(ackTimeout))) ns.core.Config.Set( "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/CtsTimeout", ns.core.TimeValue(ns.core.MicroSeconds(ctsTimeout))) ns.core.Config.Set("/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/Rifs", ns.core.TimeValue(ns.core.MicroSeconds(rifs))) ns.core.Config.Set( "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/BasicBlockAckTimeout", ns.core.TimeValue(ns.core.MicroSeconds(basicBlockAckTimeout))) ns.core.Config.Set( "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Mac/compressedBlockAckTimeout", ns.core.TimeValue(ns.core.MicroSeconds(compressedBlockAckTimeout))) #Mobility mobility = ns.mobility.MobilityHelper() positionAlloc = ns.mobility.ListPositionAllocator() positionAlloc.Add(ns.core.Vector3D(0.0, 0.0, 0.0)) positionAlloc.Add(ns.core.Vector3D(1.0, 0.0, 0.0)) mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(wifiApNode) mobility.Install(wifiStaNodes) #Internet stack stack = ns.internet.InternetStackHelper() stack.Install(wifiApNode) stack.Install(wifiStaNodes) address = ns.internet.Ipv4AddressHelper() address.SetBase(ns.network.Ipv4Address("192.168.1.0"), ns.network.Ipv4Mask("255.255.255.0")) staNodeInterface = ns.internet.Ipv4InterfaceContainer() staNodeInterface = address.Assign(staDevices) apNodeInterface = ns.internet.Ipv4InterfaceContainer() apNodeInterface = address.Assign(apDevice) #Setting applications port = 9 server = ns.applications.UdpServerHelper(port) serverApp = server.Install(wifiStaNode.Get(0)) serverApp.Start(ns.core.Seconds(0.0)) serverApp.Stop(ns.core.Seconds(simulationTime + 1)) client = ns.applications.UdpClientHelper(staNodeInterface.GetAddress(0), port) client.SetAttribute("MaxPackets", ns.core.UintegerValue(4294967295)) client.SetAttribute("Interval", ns.core.TimeValue(ns.core.Time("0.00001"))) #packets/s client.SetAttribute("PacketSize", ns.core.UintegerValue(1472)) #bytes clientApp = client.Install(wifiApNode.Get(0)) clientApp.Start(ns.core.Seconds(1.0)) clientApp.Stop(ns.core.Seconds(simulationTime + 1)) #Populate routing table #need to be done ############### ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables() #Set simulation time and launch simulation ns.core.Simulator.Stop(ns.core.Seconds(simulationTime + 1)) ns.core.Simulator.Run() totalPacketsThrough = serverApp.Get(0).GetReceived() throughput = totalPacketsThrough * 1472 * 8 / (simulationTime * 1000000.0 ) # Mbit/s print("Throughput:", throughput, "Mbit/s") ns.core.Simulator.Destroy() return 0