A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
wifi-sleep.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2009 The Boeing Company
3 * 2014 Universita' degli Studi di Napoli "Federico II"
4 *
5 * SPDX-License-Identifier: GPL-2.0-only
6 *
7 */
8
9// This script configures two nodes on an 802.11b physical layer, with
10// 802.11b NICs in adhoc mode. One of the nodes generates on-off traffic
11// destined to the other node.
12//
13// The purpose is to test the energy depletion on the nodes and the
14// activation of the callback that puts a node in the sleep state when
15// its energy is depleted. Furthermore, this script can be used to test
16// the available policies for updating the transmit current based on
17// the nominal tx power used to transmit each frame.
18//
19// There are a number of command-line options available to control
20// the default behavior. The list of available command-line options
21// can be listed with the following command:
22// ./ns3 run "wifi-sleep --help"
23//
24// Note that all ns-3 attributes (not just the ones exposed in the below
25// script) can be changed at command line; see the documentation.
26//
27// This script can also be helpful to put the Wifi layer into verbose
28// logging mode; this command will turn on all wifi logging:
29//
30// ./ns3 run "wifi-sleep --verbose=1"
31//
32// When you are done, you will notice four trace files in your directory:
33// two for the remaining energy on each node and two for the state transitions
34// of each node.
35
36#include "ns3/basic-energy-source-helper.h"
37#include "ns3/command-line.h"
38#include "ns3/config.h"
39#include "ns3/internet-stack-helper.h"
40#include "ns3/ipv4-address-helper.h"
41#include "ns3/log.h"
42#include "ns3/mobility-helper.h"
43#include "ns3/mobility-model.h"
44#include "ns3/on-off-helper.h"
45#include "ns3/packet-sink-helper.h"
46#include "ns3/string.h"
47#include "ns3/wifi-net-device.h"
48#include "ns3/wifi-radio-energy-model-helper.h"
49#include "ns3/wifi-utils.h"
50#include "ns3/yans-wifi-channel.h"
51#include "ns3/yans-wifi-helper.h"
52
53using namespace ns3;
54using namespace ns3::energy;
55
56NS_LOG_COMPONENT_DEFINE("WifiSleep");
57
58/**
59 * Remaining energy trace sink
60 *
61 * \tparam node The node ID this trace belongs to.
62 * \param oldValue Old value.
63 * \param newValue New value.
64 */
65template <int node>
66void
67RemainingEnergyTrace(double oldValue, double newValue)
68{
69 std::stringstream ss;
70 ss << "energy_" << node << ".log";
71
72 static std::fstream f(ss.str(), std::ios::out);
73
74 f << Simulator::Now().GetSeconds() << " remaining energy=" << newValue << std::endl;
75}
76
77/**
78 * PHY state trace sink
79 *
80 * \tparam node The node ID this trace belongs to.
81 * \param context The context
82 * \param start Start time for the current state
83 * \param duration Duratio of the current state
84 * \param state State
85 */
86template <int node>
87void
88PhyStateTrace(std::string context, Time start, Time duration, WifiPhyState state)
89{
90 std::stringstream ss;
91 ss << "state_" << node << ".log";
92
93 static std::fstream f(ss.str(), std::ios::out);
94
95 f << Simulator::Now().GetSeconds() << " state=" << state << " start=" << start
96 << " duration=" << duration << std::endl;
97}
98
99int
100main(int argc, char* argv[])
101{
102 DataRate dataRate{"1Mb/s"};
103 uint32_t packetSize{1000}; // bytes
104 Time duration{"10s"};
105 joule_u initialEnergy{7.5};
106 volt_u voltage{3.0};
107 dBm_u txPowerStart{0.0};
108 dBm_u txPowerEnd{15.0};
109 uint32_t nTxPowerLevels{16};
110 uint32_t txPowerLevel{0};
111 ampere_u idleCurrent{0.273};
112 ampere_u txCurrent{0.380};
113 bool verbose{false};
114
115 CommandLine cmd(__FILE__);
116 cmd.AddValue("dataRate", "Data rate", dataRate);
117 cmd.AddValue("packetSize", "size of application packet sent", packetSize);
118 cmd.AddValue("duration", "duration of the experiment", duration);
119 cmd.AddValue("initialEnergy", "Initial Energy (Joule) of each node", initialEnergy);
120 cmd.AddValue("voltage", "Supply voltage (Joule)", voltage);
121 cmd.AddValue("txPowerStart", "Minimum available transmission level (dbm)", txPowerStart);
122 cmd.AddValue("txPowerEnd", "Maximum available transmission level (dbm)", txPowerEnd);
123 cmd.AddValue("nTxPowerLevels",
124 "Number of transmission power levels available between txPowerStart and "
125 "txPowerEnd included",
126 nTxPowerLevels);
127 cmd.AddValue("txPowerLevel", "Transmission power level", txPowerLevel);
128 cmd.AddValue("idleCurrent", "The radio Idle current in Ampere", idleCurrent);
129 cmd.AddValue("txCurrent", "The radio Tx current in Ampere", txCurrent);
130 cmd.AddValue("verbose", "turn on all WifiNetDevice log components", verbose);
131 cmd.Parse(argc, argv);
132
134 c.Create(2);
135
136 // The below set of helpers will help us to put together the wifi NICs we want
138 if (verbose)
139 {
140 WifiHelper::EnableLogComponents(); // Turn on all Wifi logging
141 }
142 wifi.SetStandard(WIFI_STANDARD_80211b);
143
144 YansWifiPhyHelper wifiPhy;
145 wifiPhy.Set("TxPowerStart", DoubleValue(txPowerStart));
146 wifiPhy.Set("TxPowerEnd", DoubleValue(txPowerEnd));
147 wifiPhy.Set("TxPowerLevels", UintegerValue(nTxPowerLevels));
148
150 wifiPhy.SetChannel(wifiChannel.Create());
151
152 // Add a mac and set the selected tx power level
153 WifiMacHelper wifiMac;
154 wifi.SetRemoteStationManager("ns3::ArfWifiManager",
155 "DefaultTxPowerLevel",
156 UintegerValue(txPowerLevel));
157 // Set it to adhoc mode
158 wifiMac.SetType("ns3::AdhocWifiMac");
159 NetDeviceContainer devices = wifi.Install(wifiPhy, wifiMac, c);
160
163 positionAlloc->Add(Vector(0.0, 0.0, 0.0));
164 positionAlloc->Add(Vector(10.0, 0.0, 0.0));
165 mobility.SetPositionAllocator(positionAlloc);
166 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
167 mobility.Install(c);
168
170 internet.Install(c);
171
173 NS_LOG_INFO("Assign IP Addresses.");
174 ipv4.SetBase("10.1.1.0", "255.255.255.0");
175 Ipv4InterfaceContainer i = ipv4.Assign(devices);
176
178
179 std::string transportProto = std::string("ns3::UdpSocketFactory");
180 OnOffHelper onOff(transportProto, InetSocketAddress(Ipv4Address("10.1.1.2"), 9000));
181
182 onOff.SetAttribute("DataRate", DataRateValue(DataRate(dataRate)));
183 onOff.SetAttribute("PacketSize", UintegerValue(packetSize));
184 onOff.SetAttribute("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0.001]"));
185
186 apps = onOff.Install(c.Get(0));
187
188 apps.Start(Seconds(0.01));
189 apps.Stop(duration);
190
191 // Create a packet sink to receive these packets
193 apps = sink.Install(c.Get(1));
194 apps.Start(Seconds(0.01));
195 apps.Stop(duration);
196
197 // Energy sources
198 EnergySourceContainer eSources;
199 BasicEnergySourceHelper basicSourceHelper;
200 WifiRadioEnergyModelHelper radioEnergyHelper;
201
202 basicSourceHelper.Set("BasicEnergySourceInitialEnergyJ", DoubleValue(initialEnergy));
203 basicSourceHelper.Set("BasicEnergySupplyVoltageV", DoubleValue(voltage));
204
205 radioEnergyHelper.Set("IdleCurrentA", DoubleValue(idleCurrent));
206 radioEnergyHelper.Set("TxCurrentA", DoubleValue(txCurrent));
207
208 // compute the efficiency of the power amplifier (eta) assuming that the provided value for tx
209 // current corresponds to the minimum tx power level
210 double eta = DbmToW(txPowerStart) / ((txCurrent - idleCurrent) * voltage);
211
212 radioEnergyHelper.SetTxCurrentModel("ns3::LinearWifiTxCurrentModel",
213 "Voltage",
214 DoubleValue(voltage),
215 "IdleCurrent",
216 DoubleValue(idleCurrent),
217 "Eta",
218 DoubleValue(eta));
219
220 // install an energy source on each node
221 for (auto n = c.Begin(); n != c.End(); n++)
222 {
223 eSources.Add(basicSourceHelper.Install(*n));
224
226
227 for (uint32_t i = 0; i < (*n)->GetNDevices(); ++i)
228 {
229 wnd = (*n)->GetDevice(i)->GetObject<WifiNetDevice>();
230 // if it is a WifiNetDevice
231 if (wnd)
232 {
233 // this device draws power from the last created energy source
234 radioEnergyHelper.Install(wnd, eSources.Get(eSources.GetN() - 1));
235 }
236 }
237 }
238
239 // Tracing
240 eSources.Get(0)->TraceConnectWithoutContext("RemainingEnergy",
242 eSources.Get(1)->TraceConnectWithoutContext("RemainingEnergy",
244
245 Config::Connect("/NodeList/0/DeviceList/*/Phy/State/State", MakeCallback(&PhyStateTrace<0>));
246 Config::Connect("/NodeList/1/DeviceList/*/Phy/State/State", MakeCallback(&PhyStateTrace<1>));
247
248 Simulator::Stop(duration + Seconds(1.0));
249
252
253 return 0;
254}
holds a vector of ns3::Application pointers.
void Start(Time start) const
Start all of the Applications in this container at the start time given as a parameter.
void Stop(Time stop) const
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter.
Creates a BasicEnergySource object.
void Set(std::string name, const AttributeValue &v) override
Parse command-line arguments.
Class for representing data rates.
Definition data-rate.h:78
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::EnergySourceContainer Install(Ptr< Node > node) const
an Inet address class
aggregate IP/TCP/UDP functionality to existing Nodes.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
Ipv4 addresses are stored in host order in this class.
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.
Iterator End() const
Get an iterator which indicates past-the-last Node in the container.
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
Iterator Begin() const
Get an iterator which refers to the first Node in the container.
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes.
Smart pointer class similar to boost::intrusive_ptr.
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
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
Hold an unsigned integer type.
Definition uinteger.h:34
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)
Hold together all Wifi-related objects.
void Set(std::string name, const AttributeValue &v)
Assign WifiRadioEnergyModel to wifi devices.
void Set(std::string name, const AttributeValue &v) override
void SetTxCurrentModel(std::string name, Ts &&... args)
manage and create wifi channel objects for the YANS model.
static YansWifiChannelHelper Default()
Create a channel helper in a default working state.
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::EnergySource pointers.
uint32_t GetN() const
Get the number of Ptr<EnergySource> stored in this container.
void Add(EnergySourceContainer container)
Ptr< EnergySource > Get(uint32_t i) const
Get the i-th Ptr<EnergySource> stored in this container.
void Connect(std::string path, const CallbackBase &cb)
Definition config.cc:967
#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
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.
WifiPhyState
The state of the PHY layer.
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
Watt_u DbmToW(dBm_u val)
Convert from dBm to Watts.
Definition wifi-utils.cc:31
wifi
Definition third.py:84
mobility
Definition third.py:92
bool verbose
static const uint32_t packetSize
Packet size generated at the AP.
void RemainingEnergyTrace(double oldValue, double newValue)
Remaining energy trace sink.
Definition wifi-sleep.cc:67
void PhyStateTrace(std::string context, Time start, Time duration, WifiPhyState state)
PHY state trace sink.
Definition wifi-sleep.cc:88
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition wifi-tcp.cc:44