A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
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 * SPDX-License-Identifier: GPL-2.0-only
6 *
7 * Author: Cristiano Tapparello <cristiano.tapparello@rochester.edu>
8 */
9
10/**
11 *
12 * This example extends the energy model example by connecting a basic energy
13 * harvester to the nodes.
14 *
15 * The example considers a simple communication link between a source and a
16 * destination node, where the source node sends a packet to the destination
17 * every 1 second. Each node is powered by a BasicEnergySource, which is recharged
18 * by a BasicEnergyHarvester, and the WiFi radio consumes energy for the transmission/
19 * reception of the packets.
20 *
21 * For the receiver node, the example prints the energy consumption of the WiFi radio,
22 * the power harvested by the energy harvester and the residual energy in the
23 * energy source.
24 *
25 * The nodes initial energy is set to 1.0 J, the transmission and reception entail a
26 * current consumption of 0.0174 A and 0.0197 A, respectively (default values in
27 * WifiRadioEnergyModel). The energy harvester provides an amount of power that varies
28 * according to a random variable uniformly distributed in [0 0.1] W, and is updated
29 * every 1 s. The energy source voltage is 3 V (default value in BasicEnergySource) and
30 * the residual energy level is updated every 1 second (default value).
31 *
32 * The simulation start at time 0 and it is hard stopped at time 10 seconds. Given the
33 * packet size and the distance between the nodes, each transmission lasts 0.0023s.
34 * As a result, the destination node receives 10 messages.
35 *
36 */
37
38#include "ns3/core-module.h"
39#include "ns3/energy-module.h"
40#include "ns3/internet-module.h"
41#include "ns3/mobility-module.h"
42#include "ns3/network-module.h"
43#include "ns3/wifi-radio-energy-model-helper.h"
44#include "ns3/yans-wifi-helper.h"
45
46#include <fstream>
47#include <iostream>
48#include <string>
49#include <vector>
50
51using namespace ns3;
52using namespace ns3::energy;
53
54NS_LOG_COMPONENT_DEFINE("EnergyWithHarvestingExample");
55
56/**
57 * Print a received packet
58 *
59 * \param from sender address
60 * \return a string with the details of the packet: dst {IP, port}, time.
61 */
62static inline std::string
64{
66
67 std::ostringstream oss;
68 oss << "--\nReceived one packet! Socket: " << iaddr.GetIpv4() << " port: " << iaddr.GetPort()
69 << " at time = " << Simulator::Now().GetSeconds() << "\n--";
70
71 return oss.str();
72}
73
74/**
75 * \param socket Pointer to socket.
76 *
77 * Packet receiving sink.
78 */
79void
81{
82 Ptr<Packet> packet;
83 Address from;
84 while ((packet = socket->RecvFrom(from)))
85 {
86 if (packet->GetSize() > 0)
87 {
89 }
90 }
91}
92
93/**
94 * \param socket Pointer to socket.
95 * \param pktSize Packet size.
96 * \param n Pointer to node.
97 * \param pktCount Number of packets to generate.
98 * \param pktInterval Packet sending interval.
99 *
100 * Traffic generator.
101 */
102static void
105 Ptr<Node> n,
106 uint32_t pktCount,
107 Time pktInterval)
108{
109 if (pktCount > 0)
110 {
111 socket->Send(Create<Packet>(pktSize));
112 Simulator::Schedule(pktInterval,
114 socket,
115 pktSize,
116 n,
117 pktCount - 1,
118 pktInterval);
119 }
120 else
121 {
122 socket->Close();
123 }
124}
125
126/**
127 * Trace function for remaining energy at node.
128 *
129 * \param oldValue Old value
130 * \param remainingEnergy New value
131 */
132void
133RemainingEnergy(double oldValue, double remainingEnergy)
134{
135 NS_LOG_UNCOND(Simulator::Now().GetSeconds()
136 << "s Current remaining energy = " << remainingEnergy << "J");
137}
138
139/**
140 * Trace function for total energy consumption at node.
141 *
142 * \param oldValue Old value
143 * \param totalEnergy New value
144 */
145void
146TotalEnergy(double oldValue, double totalEnergy)
147{
148 NS_LOG_UNCOND(Simulator::Now().GetSeconds()
149 << "s Total energy consumed by radio = " << totalEnergy << "J");
150}
151
152/**
153 * Trace function for the power harvested by the energy harvester.
154 *
155 * \param oldValue Old value
156 * \param harvestedPower New value
157 */
158void
159HarvestedPower(double oldValue, double harvestedPower)
160{
161 NS_LOG_UNCOND(Simulator::Now().GetSeconds()
162 << "s Current harvested power = " << harvestedPower << " W");
163}
164
165/**
166 * Trace function for the total energy harvested by the node.
167 *
168 * \param oldValue Old value
169 * \param totalEnergyHarvested New value
170 */
171void
172TotalEnergyHarvested(double oldValue, double totalEnergyHarvested)
173{
174 NS_LOG_UNCOND(Simulator::Now().GetSeconds()
175 << "s Total energy harvested by harvester = " << totalEnergyHarvested << " J");
176}
177
178int
179main(int argc, char* argv[])
180{
181 std::string phyMode("DsssRate1Mbps");
182 double Prss = -80; // dBm
183 uint32_t PacketSize = 200; // bytes
184 bool verbose = false;
185
186 // simulation parameters
187 uint32_t numPackets = 10000; // number of packets to send
188 double interval = 1; // seconds
189 double startTime = 0.0; // seconds
190 double distanceToRx = 100.0; // meters
191
192 // Energy Harvester variables
193 double harvestingUpdateInterval = 1; // seconds
194
195 CommandLine cmd(__FILE__);
196 cmd.AddValue("phyMode", "Wifi Phy mode", phyMode);
197 cmd.AddValue("Prss", "Intended primary RSS (dBm)", Prss);
198 cmd.AddValue("PacketSize", "size of application packet sent", PacketSize);
199 cmd.AddValue("numPackets", "Total number of packets to send", numPackets);
200 cmd.AddValue("startTime", "Simulation start time", startTime);
201 cmd.AddValue("distanceToRx", "X-Axis distance between nodes", distanceToRx);
202 cmd.AddValue("verbose", "Turn on all device log components", verbose);
203 cmd.Parse(argc, argv);
204
205 // Convert to time object
206 Time interPacketInterval = Seconds(interval);
207
208 // disable fragmentation for frames below 2200 bytes
209 Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
210 StringValue("2200"));
211 // turn off RTS/CTS for frames below 2200 bytes
212 Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("2200"));
213 // Fix non-unicast data rate to be the same as that of unicast
214 Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
215
217 c.Create(2); // create 2 nodes
218 NodeContainer networkNodes;
219 networkNodes.Add(c.Get(0));
220 networkNodes.Add(c.Get(1));
221
222 // The below set of helpers will help us to put together the wifi NICs we want
224 if (verbose)
225 {
227 }
228 wifi.SetStandard(WIFI_STANDARD_80211b);
229
230 /** Wifi PHY **/
231 /***************************************************************************/
232 YansWifiPhyHelper wifiPhy;
233
234 /** wifi channel **/
235 YansWifiChannelHelper wifiChannel;
236 wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
237 wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
238
239 // create wifi channel
240 Ptr<YansWifiChannel> wifiChannelPtr = wifiChannel.Create();
241 wifiPhy.SetChannel(wifiChannelPtr);
242
243 /** MAC layer **/
244 // Add a MAC and disable rate control
245 WifiMacHelper wifiMac;
246 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
247 "DataMode",
248 StringValue(phyMode),
249 "ControlMode",
250 StringValue(phyMode));
251 // Set it to ad-hoc mode
252 wifiMac.SetType("ns3::AdhocWifiMac");
253
254 /** install PHY + MAC **/
255 NetDeviceContainer devices = wifi.Install(wifiPhy, wifiMac, networkNodes);
256
257 /** mobility **/
260 positionAlloc->Add(Vector(0.0, 0.0, 0.0));
261 positionAlloc->Add(Vector(2 * distanceToRx, 0.0, 0.0));
262 mobility.SetPositionAllocator(positionAlloc);
263 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
264 mobility.Install(c);
265
266 /** Energy Model **/
267 /***************************************************************************/
268 /* energy source */
269 BasicEnergySourceHelper basicSourceHelper;
270 // configure energy source
271 basicSourceHelper.Set("BasicEnergySourceInitialEnergyJ", DoubleValue(1.0));
272 // install source
273 EnergySourceContainer sources = basicSourceHelper.Install(c);
274 /* device energy model */
275 WifiRadioEnergyModelHelper radioEnergyHelper;
276 // configure radio energy model
277 radioEnergyHelper.Set("TxCurrentA", DoubleValue(0.0174));
278 radioEnergyHelper.Set("RxCurrentA", DoubleValue(0.0197));
279 // install device model
280 DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install(devices, sources);
281
282 /* energy harvester */
283 BasicEnergyHarvesterHelper basicHarvesterHelper;
284 // configure energy harvester
285 basicHarvesterHelper.Set("PeriodicHarvestedPowerUpdateInterval",
286 TimeValue(Seconds(harvestingUpdateInterval)));
287 basicHarvesterHelper.Set("HarvestablePower",
288 StringValue("ns3::UniformRandomVariable[Min=0.0|Max=0.1]"));
289 // install harvester on all energy sources
290 EnergyHarvesterContainer harvesters = basicHarvesterHelper.Install(sources);
291 /***************************************************************************/
292
293 /** Internet stack **/
295 internet.Install(networkNodes);
296
298 NS_LOG_INFO("Assign IP Addresses.");
299 ipv4.SetBase("10.1.1.0", "255.255.255.0");
300 Ipv4InterfaceContainer i = ipv4.Assign(devices);
301
302 TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
303 Ptr<Socket> recvSink = Socket::CreateSocket(networkNodes.Get(1), tid); // node 1, Destination
305 recvSink->Bind(local);
306 recvSink->SetRecvCallback(MakeCallback(&ReceivePacket));
307
308 Ptr<Socket> source = Socket::CreateSocket(networkNodes.Get(0), tid); // node 0, Source
310 source->SetAllowBroadcast(true);
311 source->Connect(remote);
312
313 /** connect trace sources **/
314 /***************************************************************************/
315 // all traces are connected to node 1 (Destination)
316 // energy source
317 Ptr<BasicEnergySource> basicSourcePtr = DynamicCast<BasicEnergySource>(sources.Get(1));
318 basicSourcePtr->TraceConnectWithoutContext("RemainingEnergy", MakeCallback(&RemainingEnergy));
319 // device energy model
320 Ptr<DeviceEnergyModel> basicRadioModelPtr =
321 basicSourcePtr->FindDeviceEnergyModels("ns3::WifiRadioEnergyModel").Get(0);
322 NS_ASSERT(basicRadioModelPtr);
323 basicRadioModelPtr->TraceConnectWithoutContext("TotalEnergyConsumption",
325 // energy harvester
326 Ptr<BasicEnergyHarvester> basicHarvesterPtr =
328 basicHarvesterPtr->TraceConnectWithoutContext("HarvestedPower", MakeCallback(&HarvestedPower));
329 basicHarvesterPtr->TraceConnectWithoutContext("TotalEnergyHarvested",
331 /***************************************************************************/
332
333 /** simulation setup **/
334 // start traffic
335 Simulator::Schedule(Seconds(startTime),
337 source,
338 PacketSize,
339 networkNodes.Get(0),
340 numPackets,
341 interPacketInterval);
342
345
346 for (auto iter = deviceModels.Begin(); iter != deviceModels.End(); iter++)
347 {
348 double energyConsumed = (*iter)->GetTotalEnergyConsumption();
349 NS_LOG_UNCOND("End of simulation ("
350 << Simulator::Now().GetSeconds()
351 << "s) Total energy consumed by radio = " << energyConsumed << "J");
352 NS_ASSERT(energyConsumed <= 1.0);
353 }
354
356
357 return 0;
358}
a polymophic address class
Definition address.h:90
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.
energy::DeviceEnergyModelContainer Install(Ptr< NetDevice > device, Ptr< energy::EnergySource > source) const
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
energy::EnergyHarvesterContainer Install(Ptr< energy::EnergySource > source) const
energy::EnergySourceContainer Install(Ptr< Node > node) const
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.
Smart pointer class similar to boost::intrusive_ptr.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:560
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition simulator.cc:131
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:197
static void Run()
Run the simulation.
Definition simulator.cc:167
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition simulator.cc:175
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:61
Hold variables of type string.
Definition string.h:45
Simulation virtual time values and global simulation resolution.
Definition nstime.h:94
double GetSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
Definition nstime.h:392
a unique identifier for an interface.
Definition type-id.h:48
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition type-id.cc:872
helps to create WifiNetDevice objects
static void EnableLogComponents(LogLevel logLevel=LOG_LEVEL_ALL)
Helper to enable all WifiNetDevice log components with one statement.
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)
Holds a vector of ns3::DeviceEnergyModel pointers.
Iterator End() const
Get an iterator which refers to the last DeviceEnergyModel pointer in the container.
Iterator Begin() const
Get an iterator which refers to the first DeviceEnergyModel pointer in the container.
Holds a vector of ns3::EnergyHarvester pointers.
Ptr< EnergyHarvester > Get(uint32_t i) const
Get the i-th Ptr<EnergyHarvester> stored in this container.
Holds a vector of ns3::EnergySource pointers.
Ptr< EnergySource > Get(uint32_t i) const
Get the i-th Ptr<EnergySource> stored in this container.
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:55
void SetDefault(std::string name, const AttributeValue &value)
Definition config.cc:883
#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:191
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:264
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:436
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1308
@ WIFI_STANDARD_80211b
devices
Definition first.py:31
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:684
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:580
wifi
Definition third.py:84
mobility
Definition third.py:92
bool verbose
uint32_t pktSize
packet size used for the simulation (in bytes)