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