A Discrete-Event Network Simulator
API
energy-model-with-harvesting-example.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2014 Wireless Communications and Networking Group (WCNG),
4  * University of Rochester, Rochester, NY, USA.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation;
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  *
19  * Author: Cristiano Tapparello <cristiano.tapparello@rochester.edu>
20  */
21 
50 #include <iostream>
51 #include <fstream>
52 #include <vector>
53 #include <string>
54 #include "ns3/core-module.h"
55 #include "ns3/network-module.h"
56 #include "ns3/mobility-module.h"
57 #include "ns3/config-store-module.h"
58 #include "ns3/energy-module.h"
59 #include "ns3/internet-module.h"
60 #include "ns3/yans-wifi-helper.h"
61 #include "ns3/wifi-radio-energy-model-helper.h"
62 
63 using namespace ns3;
64 
65 NS_LOG_COMPONENT_DEFINE ("EnergyWithHarvestingExample");
66 
67 static inline std::string
69 {
71 
72  std::ostringstream oss;
73  oss << "--\nReceived one packet! Socket: " << iaddr.GetIpv4 ()
74  << " port: " << iaddr.GetPort ()
75  << " at time = " << Simulator::Now ().GetSeconds ()
76  << "\n--";
77 
78  return oss.str ();
79 }
80 
86 void
88 {
89  Ptr<Packet> packet;
90  Address from;
91  while ((packet = socket->RecvFrom (from)))
92  {
93  if (packet->GetSize () > 0)
94  {
96  }
97  }
98 }
99 
109 static void
110 GenerateTraffic (Ptr<Socket> socket, uint32_t pktSize, Ptr<Node> n,
111  uint32_t pktCount, Time pktInterval)
112 {
113  if (pktCount > 0)
114  {
115  socket->Send (Create<Packet> (pktSize));
116  Simulator::Schedule (pktInterval, &GenerateTraffic, socket, pktSize, n,
117  pktCount - 1, pktInterval);
118  }
119  else
120  {
121  socket->Close ();
122  }
123 }
124 
126 void
127 RemainingEnergy (double oldValue, double remainingEnergy)
128 {
129  NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
130  << "s Current remaining energy = " << remainingEnergy << "J");
131 }
132 
134 void
135 TotalEnergy (double oldValue, double totalEnergy)
136 {
137  NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
138  << "s Total energy consumed by radio = " << totalEnergy << "J");
139 }
140 
142 void
143 HarvestedPower (double oldValue, double harvestedPower)
144 {
145  NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
146  << "s Current harvested power = " << harvestedPower << " W");
147 }
148 
150 void
152 {
153  NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
154  << "s Total energy harvested by harvester = "
155  << TotalEnergyHarvested << " J");
156 }
157 
158 
159 int
160 main (int argc, char *argv[])
161 {
162  std::string phyMode ("DsssRate1Mbps");
163  double Prss = -80; // dBm
164  uint32_t PacketSize = 200; // bytes
165  bool verbose = false;
166 
167  // simulation parameters
168  uint32_t numPackets = 10000; // number of packets to send
169  double interval = 1; // seconds
170  double startTime = 0.0; // seconds
171  double distanceToRx = 100.0; // meters
172  /*
173  * This is a magic number used to set the transmit power, based on other
174  * configuration.
175  */
176  double offset = 81;
177 
178  // Energy Harvester variables
179  double harvestingUpdateInterval = 1; // seconds
180 
182  cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
183  cmd.AddValue ("Prss", "Intended primary RSS (dBm)", Prss);
184  cmd.AddValue ("PacketSize", "size of application packet sent", PacketSize);
185  cmd.AddValue ("numPackets", "Total number of packets to send", numPackets);
186  cmd.AddValue ("startTime", "Simulation start time", startTime);
187  cmd.AddValue ("distanceToRx", "X-Axis distance between nodes", distanceToRx);
188  cmd.AddValue ("verbose", "Turn on all device log components", verbose);
189  cmd.Parse (argc, argv);
190 
191  // Convert to time object
192  Time interPacketInterval = Seconds (interval);
193 
194  // disable fragmentation for frames below 2200 bytes
195  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold",
196  StringValue ("2200"));
197  // turn off RTS/CTS for frames below 2200 bytes
198  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold",
199  StringValue ("2200"));
200  // Fix non-unicast data rate to be the same as that of unicast
201  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",
202  StringValue (phyMode));
203 
204  NodeContainer c;
205  c.Create (2); // create 2 nodes
206  NodeContainer networkNodes;
207  networkNodes.Add (c.Get (0));
208  networkNodes.Add (c.Get (1));
209 
210  // The below set of helpers will help us to put together the wifi NICs we want
212  if (verbose)
213  {
214  wifi.EnableLogComponents ();
215  }
216  wifi.SetStandard (WIFI_PHY_STANDARD_80211b);
217 
219  /***************************************************************************/
221  wifiPhy.Set ("RxGain", DoubleValue (-10));
222  wifiPhy.Set ("TxGain", DoubleValue (offset + Prss));
223  wifiPhy.Set ("CcaMode1Threshold", DoubleValue (0.0));
224  /***************************************************************************/
225 
227  YansWifiChannelHelper wifiChannel;
228  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
229  wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
230  // create wifi channel
231  Ptr<YansWifiChannel> wifiChannelPtr = wifiChannel.Create ();
232  wifiPhy.SetChannel (wifiChannelPtr);
233 
235  // Add a MAC and disable rate control
236  WifiMacHelper wifiMac;
237  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode",
238  StringValue (phyMode), "ControlMode",
239  StringValue (phyMode));
240  // Set it to ad-hoc mode
241  wifiMac.SetType ("ns3::AdhocWifiMac");
242 
244  NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, networkNodes);
245 
248  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
249  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
250  positionAlloc->Add (Vector (2 * distanceToRx, 0.0, 0.0));
251  mobility.SetPositionAllocator (positionAlloc);
252  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
253  mobility.Install (c);
254 
256  /***************************************************************************/
257  /* energy source */
258  BasicEnergySourceHelper basicSourceHelper;
259  // configure energy source
260  basicSourceHelper.Set ("BasicEnergySourceInitialEnergyJ", DoubleValue (1.0));
261  // install source
262  EnergySourceContainer sources = basicSourceHelper.Install (c);
263  /* device energy model */
264  WifiRadioEnergyModelHelper radioEnergyHelper;
265  // configure radio energy model
266  radioEnergyHelper.Set ("TxCurrentA", DoubleValue (0.0174));
267  radioEnergyHelper.Set ("RxCurrentA", DoubleValue (0.0197));
268  // install device model
269  DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install (devices, sources);
270 
271  /* energy harvester */
272  BasicEnergyHarvesterHelper basicHarvesterHelper;
273  // configure energy harvester
274  basicHarvesterHelper.Set ("PeriodicHarvestedPowerUpdateInterval", TimeValue (Seconds (harvestingUpdateInterval)));
275  basicHarvesterHelper.Set ("HarvestablePower", StringValue ("ns3::UniformRandomVariable[Min=0.0|Max=0.1]"));
276  // install harvester on all energy sources
277  EnergyHarvesterContainer harvesters = basicHarvesterHelper.Install (sources);
278  /***************************************************************************/
279 
281  InternetStackHelper internet;
282  internet.Install (networkNodes);
283 
284  Ipv4AddressHelper ipv4;
285  NS_LOG_INFO ("Assign IP Addresses.");
286  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
288 
289  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
290  Ptr<Socket> recvSink = Socket::CreateSocket (networkNodes.Get (1), tid); // node 1, Destination
292  recvSink->Bind (local);
294 
295  Ptr<Socket> source = Socket::CreateSocket (networkNodes.Get (0), tid); // node 0, Source
297  source->SetAllowBroadcast (true);
298  source->Connect (remote);
299 
301  /***************************************************************************/
302  // all traces are connected to node 1 (Destination)
303  // energy source
304  Ptr<BasicEnergySource> basicSourcePtr = DynamicCast<BasicEnergySource> (sources.Get (1));
305  basicSourcePtr->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback (&RemainingEnergy));
306  // device energy model
307  Ptr<DeviceEnergyModel> basicRadioModelPtr =
308  basicSourcePtr->FindDeviceEnergyModels ("ns3::WifiRadioEnergyModel").Get (0);
309  NS_ASSERT (basicRadioModelPtr != 0);
310  basicRadioModelPtr->TraceConnectWithoutContext ("TotalEnergyConsumption", MakeCallback (&TotalEnergy));
311  // energy harvester
312  Ptr<BasicEnergyHarvester> basicHarvesterPtr = DynamicCast<BasicEnergyHarvester> (harvesters.Get (1));
313  basicHarvesterPtr->TraceConnectWithoutContext ("HarvestedPower", MakeCallback (&HarvestedPower));
314  basicHarvesterPtr->TraceConnectWithoutContext ("TotalEnergyHarvested", MakeCallback (&TotalEnergyHarvested));
315  /***************************************************************************/
316 
317 
319  // start traffic
320  Simulator::Schedule (Seconds (startTime), &GenerateTraffic, source, PacketSize,
321  networkNodes.Get (0), numPackets, interPacketInterval);
322 
323  Simulator::Stop (Seconds (10.0));
324  Simulator::Run ();
325 
326  for (DeviceEnergyModelContainer::Iterator iter = deviceModels.Begin (); iter != deviceModels.End (); iter ++)
327  {
328  double energyConsumed = (*iter)->GetTotalEnergyConsumption ();
329  NS_LOG_UNCOND ("End of simulation (" << Simulator::Now ().GetSeconds ()
330  << "s) Total energy consumed by radio = " << energyConsumed << "J");
331  NS_ASSERT (energyConsumed <= 1.0);
332  }
333 
335 
336  return 0;
337 }
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())
void Set(std::string name, const AttributeValue &v)
Definition: wifi-helper.cc:134
std::vector< Ptr< DeviceEnergyModel > >::const_iterator Iterator
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:102
Assign WifiRadioEnergyModel to wifi devices.
an Inet address class
static Ipv4Address GetAny(void)
Holds a vector of ns3::EnergySource pointers.
holds a vector of std::pair of Ptr<Ipv4> and interface index.
uint32_t GetSize(void) const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
Definition: packet.h:831
void TotalEnergy(double oldValue, double totalEnergy)
Trace function for total energy consumption at node.
Hold variables of type string.
Definition: string.h:41
virtual bool SetAllowBroadcast(bool allowBroadcast)=0
Configure whether broadcast datagram transmissions are allowed.
Make it easy to create and manage PHY objects for the yans model.
static void GenerateTraffic(Ptr< Socket > socket, uint32_t pktSize, Ptr< Node > n, uint32_t pktCount, Time pktInterval)
double GetSeconds(void) const
Get an approximation of the time stored in this instance in the indicated unit.
Definition: nstime.h:355
Creates a BasicEnergyHarvester object.
#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
static void Run(void)
Run the simulation.
Definition: simulator.cc:226
void TotalEnergyHarvested(double oldValue, double TotalEnergyHarvested)
Trace function for the total energy harvested by the node.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:202
aggregate IP/TCP/UDP functionality to existing Nodes.
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:278
cmd
Definition: second.py:35
static YansWifiPhyHelper Default(void)
Create a phy helper in a default working state.
helps to create WifiNetDevice objects
Definition: wifi-helper.h:230
Holds a vector of ns3::DeviceEnergyModel pointers.
Ptr< DeviceEnergyModel > Get(uint32_t i) const
Get the i-th Ptr<DeviceEnergyModel> stored in this container.
a polymophic address class
Definition: address.h:90
Ptr< YansWifiChannel > Create(void) const
mobility
Definition: third.py:101
void SetChannel(Ptr< YansWifiChannel > channel)
static EventId Schedule(Time const &delay, MEM mem_ptr, OBJ obj)
Schedule an event to expire after delay.
Definition: simulator.h:1381
AttributeValue implementation for Time.
Definition: nstime.h:1076
double startTime
EnergyHarvesterContainer Install(Ptr< EnergySource > source) const
Creates a BasicEnergySource object.
holds a vector of ns3::NetDevice pointers
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1489
void SetRecvCallback(Callback< void, Ptr< Socket > >)
Notify application when new data is available to be read.
Definition: socket.cc:128
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
void Set(std::string name, const AttributeValue &v)
Parse command-line arguments.
Definition: command-line.h:213
static Ipv4Address GetBroadcast(void)
static void Destroy(void)
Execute the events scheduled with ScheduleDestroy().
Definition: simulator.cc:190
void ReceivePacket(Ptr< Socket > socket)
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
bool TraceConnectWithoutContext(std::string name, const CallbackBase &cb)
Connect a TraceSource to a Callback without a context.
Definition: object-base.cc:293
void RemainingEnergy(double oldValue, double remainingEnergy)
Trace function for remaining energy at node.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
keep track of a set of node pointers.
Holds a vector of ns3::EnergyHarvester pointers.
DSSS PHY (Clause 15) and HR/DSSS PHY (Clause 18)
void Set(std::string name, const AttributeValue &v)
uint16_t GetPort(void) const
void HarvestedPower(double oldValue, double harvestedPower)
Trace function for the power harvested by the energy harvester.
#define NS_LOG_UNCOND(msg)
Output the requested message unconditionally.
manage and create wifi channel objects for the yans model.
create MAC layers for a ns3::WifiNetDevice.
static Time Now(void)
Return the current simulation virtual time.
Definition: simulator.cc:249
virtual void SetType(std::string type, 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(), std::string n8="", const AttributeValue &v8=EmptyAttributeValue(), std::string n9="", const AttributeValue &v9=EmptyAttributeValue(), std::string n10="", const AttributeValue &v10=EmptyAttributeValue())
void Install(std::string nodeName) const
Aggregate implementations of the ns3::Ipv4, ns3::Ipv6, ns3::Udp, and ns3::Tcp classes onto the provid...
wifi
Definition: third.py:89
Helper class used to assign positions and mobility models to nodes.
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
void Add(NodeContainer other)
Append the contents of another NodeContainer to the end of this container.
EnergySourceContainer Install(Ptr< Node > node) const
static void Stop(void)
Tell the Simulator the calling event should be the last one executed.
Definition: simulator.cc:234
Iterator End(void) const
Get an iterator which refers to the last DeviceEnergyModel pointer in the container.
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1014
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:782
void Set(std::string name, const AttributeValue &v)
Iterator Begin(void) const
Get an iterator which refers to the first DeviceEnergyModel pointer in the container.
void Add(Vector v)
Add a position to the list of positions.
Ptr< EnergyHarvester > Get(uint32_t i) const
Get the i-th Ptr<EnergyHarvester> stored in this container.
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
DeviceEnergyModelContainer FindDeviceEnergyModels(TypeId tid)
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
Ptr< EnergySource > Get(uint32_t i) const
Get the i-th Ptr<EnergySource> stored in this container.
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.
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())
devices
Definition: first.py:32
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
virtual int Close(void)=0
Close a socket.
This class can be used to hold variables of floating point type such as &#39;double&#39; or &#39;float&#39;...
Definition: double.h:41
a unique identifier for an interface.
Definition: type-id.h:58
static std::string PrintReceivedPacket(Address &from)
Ipv4Address GetIpv4(void) const
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
bool verbose
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition: type-id.cc:824
DeviceEnergyModelContainer Install(Ptr< NetDevice > device, Ptr< EnergySource > source) const