/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2009 IITP RAS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * This is an example script for AODV manet routing protocol. * * Authors: Pavel Boyko */ #include "ns3/aodv-module.h" #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/internet-module.h" #include "ns3/mobility-module.h" #include "ns3/point-to-point-module.h" #include "ns3/wifi-module.h" #include "ns3/v4ping-helper.h" #include "ns3/flow-monitor-helper.h" #include #include #include "ns3/on-off-helper.h" #include "ns3/packet-sink-helper.h" #include "ns3/mobility-model.h" #include "ns3/ipv4-flow-classifier.h" #include "ns3/netanim-module.h" #include "ns3/error-rate-model.h" #include "ns3/energy-module.h" #include "ns3/animation-interface.h" //#include "ns3/enum.h" using namespace ns3; //NS_LOG_COMPONENT_DEFINE ("RandomWalk2dMobilityModel"); /** * \brief Test script. * * This script creates 1-dimensional grid topology and then ping last node from the first one: * * [10.0.0.1] <-- step --> [10.0.0.2] <-- step --> [10.0.0.3] <-- step --> [10.0.04] * * ping 10.0.0.4 */ //trace the positions and velocities of node static uint32_t m_packetsTotal = 0; static uint32_t m_macTxDrop; static uint32_t m_macRxDrop; static uint32_t m_onoffTx = 0; static uint32_t m_packetsDrop; static uint32_t m_drop_noroute; static uint32_t m_drop_rerr; static uint32_t m_reason; static uint32_t m_packetsReceived = 0; static double m_speed = 0; class AodvExample { public: AodvExample (); /// Configure script parameters, \return true on successful configuration bool Configure (int argc, char **argv); /// Run simulation void Run (); /// Report results void Velocity (); void Throughput(); void ReportMonitor(); private: ///\name parameters //\{ /// Number of nodes uint32_t size; /// Distance between nodes, meters double xMax; double yMax; /// Simulation time, seconds double totalTime; /// Write per-device PCAP traces if true bool pcap; /// Print routes if true bool printRoutes; // Velocity of nodes double velocity; //\} /// Node speed int nodeSpeed;//in m/s /// Node pause int nodePause; //in s /// Seed number & run number int seed; int run_no; /// Packet Size uint16_t packetSize; /// enable reports bool enableReports; /// enable traffic bool enableTraffic; ///configure no. of sinks int nSinks; /// start and stop simulation double startTime, stopOffset; ///DropTail max size uint32_t dropTail; ///\name network //\{ NodeContainer nodes; NetDeviceContainer devices; Ipv4InterfaceContainer interfaces; EnergySourceContainer sources; //\} private: void CreateNodes (); void CreateDevices (); void InstallEnergyModel (); void InstallInternetStack (); void InstallRandomApplications (); void PacketReceived(Ptr p, const Address &add); void MacTxDrop(Ptr p); void MacRxDrop(Ptr p); void OnOffSent(Ptr p); void PacketDrop(const ns3::Ipv4Header &, ns3::Ptr, ns3::Ipv4L3Protocol::DropReason, ns3::Ptr, uint32_t); void CourseChange(Ptr mobility); void RemainingEnergy (double oldValue, double remainingEnergy); }; int main (int argc, char **argv) { AodvExample test; if (!test.Configure (argc, argv)) NS_FATAL_ERROR ("Configuration failed. Aborted."); test.Run (); // test.Report (std::cout); return 0; } //----------------------------------------------------------------------------- AodvExample::AodvExample () : size (100), xMax (1200), yMax (900), totalTime (180), pcap (true), printRoutes (true), velocity (10), nodePause (0), //in s seed (10), run_no(1), packetSize(512), enableReports (true), enableTraffic (true), nSinks (50), startTime (60.0), stopOffset (10.0), dropTail (100) { } bool AodvExample::Configure (int argc, char **argv) { // Enable AODV logs by default. Comment this if too noisy // LogComponentEnable("AodvRoutingProtocol", LOG_LEVEL_ALL); CommandLine cmd; // std::string animFile; cmd.AddValue ("pcap", "Write PCAP traces.", pcap); cmd.AddValue ("printRoutes", "Print routing table dumps.", printRoutes); cmd.AddValue ("size", "Number of nodes.", size); cmd.AddValue ("time", "Simulation time, s.", totalTime); cmd.AddValue ("xmax", "X max distance, m", xMax); cmd.AddValue ("ymax", "Y max distance, m", yMax); cmd.AddValue ("velocity", "Velocity, m/s", velocity); cmd.AddValue ("pause", "Pause time (s)", nodePause); cmd.AddValue ("seed", "Seed Number", seed); cmd.AddValue ("run", "Run Number", run_no); cmd.AddValue ("pcap", "Pcap files export", pcap); cmd.AddValue ("report", "Enable report", enableReports); cmd.AddValue ("traffic", "Enable traffic", enableTraffic); cmd.AddValue ("sink", "No. of sinks", nSinks); cmd.AddValue ("queuesize", "Queue size", dropTail); cmd.Parse (argc, argv); SeedManager::SetSeed (seed); SeedManager::SetRun(run_no); // Config::SetDefault ("ns3::DropTailQueue::Mode", StringValue("QUEUE_MODE_PACKETS")); // Config::SetDefault ("ns3::DropTailQueue::MaxPackets", UintegerValue (dropTail)); // Config::SetDefault ("ns3::RedQueue::Mode", StringValue("QUEUE_MODE_PACKETS")); // Config::SetDefault ("ns3::RedQueue::QueueLimit", UintegerValue (dropTail)); return true; } void AodvExample::Run () { CreateNodes (); CreateDevices (); InstallInternetStack (); //InstallEnergyModel (); if (enableTraffic) { InstallRandomApplications (); } std::cout << "Starting simulation for " << totalTime << " s ...\n"; Simulator::Stop (Seconds (totalTime)); //trace mobility of nodes std::ostringstream ossSpeed; ossSpeed << "/NodeList/" << nodes.Get(size - 1)->GetId() << "/$ns3::MobilityModel/CourseChange"; std::ostringstream ossReceived; ossReceived << "/NodeList/*/ApplicationList/0/$ns3::PacketSink/Rx"; std::ostringstream ossDrop; ossDrop << "/NodeList/*/$ns3::Ipv4L3Protocol/Drop"; std::ostringstream ossTx; ossTx << "/NodeList/*/ApplicationList/0/$ns3::OnOffApplication/Tx"; Config::ConnectWithoutContext (ossSpeed.str(), MakeCallback(&AodvExample::CourseChange,this)); Config::ConnectWithoutContext (ossReceived.str(), MakeCallback (&AodvExample::PacketReceived,this)); Config::ConnectWithoutContext (ossDrop.str(), MakeCallback (&AodvExample::PacketDrop,this)); Config::ConnectWithoutContext (ossTx.str(), MakeCallback (&AodvExample::OnOffSent,this)); //report throughput if (enableReports) { Throughput(); } //Run simulation Simulator::Run (); ReportMonitor(); // Finish simulation. Simulator::Destroy (); } void AodvExample::CourseChange (Ptr mobility) { Vector vel = mobility->GetVelocity(); double x = vel.x; double y = vel.y; double z = vel.z; m_speed = sqrt((x*x) + (y*y) + (z*z)); } void AodvExample::Velocity () { std::cout << "Velocity: " << m_speed << std::endl; Simulator::Schedule(Seconds(5), &AodvExample::Velocity, this); } void AodvExample::Throughput () // in Kbps calculated every 10s { double kbps = 0; uint16_t packetSize = 512; m_packetsReceived = m_packetsTotal - m_packetsReceived; double transmisionTime = Simulator::Now ().GetSeconds()-startTime; if (transmisionTime > 0) { kbps = ((m_packetsReceived * packetSize * 8.0) / 1000)/10/nSinks; m_packetsReceived = m_packetsTotal; } Time time = Simulator::Now (); std::cout << "Second, " << time.GetSeconds() << ", Send, " << m_onoffTx << ", Received, " << m_packetsReceived << ", No route, " << m_drop_noroute << ", Route error, " << m_drop_rerr << ", Perdas, " << m_packetsDrop << ", Throughput, " << kbps << ",Kbps" << std::endl; Simulator::Schedule (Seconds (10), &AodvExample::Throughput,this); } void AodvExample::MacTxDrop (Ptr p) { // m_macRxTrace (packet); m_macTxDrop++; } void AodvExample::MacRxDrop (Ptr p) { // m_macRxTrace (packet); m_macRxDrop++; } void AodvExample::OnOffSent (Ptr p) { // m_macRxTrace (packet); m_onoffTx++; } void AodvExample::PacketReceived (Ptr p, const Address &add) { // m_macRxTrace (packet); m_packetsTotal++; } void AodvExample::PacketDrop(const ns3::Ipv4Header & h, Ptr p, ns3::Ipv4L3Protocol::DropReason reason, ns3::Ptr ip, uint32_t n) { m_reason = reason; m_packetsDrop++; //std::cout << m_reason << " -- \n"; if (m_reason == 5) { m_drop_rerr++; } if (m_reason == 2) { m_drop_noroute++; } } void AodvExample::RemainingEnergy (double oldValue, double remainingEnergy) { NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "s Current remaining energy = " << remainingEnergy << "J"); } void AodvExample::CreateNodes () { std::cout << "Creating " << (unsigned)size << " nodes the area of " << xMax << "x" << yMax << " m2.\n"; nodes.Create (size); // Name nodes for (uint32_t i = 0; i < size; ++i) { std::ostringstream os; os << "node-" << i; Names::Add (os.str (), nodes.Get (i)); } // Assign mobility model MobilityHelper mobility; /// Random Waypoint Mobility Model ObjectFactory pos; pos.SetTypeId ("ns3::RandomRectanglePositionAllocator"); std::ostringstream xpos, ypos; xpos << "ns3::UniformRandomVariable[Min=0.0|Max=" << xMax << "]"; ypos << "ns3::UniformRandomVariable[Min=0.0|Max=" << yMax << "]"; pos.Set ("X", StringValue (xpos.str())); pos.Set ("Y", StringValue (ypos.str())); Ptr taPositionAlloc = pos.Create() ->GetObject (); std::ostringstream randomSpeed, randomPause; randomSpeed << "ns3::UniformRandomVariable[Min=" << 0.1 << "|Max=" << velocity << "]"; //<--avoid velocity of 0 m/s randomPause << "ns3::UniformRandomVariable[Min=0.0|Max=" << nodePause << "]"; mobility.SetMobilityModel ("ns3::RandomWaypointMobilityModel", "Speed", StringValue(randomSpeed.str()), "Pause", StringValue(randomPause.str()), "PositionAllocator", PointerValue (taPositionAlloc)); mobility.SetPositionAllocator(taPositionAlloc); mobility.Install (nodes); } void AodvExample::CreateDevices () //Wifi devices configuration { NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default (); wifiMac.SetType ("ns3::AdhocWifiMac"); Config::SetDefault("ns3::WifiMacQueue::MaxDelay",TimeValue(Seconds(0.1))); YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default (); YansWifiChannelHelper wifiChannel;// = YansWifiChannelHelper::Default (); wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel"); //Set propagation speed = 3e+8 m/s /* wifiChannel.AddPropagationLoss ("ns3::LogDistancePropagationLossModel", "Exponent",DoubleValue(2.0), "ReferenceDistance",DoubleValue (1.0), "ReferenceLoss",DoubleValue (1)); */ wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel"); /* wifiChannel.AddPropagationLoss ("ns3::TwoRayGroundPropagationLossModel", "HeightAboveZ",DoubleValue(1.5), "SystemLoss", DoubleValue(1), "Lambda",DoubleValue(0.125)); //<-- lambda = c (m/s) /f (Hz)*/ wifiPhy.SetChannel (wifiChannel.Create ()); wifiPhy.Set("EnergyDetectionThreshold",DoubleValue(-74.0)); wifiPhy.Set("TxPowerStart",DoubleValue(13.0)); wifiPhy.Set("TxPowerEnd",DoubleValue(13.0)); wifiPhy.Set("TxPowerLevels", UintegerValue(1)); wifiPhy.Set("TxGain", DoubleValue(1)); wifiPhy.Set("RxGain", DoubleValue(1)); wifiPhy.Set ("CcaMode1Threshold", DoubleValue(-82.0)); wifiPhy.Set("RxNoiseFigure",DoubleValue(5)); wifiPhy.Set("ChannelNumber", UintegerValue(6)); WifiHelper wifi;/* = WifiHelper::Default ();*/ wifi.SetStandard(WIFI_PHY_STANDARD_80211b); wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode", StringValue ("DsssRate11Mbps"), "ControlMode", StringValue ("DsssRate11Mbps"), "RtsCtsThreshold",UintegerValue(0), "FragmentationThreshold", UintegerValue (2200)); //"NonUnicastMode",StringValue ("DsssRate1Mbps")); devices = wifi.Install (wifiPhy, wifiMac, nodes); if (pcap) { wifiPhy.EnablePcapAll (std::string ("aodv_random")); } } void AodvExample::InstallInternetStack () { AodvHelper aodv; InternetStackHelper stack; stack.SetRoutingHelper (aodv); stack.Install (nodes); Ipv4AddressHelper address; address.SetBase ("10.0.0.0", "255.0.0.0"); interfaces = address.Assign (devices); if (printRoutes) { Ptr routingStream = Create ("aodv.routes", std::ios::out); aodv.PrintRoutingTableAllAt (Seconds (totalTime-60), routingStream); } } void AodvExample::InstallEnergyModel () { BasicEnergySourceHelper basicSourceHelper; basicSourceHelper.Set ("BasicEnergySourceInitialEnergyJ", DoubleValue (600)); EnergySourceContainer sources = basicSourceHelper.Install (nodes); /* device energy model */ WifiRadioEnergyModelHelper radioEnergyHelper; // configure radio energy model radioEnergyHelper.Set ("TxCurrentA", DoubleValue (0.285)); // 285mA radioEnergyHelper.Set ("RxCurrentA", DoubleValue (0.185)); // 185mA radioEnergyHelper.Set ("IdleCurrentA", DoubleValue (0.001)); //1mA // install device model DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install (devices, sources); } void AodvExample::InstallRandomApplications () { // Configure app port & bit rate uint16_t port = 9; // uint64_t bps = 11534336; //Start app std::cout << "Clients are connecting to Servers " << "\n"; OnOffHelper onoff ("ns3::UdpSocketFactory",Address ()); onoff.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=0.00037]")); onoff.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0.99963]")); onoff.SetAttribute("PacketSize", UintegerValue(500)); PacketSinkHelper sink("ns3::UdpSocketFactory",Address(InetSocketAddress(ns3::Ipv4Address::GetAny(),port))); double dev1 = 0.0; for (int i = 0; i <= nSinks - 1; i++) { AddressValue remoteAddress (InetSocketAddress (interfaces.GetAddress (i), port)); onoff.SetAttribute ("Remote", remoteAddress); onoff.SetAttribute("DataRate", StringValue ("11Mbps")); ApplicationContainer sinkApp = sink.Install(nodes.Get(i)); sinkApp.Start(Seconds(startTime)); sinkApp.Stop(Seconds(totalTime)); std::cout << "Instalando o Par " << i << "("<< startTime << "x" << totalTime << ")--" << i+nSinks << "("<< startTime + dev1 << "x" < var = CreateObject (); dev1 = var->GetInteger(0,stopOffset-1); ///<--stopOffset allows to stop CBR before stop simulation ApplicationContainer app = onoff.Install (nodes.Get (i + nSinks)); app.Start (Seconds (startTime + dev1)); app.Stop (Seconds (totalTime-stopOffset+dev1)); //bps = bps + 5; } } void AodvExample::ReportMonitor() { FlowMonitorHelper flowmon; Ptr monitor = flowmon.InstallAll (); //std::cout << "teste monitor"; monitor->CheckForLostPackets (); Ptr classifier = DynamicCast (flowmon.GetClassifier ()); FlowMonitor::FlowStatsContainer stats = monitor->GetFlowStats (); for (std::map::const_iterator i = stats.begin (); i != stats.end (); ++i) { std::cout << i->second.txPackets << ";" << i->second.rxPackets << ";"; std::cout << i->second.txBytes << ";" << i->second.rxBytes << ";"; std::cout << "xxxxx\n"; } //monitor->SerializeToXmlFile("aodv.flowmon", true, true); }