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 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation;
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
19
20// This script configures two nodes on an 802.11b physical layer, with
21// 802.11b NICs in adhoc mode. One of the nodes generates on-off traffic
22// destined to the other node.
23//
24// The purpose is to test the energy depletion on the nodes and the
25// activation of the callback that puts a node in the sleep state when
26// its energy is depleted. Furthermore, this script can be used to test
27// the available policies for updating the transmit current based on
28// the nominal tx power used to transmit each frame.
29//
30// There are a number of command-line options available to control
31// the default behavior. The list of available command-line options
32// can be listed with the following command:
33// ./ns3 run "wifi-sleep --help"
34//
35// Note that all ns-3 attributes (not just the ones exposed in the below
36// script) can be changed at command line; see the documentation.
37//
38// This script can also be helpful to put the Wifi layer into verbose
39// logging mode; this command will turn on all wifi logging:
40//
41// ./ns3 run "wifi-sleep --verbose=1"
42//
43// When you are done, you will notice four trace files in your directory:
44// two for the remaining energy on each node and two for the state transitions
45// of each node.
46
47#include "ns3/basic-energy-source-helper.h"
48#include "ns3/command-line.h"
49#include "ns3/config.h"
50#include "ns3/internet-stack-helper.h"
51#include "ns3/ipv4-address-helper.h"
52#include "ns3/log.h"
53#include "ns3/mobility-helper.h"
54#include "ns3/mobility-model.h"
55#include "ns3/on-off-helper.h"
56#include "ns3/packet-sink-helper.h"
57#include "ns3/string.h"
58#include "ns3/wifi-net-device.h"
59#include "ns3/wifi-radio-energy-model-helper.h"
60#include "ns3/wifi-utils.h"
61#include "ns3/yans-wifi-channel.h"
62#include "ns3/yans-wifi-helper.h"
63
64using namespace ns3;
65using namespace ns3::energy;
66
67NS_LOG_COMPONENT_DEFINE("WifiSleep");
68
69/**
70 * Remaining energy trace sink
71 *
72 * \tparam node The node ID this trace belongs to.
73 * \param oldValue Old value.
74 * \param newValue New value.
75 */
76template <int node>
77void
78RemainingEnergyTrace(double oldValue, double newValue)
79{
80 std::stringstream ss;
81 ss << "energy_" << node << ".log";
82
83 static std::fstream f(ss.str(), std::ios::out);
84
85 f << Simulator::Now().GetSeconds() << " remaining energy=" << newValue << std::endl;
86}
87
88/**
89 * PHY state trace sink
90 *
91 * \tparam node The node ID this trace belongs to.
92 * \param context The context
93 * \param start Start time for the current state
94 * \param duration Duratio of the current state
95 * \param state State
96 */
97template <int node>
98void
99PhyStateTrace(std::string context, Time start, Time duration, WifiPhyState state)
100{
101 std::stringstream ss;
102 ss << "state_" << node << ".log";
103
104 static std::fstream f(ss.str(), std::ios::out);
105
106 f << Simulator::Now().GetSeconds() << " state=" << state << " start=" << start
107 << " duration=" << duration << std::endl;
108}
109
110int
111main(int argc, char* argv[])
112{
113 DataRate dataRate{"1Mb/s"};
114 uint32_t packetSize{1000}; // bytes
115 Time duration{"10s"};
116 double initialEnergy{7.5}; // joule
117 double voltage{3.0}; // volts
118 double txPowerStart{0.0}; // dbm
119 double txPowerEnd{15.0}; // dbm
120 uint32_t nTxPowerLevels{16};
121 uint32_t txPowerLevel{0};
122 double idleCurrent{0.273}; // Ampere
123 double txCurrent{0.380}; // Ampere
124 bool verbose{false};
125
126 CommandLine cmd(__FILE__);
127 cmd.AddValue("dataRate", "Data rate", dataRate);
128 cmd.AddValue("packetSize", "size of application packet sent", packetSize);
129 cmd.AddValue("duration", "duration of the experiment", duration);
130 cmd.AddValue("initialEnergy", "Initial Energy (Joule) of each node", initialEnergy);
131 cmd.AddValue("voltage", "Supply voltage (Joule)", voltage);
132 cmd.AddValue("txPowerStart", "Minimum available transmission level (dbm)", txPowerStart);
133 cmd.AddValue("txPowerEnd", "Maximum available transmission level (dbm)", txPowerEnd);
134 cmd.AddValue("nTxPowerLevels",
135 "Number of transmission power levels available between txPowerStart and "
136 "txPowerEnd included",
137 nTxPowerLevels);
138 cmd.AddValue("txPowerLevel", "Transmission power level", txPowerLevel);
139 cmd.AddValue("idleCurrent", "The radio Idle current in Ampere", idleCurrent);
140 cmd.AddValue("txCurrent", "The radio Tx current in Ampere", txCurrent);
141 cmd.AddValue("verbose", "turn on all WifiNetDevice log components", verbose);
142 cmd.Parse(argc, argv);
143
145 c.Create(2);
146
147 // The below set of helpers will help us to put together the wifi NICs we want
149 if (verbose)
150 {
151 WifiHelper::EnableLogComponents(); // Turn on all Wifi logging
152 }
153 wifi.SetStandard(WIFI_STANDARD_80211b);
154
155 YansWifiPhyHelper wifiPhy;
156 wifiPhy.Set("TxPowerStart", DoubleValue(txPowerStart));
157 wifiPhy.Set("TxPowerEnd", DoubleValue(txPowerEnd));
158 wifiPhy.Set("TxPowerLevels", UintegerValue(nTxPowerLevels));
159
161 wifiPhy.SetChannel(wifiChannel.Create());
162
163 // Add a mac and set the selected tx power level
164 WifiMacHelper wifiMac;
165 wifi.SetRemoteStationManager("ns3::ArfWifiManager",
166 "DefaultTxPowerLevel",
167 UintegerValue(txPowerLevel));
168 // Set it to adhoc mode
169 wifiMac.SetType("ns3::AdhocWifiMac");
170 NetDeviceContainer devices = wifi.Install(wifiPhy, wifiMac, c);
171
173 Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator>();
174 positionAlloc->Add(Vector(0.0, 0.0, 0.0));
175 positionAlloc->Add(Vector(10.0, 0.0, 0.0));
176 mobility.SetPositionAllocator(positionAlloc);
177 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
178 mobility.Install(c);
179
181 internet.Install(c);
182
184 NS_LOG_INFO("Assign IP Addresses.");
185 ipv4.SetBase("10.1.1.0", "255.255.255.0");
186 Ipv4InterfaceContainer i = ipv4.Assign(devices);
187
189
190 std::string transportProto = std::string("ns3::UdpSocketFactory");
191 OnOffHelper onOff(transportProto, InetSocketAddress(Ipv4Address("10.1.1.2"), 9000));
192
193 onOff.SetAttribute("DataRate", DataRateValue(DataRate(dataRate)));
194 onOff.SetAttribute("PacketSize", UintegerValue(packetSize));
195 onOff.SetAttribute("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0.001]"));
196
197 apps = onOff.Install(c.Get(0));
198
199 apps.Start(Seconds(0.01));
200 apps.Stop(duration);
201
202 // Create a packet sink to receive these packets
204 apps = sink.Install(c.Get(1));
205 apps.Start(Seconds(0.01));
206 apps.Stop(duration);
207
208 // Energy sources
209 EnergySourceContainer eSources;
210 BasicEnergySourceHelper basicSourceHelper;
211 WifiRadioEnergyModelHelper radioEnergyHelper;
212
213 basicSourceHelper.Set("BasicEnergySourceInitialEnergyJ", DoubleValue(initialEnergy));
214 basicSourceHelper.Set("BasicEnergySupplyVoltageV", DoubleValue(voltage));
215
216 radioEnergyHelper.Set("IdleCurrentA", DoubleValue(idleCurrent));
217 radioEnergyHelper.Set("TxCurrentA", DoubleValue(txCurrent));
218
219 // compute the efficiency of the power amplifier (eta) assuming that the provided value for tx
220 // current corresponds to the minimum tx power level
221 double eta = DbmToW(txPowerStart) / ((txCurrent - idleCurrent) * voltage);
222
223 radioEnergyHelper.SetTxCurrentModel("ns3::LinearWifiTxCurrentModel",
224 "Voltage",
225 DoubleValue(voltage),
226 "IdleCurrent",
227 DoubleValue(idleCurrent),
228 "Eta",
229 DoubleValue(eta));
230
231 // install an energy source on each node
232 for (auto n = c.Begin(); n != c.End(); n++)
233 {
234 eSources.Add(basicSourceHelper.Install(*n));
235
237
238 for (uint32_t i = 0; i < (*n)->GetNDevices(); ++i)
239 {
240 wnd = (*n)->GetDevice(i)->GetObject<WifiNetDevice>();
241 // if it is a WifiNetDevice
242 if (wnd)
243 {
244 // this device draws power from the last created energy source
245 radioEnergyHelper.Install(wnd, eSources.Get(eSources.GetN() - 1));
246 }
247 }
248 }
249
250 // Tracing
251 eSources.Get(0)->TraceConnectWithoutContext("RemainingEnergy",
252 MakeCallback(&RemainingEnergyTrace<0>));
253 eSources.Get(1)->TraceConnectWithoutContext("RemainingEnergy",
254 MakeCallback(&RemainingEnergyTrace<1>));
255
256 Config::Connect("/NodeList/0/DeviceList/*/Phy/State/State", MakeCallback(&PhyStateTrace<0>));
257 Config::Connect("/NodeList/1/DeviceList/*/Phy/State/State", MakeCallback(&PhyStateTrace<1>));
258
259 Simulator::Stop(duration + Seconds(1.0));
260
263
264 return 0;
265}
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.
Definition: command-line.h:232
Class for representing data rates.
Definition: data-rate.h:89
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
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.
Definition: ipv4-address.h:42
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.
Definition: on-off-helper.h:37
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes.
Smart pointer class similar to boost::intrusive_ptr.
Definition: ptr.h:77
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition: simulator.cc:142
static Time Now()
Return the current simulation virtual time.
Definition: simulator.cc:208
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
Hold variables of type string.
Definition: string.h:56
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:105
double GetSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
Definition: nstime.h:403
Hold an unsigned integer type.
Definition: uinteger.h:45
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)
Hold together all Wifi-related objects.
void Set(std::string name, const AttributeValue &v)
Definition: wifi-helper.cc:163
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:978
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:202
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:275
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.
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:700
double DbmToW(double dBm)
Convert from dBm to Watts.
Definition: wifi-utils.cc:42
ns cmd
Definition: second.py:40
ns wifi
Definition: third.py:95
ns mobility
Definition: third.py:103
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:78
void PhyStateTrace(std::string context, Time start, Time duration, WifiPhyState state)
PHY state trace sink.
Definition: wifi-sleep.cc:99
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition: wifi-tcp.cc:55