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;
51
52NS_LOG_COMPONENT_DEFINE("GenericBatteryWifiRadioExample");
53
54/**
55 * Print a received packet
56 *
57 * \param from sender address
58 * \return a string with the details of the packet: dst {IP, port}, time.
59 */
60inline std::string
62{
64
65 std::ostringstream oss;
66 oss << " Received one packet! Socket: " << iaddr.GetIpv4() << " port: " << iaddr.GetPort()
67 << "\n";
68
69 return oss.str();
70}
71
72/**
73 * \param socket Pointer to socket.
74 *
75 * Packet receiving sink.
76 */
77void
79{
80 Ptr<Packet> packet;
81 Address from;
82 while ((packet = socket->RecvFrom(from)))
83 {
84 if (packet->GetSize() > 0)
85 {
87 }
88 }
89}
90
91/**
92 * \param socket Pointer to socket.
93 * \param pktSize Packet size.
94 * \param n Pointer to node.
95 * \param pktCount Number of packets to generate.
96 * \param pktInterval Packet sending interval.
97 *
98 * Generate Traffic
99 */
100static void
103 Ptr<Node> n,
104 uint32_t pktCount,
105 Time pktInterval)
106{
107 if (pktCount > 0)
108 {
109 socket->Send(Create<Packet>(pktSize));
110 Simulator::Schedule(pktInterval,
112 socket,
113 pktSize,
114 n,
115 pktCount - 1,
116 pktInterval);
117 }
118 else
119 {
120 socket->Close();
121 }
122}
123
124/**
125 * Trace function for remaining energy at node.
126 *
127 * \param oldValue Old value
128 * \param remainingEnergy New value
129 */
130void
131RemainingEnergy(double oldValue, double remainingEnergy)
132{
133 NS_LOG_DEBUG(" Remaining energy Node 1 = " << remainingEnergy << " J");
134}
135
136int
137main(int argc, char* argv[])
138{
140 LogComponentEnable("GenericBatteryWifiRadioExample", LOG_LEVEL_DEBUG);
141
142 std::string phyMode("DsssRate1Mbps");
143 double rss = -80; // dBm
144 uint32_t packetSize = 200; // bytes
145 bool verbose = false;
146
147 // simulation parameters
148 uint32_t numPackets = 10000; // number of packets to send
149 double interval = 1; // seconds
150 double startTime = 0.0; // seconds
151 double distanceToRx = 100.0; // meters
152
153 CommandLine cmd(__FILE__);
154 cmd.AddValue("phyMode", "Wifi Phy mode", phyMode);
155 cmd.AddValue("rss", "Intended primary RSS (dBm)", rss);
156 cmd.AddValue("packetSize", "size of application packet sent (Bytes)", packetSize);
157 cmd.AddValue("numPackets", "Total number of packets to send", numPackets);
158 cmd.AddValue("startTime", "Simulation start time (seconds)", startTime);
159 cmd.AddValue("distanceToRx", "X-Axis distance between nodes (meters)", distanceToRx);
160 cmd.AddValue("verbose", "Turn on all device log components", verbose);
161 cmd.Parse(argc, argv);
162
163 Time interPacketInterval = Seconds(interval);
164
165 Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
166 StringValue("2200"));
167 Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("2200"));
168 Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
169
170 NodeContainer nodeContainer;
171 nodeContainer.Create(2);
172
174 if (verbose)
175 {
177 }
178 wifi.SetStandard(WIFI_STANDARD_80211b);
179
180 ////////////////////////
181 // Wifi PHY and MAC //
182 ////////////////////////
183
184 YansWifiPhyHelper wifiPhy;
185 YansWifiChannelHelper wifiChannel;
186 wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
187 wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
188
189 Ptr<YansWifiChannel> wifiChannelPtr = wifiChannel.Create();
190 wifiPhy.SetChannel(wifiChannelPtr);
191
192 WifiMacHelper wifiMac;
193 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
194 "DataMode",
195 StringValue(phyMode),
196 "ControlMode",
197 StringValue(phyMode));
198
199 wifiMac.SetType("ns3::AdhocWifiMac");
200 NetDeviceContainer devices = wifi.Install(wifiPhy, wifiMac, nodeContainer);
201
202 //////////////////
203 // Mobility //
204 //////////////////
205
207 Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator>();
208 positionAlloc->Add(Vector(0.0, 0.0, 0.0));
209 positionAlloc->Add(Vector(2 * distanceToRx, 0.0, 0.0));
210 mobility.SetPositionAllocator(positionAlloc);
211 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
212 mobility.Install(nodeContainer);
213
214 //////////////////////
215 // Energy Model //
216 //////////////////////
217
218 // Use a preset PANASONIC Li-Ion batteries arranged in a cell pack (2 series, 2 parallel)
219 GenericBatteryModelHelper batteryHelper;
220 EnergySourceContainer energySourceContainer =
221 batteryHelper.Install(nodeContainer, PANASONIC_CGR18650DA_LION);
222 batteryHelper.SetCellPack(energySourceContainer, 2, 2);
223
224 Ptr<GenericBatteryModel> battery0 =
225 DynamicCast<GenericBatteryModel>(energySourceContainer.Get(0));
226 Ptr<GenericBatteryModel> battery1 =
227 DynamicCast<GenericBatteryModel>(energySourceContainer.Get(1));
228
229 // Energy consumption quantities have been exaggerated for
230 // demonstration purposes, real consumption values are much smaller.
231 WifiRadioEnergyModelHelper radioEnergyHelper;
232 radioEnergyHelper.Set("TxCurrentA", DoubleValue(4.66));
233 radioEnergyHelper.Set("RxCurrentA", DoubleValue(0.466));
234 radioEnergyHelper.Set("IdleCurrentA", DoubleValue(0.466));
235 DeviceEnergyModelContainer deviceModels =
236 radioEnergyHelper.Install(devices, energySourceContainer);
237
238 /////////////////////
239 // Internet stack //
240 /////////////////////
241
243 internet.Install(nodeContainer);
244
246 ipv4.SetBase("10.1.1.0", "255.255.255.0");
247 Ipv4InterfaceContainer i = ipv4.Assign(devices);
248
249 TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
250 Ptr<Socket> recvSink = Socket::CreateSocket(nodeContainer.Get(1), tid); // node 1, receiver
252 recvSink->Bind(local);
253 recvSink->SetRecvCallback(MakeCallback(&ReceivePacket));
254
255 Ptr<Socket> source = Socket::CreateSocket(nodeContainer.Get(0), tid); // node 0, sender
257 source->SetAllowBroadcast(true);
258 source->Connect(remote);
259
260 /////////////////////
261 // Trace Sources //
262 /////////////////////
263
264 battery1->TraceConnectWithoutContext("RemainingEnergy", MakeCallback(&RemainingEnergy));
265
266 Ptr<DeviceEnergyModel> radioConsumptionModel =
267 battery1->FindDeviceEnergyModels("ns3::WifiRadioEnergyModel").Get(0);
268
269 /////////////////////
270 // Traffic Setup //
271 /////////////////////
272 Simulator::Schedule(Seconds(startTime),
274 source,
276 nodeContainer.Get(0),
277 numPackets,
278 interPacketInterval);
279
282
283 NS_LOG_DEBUG(" *Remaining Capacity * "
284 << "| Node 0: " << battery0->GetRemainingEnergy() << " J "
285 << "| Node 1: " << battery1->GetRemainingEnergy() << " J");
286 NS_LOG_DEBUG(" *SoC * "
287 << "| Node 0: " << battery0->GetStateOfCharge() << " % "
288 << "| Node 1: " << battery1->GetStateOfCharge() << " % ");
289
291
292 return 0;
293}
a polymophic address class
Definition: address.h:101
Parse command-line arguments.
Definition: command-line.h:232
Holds a vector of ns3::DeviceEnergyModel pointers.
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::EnergySource pointers.
Ptr< EnergySource > Get(uint32_t i) const
Get the i-th Ptr<EnergySource> stored in this container.
Creates and assign an assortment of BatteryModels to Nodes.
void SetCellPack(Ptr< 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< 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)
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:706
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:105
bool verbose
uint32_t pktSize
packet size used for the simulation (in bytes)
static const uint32_t packetSize
Packet size generated at the AP.