A Discrete-Event Network Simulator
API
energy-model-example.cc
Go to the documentation of this file.
1 /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2010 Network Security Lab, University of Washington, Seattle.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation;
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * Author: Sidharth Nabar <snabar@uw.edu>, He Wu <mdzz@u.washington.edu>
19  */
20 
21 #include <iostream>
22 #include <fstream>
23 #include <vector>
24 #include <string>
25 #include "ns3/core-module.h"
26 #include "ns3/network-module.h"
27 #include "ns3/mobility-module.h"
28 #include "ns3/config-store-module.h"
29 #include "ns3/energy-module.h"
30 #include "ns3/internet-module.h"
31 #include "ns3/yans-wifi-helper.h"
32 #include "ns3/wifi-radio-energy-model-helper.h"
33 
34 using namespace ns3;
35 
36 NS_LOG_COMPONENT_DEFINE ("EnergyExample");
37 
38 static inline std::string
40 {
42 
43  std::ostringstream oss;
44  oss << "--\nReceived one packet! Socket: " << iaddr.GetIpv4 ()
45  << " port: " << iaddr.GetPort ()
46  << " at time = " << Simulator::Now ().GetSeconds ()
47  << "\n--";
48 
49  return oss.str ();
50 }
51 
57 void
59 {
60  Ptr<Packet> packet;
61  Address from;
62  while ((packet = socket->RecvFrom (from)))
63  {
64  if (packet->GetSize () > 0)
65  {
67  }
68  }
69 }
70 
80 static void
82  uint32_t pktCount, Time pktInterval)
83 {
84  if (pktCount > 0)
85  {
86  socket->Send (Create<Packet> (pktSize));
87  Simulator::Schedule (pktInterval, &GenerateTraffic, socket, pktSize, n,
88  pktCount - 1, pktInterval);
89  }
90  else
91  {
92  socket->Close ();
93  }
94 }
95 
97 void
98 RemainingEnergy (double oldValue, double remainingEnergy)
99 {
100  NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
101  << "s Current remaining energy = " << remainingEnergy << "J");
102 }
103 
105 void
106 TotalEnergy (double oldValue, double totalEnergy)
107 {
108  NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
109  << "s Total energy consumed by radio = " << totalEnergy << "J");
110 }
111 
112 int
113 main (int argc, char *argv[])
114 {
115  /*
116  LogComponentEnable ("EnergySource", LOG_LEVEL_DEBUG);
117  LogComponentEnable ("BasicEnergySource", LOG_LEVEL_DEBUG);
118  LogComponentEnable ("DeviceEnergyModel", LOG_LEVEL_DEBUG);
119  LogComponentEnable ("WifiRadioEnergyModel", LOG_LEVEL_DEBUG);
120  */
121 
123 
124  std::string phyMode ("DsssRate1Mbps");
125  double Prss = -80; // dBm
126  uint32_t PpacketSize = 200; // bytes
127  bool verbose = false;
128 
129  // simulation parameters
130  uint32_t numPackets = 10000; // number of packets to send
131  double interval = 1; // seconds
132  double startTime = 0.0; // seconds
133  double distanceToRx = 100.0; // meters
134 
135  CommandLine cmd (__FILE__);
136  cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
137  cmd.AddValue ("Prss", "Intended primary RSS (dBm)", Prss);
138  cmd.AddValue ("PpacketSize", "size of application packet sent", PpacketSize);
139  cmd.AddValue ("numPackets", "Total number of packets to send", numPackets);
140  cmd.AddValue ("startTime", "Simulation start time", startTime);
141  cmd.AddValue ("distanceToRx", "X-Axis distance between nodes", distanceToRx);
142  cmd.AddValue ("verbose", "Turn on all device log components", verbose);
143  cmd.Parse (argc, argv);
144 
145  // Convert to time object
146  Time interPacketInterval = Seconds (interval);
147 
148  // disable fragmentation for frames below 2200 bytes
149  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold",
150  StringValue ("2200"));
151  // turn off RTS/CTS for frames below 2200 bytes
152  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold",
153  StringValue ("2200"));
154  // Fix non-unicast data rate to be the same as that of unicast
155  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",
156  StringValue (phyMode));
157 
158  NodeContainer c;
159  c.Create (2); // create 2 nodes
160  NodeContainer networkNodes;
161  networkNodes.Add (c.Get (0));
162  networkNodes.Add (c.Get (1));
163 
164  // The below set of helpers will help us to put together the wifi NICs we want
166  if (verbose)
167  {
168  wifi.EnableLogComponents ();
169  }
170  wifi.SetStandard (WIFI_STANDARD_80211b);
171 
173  /***************************************************************************/
174  YansWifiPhyHelper wifiPhy;
175 
177  YansWifiChannelHelper wifiChannel;
178  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
179  wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
180 
181  // create wifi channel
182  Ptr<YansWifiChannel> wifiChannelPtr = wifiChannel.Create ();
183  wifiPhy.SetChannel (wifiChannelPtr);
184 
186  // Add a MAC and disable rate control
187  WifiMacHelper wifiMac;
188  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode",
189  StringValue (phyMode), "ControlMode",
190  StringValue (phyMode));
191  // Set it to ad-hoc mode
192  wifiMac.SetType ("ns3::AdhocWifiMac");
193 
195  NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, networkNodes);
196 
199  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
200  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
201  positionAlloc->Add (Vector (2 * distanceToRx, 0.0, 0.0));
202  mobility.SetPositionAllocator (positionAlloc);
203  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
204  mobility.Install (c);
205 
207  /***************************************************************************/
208  /* energy source */
209  BasicEnergySourceHelper basicSourceHelper;
210  // configure energy source
211  basicSourceHelper.Set ("BasicEnergySourceInitialEnergyJ", DoubleValue (0.1));
212  // install source
213  EnergySourceContainer sources = basicSourceHelper.Install (c);
214  /* device energy model */
215  WifiRadioEnergyModelHelper radioEnergyHelper;
216  // configure radio energy model
217  radioEnergyHelper.Set ("TxCurrentA", DoubleValue (0.0174));
218  // install device model
219  DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install (devices, sources);
220  /***************************************************************************/
221 
223  InternetStackHelper internet;
224  internet.Install (networkNodes);
225 
226  Ipv4AddressHelper ipv4;
227  NS_LOG_INFO ("Assign IP Addresses.");
228  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
230 
231  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
232  Ptr<Socket> recvSink = Socket::CreateSocket (networkNodes.Get (1), tid); // node 1, receiver
234  recvSink->Bind (local);
236 
237  Ptr<Socket> source = Socket::CreateSocket (networkNodes.Get (0), tid); // node 0, sender
239  source->SetAllowBroadcast (true);
240  source->Connect (remote);
241 
243  /***************************************************************************/
244  // all sources are connected to node 1
245  // energy source
246  Ptr<BasicEnergySource> basicSourcePtr = DynamicCast<BasicEnergySource> (sources.Get (1));
247  basicSourcePtr->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback (&RemainingEnergy));
248  // device energy model
249  Ptr<DeviceEnergyModel> basicRadioModelPtr =
250  basicSourcePtr->FindDeviceEnergyModels ("ns3::WifiRadioEnergyModel").Get (0);
251  NS_ASSERT (basicRadioModelPtr != NULL);
252  basicRadioModelPtr->TraceConnectWithoutContext ("TotalEnergyConsumption", MakeCallback (&TotalEnergy));
253  /***************************************************************************/
254 
255 
257  // start traffic
258  Simulator::Schedule (Seconds (startTime), &GenerateTraffic, source, PpacketSize,
259  networkNodes.Get (0), numPackets, interPacketInterval);
260 
261  Simulator::Stop (Seconds (10.0));
262  Simulator::Run ();
263 
264  for (DeviceEnergyModelContainer::Iterator iter = deviceModels.Begin (); iter != deviceModels.End (); iter ++)
265  {
266  double energyConsumed = (*iter)->GetTotalEnergyConsumption ();
267  NS_LOG_UNCOND ("End of simulation (" << Simulator::Now ().GetSeconds ()
268  << "s) Total energy consumed by radio = " << energyConsumed << "J");
269  NS_ASSERT (energyConsumed <= 0.1);
270  }
271 
273 
274  return 0;
275 }
ns3::DeviceEnergyModelContainer::End
Iterator End(void) const
Get an iterator which refers to the last DeviceEnergyModel pointer in the container.
Definition: device-energy-model-container.cc:67
ns3::NetDeviceContainer
holds a vector of ns3::NetDevice pointers
Definition: net-device-container.h:42
ns3::TypeId
a unique identifier for an interface.
Definition: type-id.h:59
ns3::DeviceEnergyModelHelper::Install
DeviceEnergyModelContainer Install(Ptr< NetDevice > device, Ptr< EnergySource > source) const
Definition: energy-model-helper.cc:91
NS_LOG_COMPONENT_DEFINE
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:205
ns3::InetSocketAddress
an Inet address class
Definition: inet-socket-address.h:41
ns3::YansWifiPhyHelper
Make it easy to create and manage PHY objects for the YANS model.
Definition: yans-wifi-helper.h:161
ns3::CommandLine
Parse command-line arguments.
Definition: command-line.h:228
ns3::Socket::SetAllowBroadcast
virtual bool SetAllowBroadcast(bool allowBroadcast)=0
Configure whether broadcast datagram transmissions are allowed.
ns3::ListPositionAllocator::Add
void Add(Vector v)
Add a position to the list of positions.
Definition: position-allocator.cc:70
NS_ASSERT
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Definition: assert.h:67
ns3::YansWifiChannelHelper::SetPropagationDelay
void SetPropagationDelay(std::string name, std::string n0="", const AttributeValue &v0=EmptyAttributeValue(), std::string n1="", const AttributeValue &v1=EmptyAttributeValue(), std::string n2="", const AttributeValue &v2=EmptyAttributeValue(), std::string n3="", const AttributeValue &v3=EmptyAttributeValue(), std::string n4="", const AttributeValue &v4=EmptyAttributeValue(), std::string n5="", const AttributeValue &v5=EmptyAttributeValue(), std::string n6="", const AttributeValue &v6=EmptyAttributeValue(), std::string n7="", const AttributeValue &v7=EmptyAttributeValue())
Definition: yans-wifi-helper.cc:74
ns3::DeviceEnergyModelContainer::Get
Ptr< DeviceEnergyModel > Get(uint32_t i) const
Get the i-th Ptr<DeviceEnergyModel> stored in this container.
Definition: device-energy-model-container.cc:81
ns3::LOG_LEVEL_INFO
@ LOG_LEVEL_INFO
LOG_INFO and above.
Definition: log.h:107
ns3::Socket::Bind
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
ns3::Packet::GetSize
uint32_t GetSize(void) const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
Definition: packet.h:852
ns3::InetSocketAddress::GetPort
uint16_t GetPort(void) const
Definition: inet-socket-address.cc:65
ns3::Simulator::Now
static Time Now(void)
Return the current simulation virtual time.
Definition: simulator.cc:195
GenerateTraffic
static void GenerateTraffic(Ptr< Socket > socket, uint32_t pktSize, Ptr< Node > n, uint32_t pktCount, Time pktInterval)
Definition: energy-model-example.cc:81
ns3
Every class exported by the ns3 library is enclosed in the ns3 namespace.
ns3::Ipv4Address::GetBroadcast
static Ipv4Address GetBroadcast(void)
Definition: ipv4-address.cc:402
ns3::DeviceEnergyModelContainer::Begin
Iterator Begin(void) const
Get an iterator which refers to the first DeviceEnergyModel pointer in the container.
Definition: device-energy-model-container.cc:60
ns3::WifiHelper
helps to create WifiNetDevice objects
Definition: wifi-helper.h:327
ns3::Ipv4AddressHelper
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
Definition: ipv4-address-helper.h:48
ns3::LOG_PREFIX_NODE
@ LOG_PREFIX_NODE
Prefix all trace prints with simulation node.
Definition: log.h:120
ReceivePacket
void ReceivePacket(Ptr< Socket > socket)
Definition: energy-model-example.cc:58
ns3::LogComponentEnable
void LogComponentEnable(char const *name, enum LogLevel level)
Enable the logging output associated with that log component.
Definition: log.cc:361
ns3::YansWifiChannelHelper::AddPropagationLoss
void AddPropagationLoss(std::string name, std::string n0="", const AttributeValue &v0=EmptyAttributeValue(), std::string n1="", const AttributeValue &v1=EmptyAttributeValue(), std::string n2="", const AttributeValue &v2=EmptyAttributeValue(), std::string n3="", const AttributeValue &v3=EmptyAttributeValue(), std::string n4="", const AttributeValue &v4=EmptyAttributeValue(), std::string n5="", const AttributeValue &v5=EmptyAttributeValue(), std::string n6="", const AttributeValue &v6=EmptyAttributeValue(), std::string n7="", const AttributeValue &v7=EmptyAttributeValue())
Definition: yans-wifi-helper.cc:50
ns3::Simulator::Schedule
static EventId Schedule(Time const &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition: simulator.h:557
ns3::YansWifiPhyHelper::SetChannel
void SetChannel(Ptr< YansWifiChannel > channel)
Definition: yans-wifi-helper.cc:134
first.devices
devices
Definition: first.py:39
ns3::InetSocketAddress::ConvertFrom
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
Definition: inet-socket-address.cc:126
ns3::DoubleValue
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition: double.h:41
ns3::NodeContainer::Create
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
Definition: node-container.cc:98
TotalEnergy
void TotalEnergy(double oldValue, double totalEnergy)
Trace function for total energy consumption at node.
Definition: energy-model-example.cc:106
ns3::BasicEnergySourceHelper::Set
void Set(std::string name, const AttributeValue &v)
Definition: basic-energy-source-helper.cc:36
startTime
double startTime
Definition: tcp-nsc-comparison.cc:45
ns3::NodeContainer::Add
void Add(NodeContainer other)
Append the contents of another NodeContainer to the end of this container.
Definition: node-container.cc:114
ns3::EnergySourceContainer
Holds a vector of ns3::EnergySource pointers.
Definition: energy-source-container.h:45
ns3::Ipv4AddressHelper::SetBase
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
Definition: ipv4-address-helper.cc:64
ns3::EnergySourceHelper::Install
EnergySourceContainer Install(Ptr< Node > node) const
Definition: energy-model-helper.cc:35
third.wifi
wifi
Definition: third.py:96
ns3::Ptr< Socket >
ns3::EnergySourceContainer::Get
Ptr< EnergySource > Get(uint32_t i) const
Get the i-th Ptr<EnergySource> stored in this container.
Definition: energy-source-container.cc:88
ns3::Socket::Send
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
ns3::Socket::SetRecvCallback
void SetRecvCallback(Callback< void, Ptr< Socket > > receivedData)
Notify application when new data is available to be read.
Definition: socket.cc:128
ns3::YansWifiChannelHelper::Create
Ptr< YansWifiChannel > Create(void) const
Definition: yans-wifi-helper.cc:98
ns3::Simulator::Stop
static void Stop(void)
Tell the Simulator the calling event should be the last one executed.
Definition: simulator.cc:180
ns3::Address
a polymophic address class
Definition: address.h:91
ns3::BasicEnergySourceHelper
Creates a BasicEnergySource object.
Definition: basic-energy-source-helper.h:35
ns3::InternetStackHelper::Install
void Install(std::string nodeName) const
Aggregate implementations of the ns3::Ipv4, ns3::Ipv6, ns3::Udp, and ns3::Tcp classes onto the provid...
Definition: internet-stack-helper.cc:366
NS_LOG_INFO
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:281
ns3::Socket::RecvFrom
virtual Ptr< Packet > RecvFrom(uint32_t maxSize, uint32_t flags, Address &fromAddress)=0
Read a single packet from the socket and retrieve the sender address.
ns3::InetSocketAddress::GetIpv4
Ipv4Address GetIpv4(void) const
Definition: inet-socket-address.cc:71
ns3::WifiRadioEnergyModelHelper
Assign WifiRadioEnergyModel to wifi devices.
Definition: wifi-radio-energy-model-helper.h:37
ns3::DeviceEnergyModelContainer::Iterator
std::vector< Ptr< DeviceEnergyModel > >::const_iterator Iterator
Definition: device-energy-model-container.h:46
ns3::Ipv4InterfaceContainer
holds a vector of std::pair of Ptr<Ipv4> and interface index.
Definition: ipv4-interface-container.h:55
ns3::WIFI_STANDARD_80211b
@ WIFI_STANDARD_80211b
Definition: wifi-standards.h:128
ns3::NodeContainer::Get
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
Definition: node-container.cc:93
verbose
bool verbose
Definition: openflow-switch.cc:50
ns3::Time
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:104
ns3::Socket::Close
virtual int Close(void)=0
Close a socket.
second.cmd
cmd
Definition: second.py:35
ns3::DeviceEnergyModelContainer
Holds a vector of ns3::DeviceEnergyModel pointers.
Definition: device-energy-model-container.h:44
NS_LOG_UNCOND
#define NS_LOG_UNCOND(msg)
Output the requested message unconditionally.
Definition: log-macros-enabled.h:269
PrintReceivedPacket
static std::string PrintReceivedPacket(Address &from)
Definition: energy-model-example.cc:39
ns3::MakeCallback
Callback< R, Ts... > MakeCallback(R(T::*memPtr)(Ts...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Definition: callback.h:1642
ns3::Simulator::Run
static void Run(void)
Run the simulation.
Definition: simulator.cc:172
ns3::StringValue
Hold variables of type string.
Definition: string.h:41
ns3::LOG_PREFIX_TIME
@ LOG_PREFIX_TIME
Prefix all trace prints with simulation time.
Definition: log.h:119
ns3::Ipv4Address::GetAny
static Ipv4Address GetAny(void)
Definition: ipv4-address.cc:395
ns3::Socket::Connect
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
ns3::Seconds
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1289
ns3::Ipv4AddressHelper::Assign
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
Definition: ipv4-address-helper.cc:135
ns3::Simulator::Destroy
static void Destroy(void)
Execute the events scheduled with ScheduleDestroy().
Definition: simulator.cc:136
ns3::LogLevel
LogLevel
Logging severity classes and levels.
Definition: log.h:94
pktSize
uint32_t pktSize
packet size used for the simulation (in bytes)
Definition: wifi-bianchi.cc:86
ns3::NodeContainer
keep track of a set of node pointers.
Definition: node-container.h:39
ns3::WifiMacHelper::SetType
void SetType(std::string type, Args &&... args)
Definition: wifi-mac-helper.h:130
ns3::Socket::CreateSocket
static Ptr< Socket > CreateSocket(Ptr< Node > node, TypeId tid)
This method wraps the creation of sockets that is performed on a given node by a SocketFactory specif...
Definition: socket.cc:71
ns3::YansWifiChannelHelper
manage and create wifi channel objects for the YANS model.
Definition: yans-wifi-helper.h:37
ns3::WifiMacHelper
create MAC layers for a ns3::WifiNetDevice.
Definition: wifi-mac-helper.h:48
ns3::Config::SetDefault
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:849
ns3::ObjectBase::TraceConnectWithoutContext
bool TraceConnectWithoutContext(std::string name, const CallbackBase &cb)
Connect a TraceSource to a Callback without a context.
Definition: object-base.cc:293
RemainingEnergy
void RemainingEnergy(double oldValue, double remainingEnergy)
Trace function for remaining energy at node.
Definition: energy-model-example.cc:98
ns3::EnergySource::FindDeviceEnergyModels
DeviceEnergyModelContainer FindDeviceEnergyModels(TypeId tid)
Definition: energy-source.cc:78
ns3::InternetStackHelper
aggregate IP/TCP/UDP functionality to existing Nodes.
Definition: internet-stack-helper.h:88
ns3::TypeId::LookupByName
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition: type-id.cc:830
ns3::MobilityHelper
Helper class used to assign positions and mobility models to nodes.
Definition: mobility-helper.h:43
ns3::Time::GetSeconds
double GetSeconds(void) const
Get an approximation of the time stored in this instance in the indicated unit.
Definition: nstime.h:380
sample-rng-plot.n
n
Definition: sample-rng-plot.py:37
third.mobility
mobility
Definition: third.py:108
ns3::WifiRadioEnergyModelHelper::Set
void Set(std::string name, const AttributeValue &v) override
Definition: wifi-radio-energy-model-helper.cc:40