A Discrete-Event Network Simulator
API
energy-model-with-harvesting-example.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2014 Wireless Communications and Networking Group (WCNG),
3  * University of Rochester, Rochester, NY, USA.
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: Cristiano Tapparello <cristiano.tapparello@rochester.edu>
19  */
20 
49 #include "ns3/core-module.h"
50 #include "ns3/energy-module.h"
51 #include "ns3/internet-module.h"
52 #include "ns3/mobility-module.h"
53 #include "ns3/network-module.h"
54 #include "ns3/wifi-radio-energy-model-helper.h"
55 #include "ns3/yans-wifi-helper.h"
56 
57 #include <fstream>
58 #include <iostream>
59 #include <string>
60 #include <vector>
61 
62 using namespace ns3;
63 
64 NS_LOG_COMPONENT_DEFINE("EnergyWithHarvestingExample");
65 
72 static inline std::string
74 {
76 
77  std::ostringstream oss;
78  oss << "--\nReceived one packet! Socket: " << iaddr.GetIpv4() << " port: " << iaddr.GetPort()
79  << " at time = " << Simulator::Now().GetSeconds() << "\n--";
80 
81  return oss.str();
82 }
83 
89 void
91 {
92  Ptr<Packet> packet;
93  Address from;
94  while ((packet = socket->RecvFrom(from)))
95  {
96  if (packet->GetSize() > 0)
97  {
99  }
100  }
101 }
102 
112 static void
114  uint32_t pktSize,
115  Ptr<Node> n,
116  uint32_t pktCount,
117  Time pktInterval)
118 {
119  if (pktCount > 0)
120  {
121  socket->Send(Create<Packet>(pktSize));
122  Simulator::Schedule(pktInterval,
124  socket,
125  pktSize,
126  n,
127  pktCount - 1,
128  pktInterval);
129  }
130  else
131  {
132  socket->Close();
133  }
134 }
135 
142 void
143 RemainingEnergy(double oldValue, double remainingEnergy)
144 {
145  NS_LOG_UNCOND(Simulator::Now().GetSeconds()
146  << "s Current remaining energy = " << remainingEnergy << "J");
147 }
148 
155 void
156 TotalEnergy(double oldValue, double totalEnergy)
157 {
158  NS_LOG_UNCOND(Simulator::Now().GetSeconds()
159  << "s Total energy consumed by radio = " << totalEnergy << "J");
160 }
161 
168 void
169 HarvestedPower(double oldValue, double harvestedPower)
170 {
171  NS_LOG_UNCOND(Simulator::Now().GetSeconds()
172  << "s Current harvested power = " << harvestedPower << " W");
173 }
174 
181 void
182 TotalEnergyHarvested(double oldValue, double totalEnergyHarvested)
183 {
184  NS_LOG_UNCOND(Simulator::Now().GetSeconds()
185  << "s Total energy harvested by harvester = " << totalEnergyHarvested << " J");
186 }
187 
188 int
189 main(int argc, char* argv[])
190 {
191  std::string phyMode("DsssRate1Mbps");
192  double Prss = -80; // dBm
193  uint32_t PacketSize = 200; // bytes
194  bool verbose = false;
195 
196  // simulation parameters
197  uint32_t numPackets = 10000; // number of packets to send
198  double interval = 1; // seconds
199  double startTime = 0.0; // seconds
200  double distanceToRx = 100.0; // meters
201 
202  // Energy Harvester variables
203  double harvestingUpdateInterval = 1; // seconds
204 
205  CommandLine cmd(__FILE__);
206  cmd.AddValue("phyMode", "Wifi Phy mode", phyMode);
207  cmd.AddValue("Prss", "Intended primary RSS (dBm)", Prss);
208  cmd.AddValue("PacketSize", "size of application packet sent", PacketSize);
209  cmd.AddValue("numPackets", "Total number of packets to send", numPackets);
210  cmd.AddValue("startTime", "Simulation start time", startTime);
211  cmd.AddValue("distanceToRx", "X-Axis distance between nodes", distanceToRx);
212  cmd.AddValue("verbose", "Turn on all device log components", verbose);
213  cmd.Parse(argc, argv);
214 
215  // Convert to time object
216  Time interPacketInterval = Seconds(interval);
217 
218  // disable fragmentation for frames below 2200 bytes
219  Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
220  StringValue("2200"));
221  // turn off RTS/CTS for frames below 2200 bytes
222  Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("2200"));
223  // Fix non-unicast data rate to be the same as that of unicast
224  Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
225 
226  NodeContainer c;
227  c.Create(2); // create 2 nodes
228  NodeContainer networkNodes;
229  networkNodes.Add(c.Get(0));
230  networkNodes.Add(c.Get(1));
231 
232  // The below set of helpers will help us to put together the wifi NICs we want
234  if (verbose)
235  {
237  }
238  wifi.SetStandard(WIFI_STANDARD_80211b);
239 
241  /***************************************************************************/
242  YansWifiPhyHelper wifiPhy;
243 
245  YansWifiChannelHelper wifiChannel;
246  wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
247  wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
248 
249  // create wifi channel
250  Ptr<YansWifiChannel> wifiChannelPtr = wifiChannel.Create();
251  wifiPhy.SetChannel(wifiChannelPtr);
252 
254  // Add a MAC and disable rate control
255  WifiMacHelper wifiMac;
256  wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
257  "DataMode",
258  StringValue(phyMode),
259  "ControlMode",
260  StringValue(phyMode));
261  // Set it to ad-hoc mode
262  wifiMac.SetType("ns3::AdhocWifiMac");
263 
265  NetDeviceContainer devices = wifi.Install(wifiPhy, wifiMac, networkNodes);
266 
269  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator>();
270  positionAlloc->Add(Vector(0.0, 0.0, 0.0));
271  positionAlloc->Add(Vector(2 * distanceToRx, 0.0, 0.0));
272  mobility.SetPositionAllocator(positionAlloc);
273  mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
274  mobility.Install(c);
275 
277  /***************************************************************************/
278  /* energy source */
279  BasicEnergySourceHelper basicSourceHelper;
280  // configure energy source
281  basicSourceHelper.Set("BasicEnergySourceInitialEnergyJ", DoubleValue(1.0));
282  // install source
283  EnergySourceContainer sources = basicSourceHelper.Install(c);
284  /* device energy model */
285  WifiRadioEnergyModelHelper radioEnergyHelper;
286  // configure radio energy model
287  radioEnergyHelper.Set("TxCurrentA", DoubleValue(0.0174));
288  radioEnergyHelper.Set("RxCurrentA", DoubleValue(0.0197));
289  // install device model
290  DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install(devices, sources);
291 
292  /* energy harvester */
293  BasicEnergyHarvesterHelper basicHarvesterHelper;
294  // configure energy harvester
295  basicHarvesterHelper.Set("PeriodicHarvestedPowerUpdateInterval",
296  TimeValue(Seconds(harvestingUpdateInterval)));
297  basicHarvesterHelper.Set("HarvestablePower",
298  StringValue("ns3::UniformRandomVariable[Min=0.0|Max=0.1]"));
299  // install harvester on all energy sources
300  EnergyHarvesterContainer harvesters = basicHarvesterHelper.Install(sources);
301  /***************************************************************************/
302 
305  internet.Install(networkNodes);
306 
308  NS_LOG_INFO("Assign IP Addresses.");
309  ipv4.SetBase("10.1.1.0", "255.255.255.0");
310  Ipv4InterfaceContainer i = ipv4.Assign(devices);
311 
312  TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
313  Ptr<Socket> recvSink = Socket::CreateSocket(networkNodes.Get(1), tid); // node 1, Destination
315  recvSink->Bind(local);
317 
318  Ptr<Socket> source = Socket::CreateSocket(networkNodes.Get(0), tid); // node 0, Source
320  source->SetAllowBroadcast(true);
321  source->Connect(remote);
322 
324  /***************************************************************************/
325  // all traces are connected to node 1 (Destination)
326  // energy source
327  Ptr<BasicEnergySource> basicSourcePtr = DynamicCast<BasicEnergySource>(sources.Get(1));
328  basicSourcePtr->TraceConnectWithoutContext("RemainingEnergy", MakeCallback(&RemainingEnergy));
329  // device energy model
330  Ptr<DeviceEnergyModel> basicRadioModelPtr =
331  basicSourcePtr->FindDeviceEnergyModels("ns3::WifiRadioEnergyModel").Get(0);
332  NS_ASSERT(basicRadioModelPtr);
333  basicRadioModelPtr->TraceConnectWithoutContext("TotalEnergyConsumption",
335  // energy harvester
336  Ptr<BasicEnergyHarvester> basicHarvesterPtr =
337  DynamicCast<BasicEnergyHarvester>(harvesters.Get(1));
338  basicHarvesterPtr->TraceConnectWithoutContext("HarvestedPower", MakeCallback(&HarvestedPower));
339  basicHarvesterPtr->TraceConnectWithoutContext("TotalEnergyHarvested",
341  /***************************************************************************/
342 
344  // start traffic
345  Simulator::Schedule(Seconds(startTime),
347  source,
348  PacketSize,
349  networkNodes.Get(0),
350  numPackets,
351  interPacketInterval);
352 
353  Simulator::Stop(Seconds(10.0));
354  Simulator::Run();
355 
356  for (auto iter = deviceModels.Begin(); iter != deviceModels.End(); iter++)
357  {
358  double energyConsumed = (*iter)->GetTotalEnergyConsumption();
359  NS_LOG_UNCOND("End of simulation ("
360  << Simulator::Now().GetSeconds()
361  << "s) Total energy consumed by radio = " << energyConsumed << "J");
362  NS_ASSERT(energyConsumed <= 1.0);
363  }
364 
366 
367  return 0;
368 }
a polymophic address class
Definition: address.h:101
Creates a BasicEnergyHarvester object.
void Set(std::string name, const AttributeValue &v) override
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::EnergyHarvester pointers.
Ptr< EnergyHarvester > Get(uint32_t i) const
Get the i-th Ptr<EnergyHarvester> stored in this container.
EnergyHarvesterContainer Install(Ptr< EnergySource > source) const
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 HarvestedPower(double oldValue, double harvestedPower)
Trace function for the power harvested by the energy harvester.
void TotalEnergy(double oldValue, double totalEnergy)
Trace function for total energy consumption at node.
void ReceivePacket(Ptr< Socket > socket)
void TotalEnergyHarvested(double oldValue, double totalEnergyHarvested)
Trace function for the total energy harvested by the node.
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.
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
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)