A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
generic-battery-wifiradio-example.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2023 Tokushima University, Japan
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Alberto Gallegos Ramonet <alramonet@is.tokushima-u.ac.jp>
7 */
8
9/*
10 * Node 1 <-------------- distanceToRx ------------> Node2
11 * (SoC 89%) (SoC 95%)
12 *
13 * This example is based on the basic-energy-model-test created by He Wu.
14 * The objective is to demonstrate the use of a GenericBatteryModel with
15 * the WifiRadioEnergyModel. The WifiRadioEnergyModel was created to work
16 * specifically with the BasicEnergySource, therefore, the current example
17 * should be considered a prototype until WifiRadioEnergyModel can be
18 * revised and thoroughly tested with the GenericBatterySource.
19 *
20 * In the example, 2 wifi nodes are created each with a GenericBatterySource
21 * (Li-Ion battery type) is created with 4 cells (2 series, 2 parallel).
22 * The simulation runs for 3600 secs. Tx, Rx and Idle consumption values
23 * have been exaggerated for demonstration purposes. At the end of the simulation,
24 * the State of Charge (Soc %) and remaining capacity in Jouls for each node is
25 * displayed.
26 *
27 */
28
29#include <ns3/core-module.h>
30#include <ns3/energy-module.h>
31#include <ns3/internet-module.h>
32#include <ns3/mobility-module.h>
33#include <ns3/network-module.h>
34#include <ns3/wifi-module.h>
35
36#include <sstream>
37#include <string>
38
39using namespace ns3;
40using namespace ns3::energy;
41
42NS_LOG_COMPONENT_DEFINE("GenericBatteryWifiRadioExample");
43
44/**
45 * Print a received packet
46 *
47 * \param from sender address
48 * \return a string with the details of the packet: dst {IP, port}, time.
49 */
50inline std::string
52{
54
55 std::ostringstream oss;
56 oss << " Received one packet! Socket: " << iaddr.GetIpv4() << " port: " << iaddr.GetPort()
57 << "\n";
58
59 return oss.str();
60}
61
62/**
63 * \param socket Pointer to socket.
64 *
65 * Packet receiving sink.
66 */
67void
69{
70 Ptr<Packet> packet;
71 Address from;
72 while ((packet = socket->RecvFrom(from)))
73 {
74 if (packet->GetSize() > 0)
75 {
77 }
78 }
79}
80
81/**
82 * \param socket Pointer to socket.
83 * \param pktSize Packet size.
84 * \param n Pointer to node.
85 * \param pktCount Number of packets to generate.
86 * \param pktInterval Packet sending interval.
87 *
88 * Generate Traffic
89 */
90static void
93 Ptr<Node> n,
94 uint32_t pktCount,
95 Time pktInterval)
96{
97 if (pktCount > 0)
98 {
99 socket->Send(Create<Packet>(pktSize));
100 Simulator::Schedule(pktInterval,
102 socket,
103 pktSize,
104 n,
105 pktCount - 1,
106 pktInterval);
107 }
108 else
109 {
110 socket->Close();
111 }
112}
113
114/**
115 * Trace function for remaining energy at node.
116 *
117 * \param oldValue Old value
118 * \param remainingEnergy New value
119 */
120void
121RemainingEnergy(double oldValue, double remainingEnergy)
122{
123 NS_LOG_DEBUG(" Remaining energy Node 1 = " << remainingEnergy << " J");
124}
125
126int
127main(int argc, char* argv[])
128{
130 LogComponentEnable("GenericBatteryWifiRadioExample", LOG_LEVEL_DEBUG);
131
132 std::string phyMode("DsssRate1Mbps");
133 double rss = -80; // dBm
134 uint32_t packetSize = 200; // bytes
135 bool verbose = false;
136
137 // simulation parameters
138 uint32_t numPackets = 10000; // number of packets to send
139 double interval = 1; // seconds
140 double startTime = 0.0; // seconds
141 double distanceToRx = 100.0; // meters
142
143 CommandLine cmd(__FILE__);
144 cmd.AddValue("phyMode", "Wifi Phy mode", phyMode);
145 cmd.AddValue("rss", "Intended primary RSS (dBm)", rss);
146 cmd.AddValue("packetSize", "size of application packet sent (Bytes)", packetSize);
147 cmd.AddValue("numPackets", "Total number of packets to send", numPackets);
148 cmd.AddValue("startTime", "Simulation start time (seconds)", startTime);
149 cmd.AddValue("distanceToRx", "X-Axis distance between nodes (meters)", distanceToRx);
150 cmd.AddValue("verbose", "Turn on all device log components", verbose);
151 cmd.Parse(argc, argv);
152
153 Time interPacketInterval = Seconds(interval);
154
155 Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
156 StringValue("2200"));
157 Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("2200"));
158 Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
159
160 NodeContainer nodeContainer;
161 nodeContainer.Create(2);
162
164 if (verbose)
165 {
167 }
168 wifi.SetStandard(WIFI_STANDARD_80211b);
169
170 ////////////////////////
171 // Wifi PHY and MAC //
172 ////////////////////////
173
174 YansWifiPhyHelper wifiPhy;
175 YansWifiChannelHelper wifiChannel;
176 wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
177 wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
178
179 Ptr<YansWifiChannel> wifiChannelPtr = wifiChannel.Create();
180 wifiPhy.SetChannel(wifiChannelPtr);
181
182 WifiMacHelper wifiMac;
183 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
184 "DataMode",
185 StringValue(phyMode),
186 "ControlMode",
187 StringValue(phyMode));
188
189 wifiMac.SetType("ns3::AdhocWifiMac");
190 NetDeviceContainer devices = wifi.Install(wifiPhy, wifiMac, nodeContainer);
191
192 //////////////////
193 // Mobility //
194 //////////////////
195
198 positionAlloc->Add(Vector(0.0, 0.0, 0.0));
199 positionAlloc->Add(Vector(2 * distanceToRx, 0.0, 0.0));
200 mobility.SetPositionAllocator(positionAlloc);
201 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
202 mobility.Install(nodeContainer);
203
204 //////////////////////
205 // Energy Model //
206 //////////////////////
207
208 // Use a preset PANASONIC Li-Ion batteries arranged in a cell pack (2 series, 2 parallel)
209 GenericBatteryModelHelper batteryHelper;
210 EnergySourceContainer energySourceContainer =
211 batteryHelper.Install(nodeContainer, PANASONIC_CGR18650DA_LION);
212 batteryHelper.SetCellPack(energySourceContainer, 2, 2);
213
214 Ptr<GenericBatteryModel> battery0 =
215 DynamicCast<GenericBatteryModel>(energySourceContainer.Get(0));
216 Ptr<GenericBatteryModel> battery1 =
217 DynamicCast<GenericBatteryModel>(energySourceContainer.Get(1));
218
219 // Energy consumption quantities have been exaggerated for
220 // demonstration purposes, real consumption values are much smaller.
221 WifiRadioEnergyModelHelper radioEnergyHelper;
222 radioEnergyHelper.Set("TxCurrentA", DoubleValue(4.66));
223 radioEnergyHelper.Set("RxCurrentA", DoubleValue(0.466));
224 radioEnergyHelper.Set("IdleCurrentA", DoubleValue(0.466));
225 DeviceEnergyModelContainer deviceModels =
226 radioEnergyHelper.Install(devices, energySourceContainer);
227
228 /////////////////////
229 // Internet stack //
230 /////////////////////
231
233 internet.Install(nodeContainer);
234
236 ipv4.SetBase("10.1.1.0", "255.255.255.0");
237 Ipv4InterfaceContainer i = ipv4.Assign(devices);
238
239 TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
240 Ptr<Socket> recvSink = Socket::CreateSocket(nodeContainer.Get(1), tid); // node 1, receiver
242 recvSink->Bind(local);
243 recvSink->SetRecvCallback(MakeCallback(&ReceivePacket));
244
245 Ptr<Socket> source = Socket::CreateSocket(nodeContainer.Get(0), tid); // node 0, sender
247 source->SetAllowBroadcast(true);
248 source->Connect(remote);
249
250 /////////////////////
251 // Trace Sources //
252 /////////////////////
253
254 battery1->TraceConnectWithoutContext("RemainingEnergy", MakeCallback(&RemainingEnergy));
255
256 Ptr<DeviceEnergyModel> radioConsumptionModel =
257 battery1->FindDeviceEnergyModels("ns3::WifiRadioEnergyModel").Get(0);
258
259 /////////////////////
260 // Traffic Setup //
261 /////////////////////
262 Simulator::Schedule(Seconds(startTime),
264 source,
266 nodeContainer.Get(0),
267 numPackets,
268 interPacketInterval);
269
272
273 NS_LOG_DEBUG(" *Remaining Capacity * "
274 << "| Node 0: " << battery0->GetRemainingEnergy() << " J "
275 << "| Node 1: " << battery1->GetRemainingEnergy() << " J");
276 NS_LOG_DEBUG(" *SoC * "
277 << "| Node 0: " << battery0->GetStateOfCharge() << " % "
278 << "| Node 1: " << battery1->GetStateOfCharge() << " % ");
279
281
282 return 0;
283}
a polymophic address class
Definition address.h:90
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
Creates and assign an assortment of BatteryModels to Nodes.
void SetCellPack(Ptr< energy::EnergySource > energySource, uint8_t series, uint8_t parallel) const
This function takes an existing energy source and transform its values to form a group of connected i...
Ptr< energy::EnergySourceContainer > Install(NodeContainer c) const
This function installs energy sources in a group of nodes in a node container.
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.
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 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
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.
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 ReceivePacket(Ptr< Socket > socket)
std::string PrintReceivedPacket(Address &from)
Print a received packet.
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)
void SetDefault(std::string name, const AttributeValue &value)
Definition config.cc:883
@ PANASONIC_CGR18650DA_LION
Panasonic CGR18650DA Li-Ion battery.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:257
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.
void LogComponentEnable(const std::string &name, LogLevel level)
Enable the logging output associated with that log component.
Definition log.cc:291
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
LogLevel
Logging severity classes and levels.
Definition log.h:83
@ LOG_PREFIX_FUNC
Prefix all trace prints with function.
Definition log.h:107
@ LOG_PREFIX_TIME
Prefix all trace prints with simulation time.
Definition log.h:108
@ LOG_LEVEL_DEBUG
LOG_DEBUG and above.
Definition log.h:102
void LogComponentEnableAll(LogLevel level)
Enable the logging output for all registered log components.
Definition log.cc:309
wifi
Definition third.py:84
mobility
Definition third.py:92
bool verbose
uint32_t pktSize
packet size used for the simulation (in bytes)
static const uint32_t packetSize
Packet size generated at the AP.