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