A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
basic-energy-model-test.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2010 Network Security Lab, University of Washington, Seattle.
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: He Wu <mdzz@u.washington.edu>
18 */
19
20#include "ns3/basic-energy-source-helper.h"
21#include "ns3/basic-energy-source.h"
22#include "ns3/config.h"
23#include "ns3/device-energy-model-container.h"
24#include "ns3/double.h"
25#include "ns3/energy-source-container.h"
26#include "ns3/log.h"
27#include "ns3/node.h"
28#include "ns3/simulator.h"
29#include "ns3/string.h"
30#include "ns3/wifi-radio-energy-model-helper.h"
31#include "ns3/wifi-radio-energy-model.h"
32#include "ns3/yans-wifi-helper.h"
33
34#include <cmath>
35
36using namespace ns3;
37using namespace ns3::energy;
38
39NS_LOG_COMPONENT_DEFINE("BasicEnergyModelTestSuite");
40
41/**
42 * Test case of update remaining energy for BasicEnergySource and
43 * WifiRadioEnergyModel.
44 */
46{
47 public:
49 virtual ~BasicEnergyUpdateTest();
50
51 /**
52 * Performs some tests involving state updates and the relative energy consumption
53 * \return true is some error happened.
54 */
55 bool DoRun();
56
57 private:
58 /**
59 * \param state Radio state to switch to.
60 * \return False if no error occurs.
61 *
62 * Runs simulation for a while, check if final state & remaining energy is
63 * correctly updated.
64 */
65 bool StateSwitchTest(WifiPhyState state);
66
67 private:
68 double m_timeS; //!< Time in seconds
69 double m_tolerance; //!< Tolerance for power estimation
70
71 ObjectFactory m_energySource; //!< Energy source factory
72 ObjectFactory m_deviceEnergyModel; //!< Device energy model factory
73};
74
76{
77 m_timeS = 15.5; // idle for 15 seconds before changing state
78 m_tolerance = 1.0e-5; //
79}
80
82{
83}
84
85bool
87{
88 // set types
89 m_energySource.SetTypeId("ns3::BasicEnergySource");
90 m_deviceEnergyModel.SetTypeId("ns3::WifiRadioEnergyModel");
91
92 // run state switch tests
93 if (StateSwitchTest(WifiPhyState::IDLE))
94 {
95 return true;
96 std::cerr << "Problem with state switch test (WifiPhy idle)." << std::endl;
97 }
98 if (StateSwitchTest(WifiPhyState::CCA_BUSY))
99 {
100 return true;
101 std::cerr << "Problem with state switch test (WifiPhy cca busy)." << std::endl;
102 }
103 if (StateSwitchTest(WifiPhyState::TX))
104 {
105 return true;
106 std::cerr << "Problem with state switch test (WifiPhy tx)." << std::endl;
107 }
108 if (StateSwitchTest(WifiPhyState::RX))
109 {
110 return true;
111 std::cerr << "Problem with state switch test (WifiPhy rx)." << std::endl;
112 }
113 if (StateSwitchTest(WifiPhyState::SWITCHING))
114 {
115 return true;
116 std::cerr << "Problem with state switch test (WifiPhy switching)." << std::endl;
117 }
118 if (StateSwitchTest(WifiPhyState::SLEEP))
119 {
120 return true;
121 std::cerr << "Problem with state switch test (WifiPhy sleep)." << std::endl;
122 }
123 return false;
124}
125
126bool
128{
129 // create node
130 Ptr<Node> node = CreateObject<Node>();
131
132 // create energy source
134 source->SetInitialEnergy(50);
135 // aggregate energy source to node
136 node->AggregateObject(source);
137 source->SetNode(node);
138
139 // create device energy model
141 // set energy source pointer
142 model->SetEnergySource(source);
143 // add device energy model to model list in energy source
144 source->AppendDeviceEnergyModel(model);
145
146 // retrieve device energy model from energy source
147 DeviceEnergyModelContainer models = source->FindDeviceEnergyModels("ns3::WifiRadioEnergyModel");
148 // check list
149 if (models.GetN() == 0)
150 {
151 std::cerr << "Model list is empty!." << std::endl;
152 return true;
153 }
154 // get pointer
155 Ptr<WifiRadioEnergyModel> devModel = DynamicCast<WifiRadioEnergyModel>(models.Get(0));
156 // check pointer
157 if (!devModel)
158 {
159 std::cerr << "NULL pointer to device model!." << std::endl;
160 return true;
161 }
162
163 /*
164 * The radio will stay IDLE for m_timeS seconds. Then it will switch into a
165 * different state.
166 */
167
168 // schedule change of state
171 devModel,
172 static_cast<int>(state));
173
174 // Calculate remaining energy at simulation stop time
176
177 double timeDelta = 0.000000001; // 1 nanosecond
178 // run simulation; stop just after last scheduled event
179 Simulator::Stop(Seconds(m_timeS * 2 + timeDelta));
181
182 // energy = current * voltage * time
183
184 // calculate idle power consumption
185 double estRemainingEnergy = source->GetInitialEnergy();
186 double voltage = source->GetSupplyVoltage();
187 estRemainingEnergy -= devModel->GetIdleCurrentA() * voltage * m_timeS;
188
189 // calculate new state power consumption
190 double current = 0.0;
191 switch (state)
192 {
193 case WifiPhyState::IDLE:
194 current = devModel->GetIdleCurrentA();
195 break;
196 case WifiPhyState::CCA_BUSY:
197 current = devModel->GetCcaBusyCurrentA();
198 break;
199 case WifiPhyState::TX:
200 current = devModel->GetTxCurrentA();
201 break;
202 case WifiPhyState::RX:
203 current = devModel->GetRxCurrentA();
204 break;
205 case WifiPhyState::SWITCHING:
206 current = devModel->GetSwitchingCurrentA();
207 break;
208 case WifiPhyState::SLEEP:
209 current = devModel->GetSleepCurrentA();
210 break;
211 case WifiPhyState::OFF:
212 current = 0;
213 break;
214 default:
215 NS_FATAL_ERROR("Undefined radio state: " << state);
216 break;
217 }
218 estRemainingEnergy -= current * voltage * m_timeS;
219 estRemainingEnergy = std::max(0.0, estRemainingEnergy);
220
221 // obtain remaining energy from source
222 double remainingEnergy = source->GetRemainingEnergy();
223 NS_LOG_DEBUG("Remaining energy is " << remainingEnergy);
224 NS_LOG_DEBUG("Estimated remaining energy is " << estRemainingEnergy);
225 NS_LOG_DEBUG("Difference is " << estRemainingEnergy - remainingEnergy);
226
227 // check remaining energy
228 if ((remainingEnergy > (estRemainingEnergy + m_tolerance)) ||
229 (remainingEnergy < (estRemainingEnergy - m_tolerance)))
230 {
231 std::cerr << "Incorrect remaining energy!" << std::endl;
232 return true;
233 }
234
235 // obtain radio state
236 WifiPhyState endState = devModel->GetCurrentState();
237 NS_LOG_DEBUG("Radio state is " << endState);
238 // check end state
239 if (endState != state)
240 {
241 std::cerr << "Incorrect end state!" << std::endl;
242 return true;
243 }
245
246 return false; // no error
247}
248
249// -------------------------------------------------------------------------- //
250
251/**
252 * Test case of energy depletion handling for BasicEnergySource and
253 * WifiRadioEnergyModel.
254 */
256{
257 public:
260
261 /**
262 * Performs some tests involving energy depletion
263 * \return true is some error happened.
264 */
265 bool DoRun();
266
267 private:
268 /**
269 * Callback invoked when energy is drained from source.
270 */
271 void DepletionHandler();
272
273 /**
274 * \param simTimeS Simulation time, in seconds.
275 * \param updateIntervalS Device model update interval, in seconds.
276 * \return False if all is good.
277 *
278 * Runs simulation with specified simulation time and update interval.
279 */
280 bool DepletionTestCase(double simTimeS, double updateIntervalS);
281
282 private:
283 int m_numOfNodes; //!< number of nodes in simulation
284 int m_callbackCount; //!< counter for # of callbacks invoked
285 double m_simTimeS; //!< maximum simulation time, in seconds
286 double m_timeStepS; //!< simulation time step size, in seconds
287 double m_updateIntervalS; //!< update interval of each device model
288};
289
291{
292 m_numOfNodes = 10;
293 m_callbackCount = 0;
294 m_simTimeS = 4.5;
295 m_timeStepS = 0.5;
296 m_updateIntervalS = 1.5;
297}
298
300{
301}
302
303bool
305{
306 /*
307 * Run simulation with different simulation time and update interval.
308 */
309 bool ret = false;
310
311 for (double simTimeS = 0.0; simTimeS <= m_simTimeS; simTimeS += m_timeStepS)
312 {
313 for (double updateIntervalS = 0.5; updateIntervalS <= m_updateIntervalS;
314 updateIntervalS += m_timeStepS)
315 {
316 if (DepletionTestCase(simTimeS, updateIntervalS))
317 {
318 ret = true;
319 std::cerr << "Depletion test case problem." << std::endl;
320 }
321 // reset callback count
322 m_callbackCount = 0;
323 }
324 }
325 return ret;
326}
327
328void
330{
332}
333
334bool
335BasicEnergyDepletionTest::DepletionTestCase(double simTimeS, double updateIntervalS)
336{
337 // create node
340
341 std::string phyMode("DsssRate1Mbps");
342
343 // disable fragmentation for frames below 2200 bytes
344 Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
345 StringValue("2200"));
346 // turn off RTS/CTS for frames below 2200 bytes
347 Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("2200"));
348 // Fix non-unicast data rate to be the same as that of unicast
349 Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
350
351 // install YansWifiPhy
352 WifiHelper wifi;
353 wifi.SetStandard(WIFI_STANDARD_80211b);
354
355 YansWifiPhyHelper wifiPhy;
356 /*
357 * This is one parameter that matters when using FixedRssLossModel, set it to
358 * zero; otherwise, gain will be added.
359 */
360 wifiPhy.Set("RxGain", DoubleValue(0));
361 // ns-3 supports RadioTap and Prism tracing extensions for 802.11b
363
364 YansWifiChannelHelper wifiChannel;
365 wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
366 wifiPhy.SetChannel(wifiChannel.Create());
367
368 // Add a MAC and disable rate control
369 WifiMacHelper wifiMac;
370 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
371 "DataMode",
372 StringValue(phyMode),
373 "ControlMode",
374 StringValue(phyMode));
375 // Set it to ad-hoc mode
376 wifiMac.SetType("ns3::AdhocWifiMac");
377 NetDeviceContainer devices = wifi.Install(wifiPhy, wifiMac, c);
378
379 /*
380 * Create and install energy source and a single basic radio energy model on
381 * the node using helpers.
382 */
383 // source helper
384 BasicEnergySourceHelper basicSourceHelper;
385 // set energy to 0 so that we deplete energy at the beginning of simulation
386 basicSourceHelper.Set("BasicEnergySourceInitialEnergyJ", DoubleValue(0.0));
387 // set update interval
388 basicSourceHelper.Set("PeriodicEnergyUpdateInterval", TimeValue(Seconds(updateIntervalS)));
389 // install source
390 EnergySourceContainer sources = basicSourceHelper.Install(c);
391
392 // device energy model helper
393 WifiRadioEnergyModelHelper radioEnergyHelper;
394 // set energy depletion callback
397 radioEnergyHelper.SetDepletionCallback(callback);
398 // install on node
399 DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install(devices, sources);
400
401 // run simulation
402 Simulator::Stop(Seconds(simTimeS));
405
406 NS_LOG_DEBUG("Simulation time = " << simTimeS << "s");
407 NS_LOG_DEBUG("Update interval = " << updateIntervalS << "s");
408 NS_LOG_DEBUG("Expected callback count is " << m_numOfNodes);
409 NS_LOG_DEBUG("Actual callback count is " << m_callbackCount);
410
411 // check result, call back should only be invoked once
413 {
414 std::cerr << "Not all callbacks are invoked!" << std::endl;
415 return true;
416 }
417
418 return false;
419}
420
421// -------------------------------------------------------------------------- //
422
423int
424main(int argc, char** argv)
425{
426 BasicEnergyUpdateTest testEnergyUpdate;
427 if (testEnergyUpdate.DoRun())
428 {
429 return 1;
430 }
431
432 BasicEnergyDepletionTest testEnergyDepletion;
433 if (testEnergyDepletion.DoRun())
434 {
435 return 1;
436 }
437
438 return 0;
439}
Test case of energy depletion handling for BasicEnergySource and WifiRadioEnergyModel.
double m_updateIntervalS
update interval of each device model
double m_simTimeS
maximum simulation time, in seconds
double m_timeStepS
simulation time step size, in seconds
int m_numOfNodes
number of nodes in simulation
bool DepletionTestCase(double simTimeS, double updateIntervalS)
bool DoRun()
Performs some tests involving energy depletion.
void DepletionHandler()
Callback invoked when energy is drained from source.
int m_callbackCount
counter for # of callbacks invoked
Test case of update remaining energy for BasicEnergySource and WifiRadioEnergyModel.
double m_timeS
Time in seconds.
ObjectFactory m_energySource
Energy source factory.
ObjectFactory m_deviceEnergyModel
Device energy model factory.
bool StateSwitchTest(WifiPhyState state)
bool DoRun()
Performs some tests involving state updates and the relative energy consumption.
double m_tolerance
Tolerance for power estimation.
Creates a BasicEnergySource object.
void Set(std::string name, const AttributeValue &v) override
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
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.
Instantiate subclasses of ns3::Object.
Ptr< Object > Create() const
Create an Object instance of the configured TypeId.
void SetTypeId(TypeId tid)
Set the TypeId of the Objects to be created by this factory.
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
Hold variables of type string.
Definition: string.h:56
helps to create WifiNetDevice objects
Definition: wifi-helper.h:324
create MAC layers for a ns3::WifiNetDevice.
void SetType(std::string type, Args &&... args)
void SetPcapDataLinkType(SupportedPcapDataLinkTypes dlt)
Set the data link type of PCAP traces to be used.
Definition: wifi-helper.cc:543
void Set(std::string name, const AttributeValue &v)
Definition: wifi-helper.cc:163
@ DLT_IEEE802_11_RADIO
Include Radiotap link layer information.
Definition: wifi-helper.h:178
Assign WifiRadioEnergyModel to wifi devices.
void SetDepletionCallback(WifiRadioEnergyModel::WifiRadioEnergyDepletionCallback callback)
A WiFi radio energy model.
void ChangeState(int newState) override
Changes state of the WifiRadioEnergyMode.
manage and create wifi channel objects for the YANS model.
void SetPropagationDelay(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)
BasicEnergySource decreases/increases remaining energy stored in itself in linearly.
void UpdateEnergySource() override
Implements UpdateEnergySource.
Holds a vector of ns3::DeviceEnergyModel pointers.
Ptr< DeviceEnergyModel > Get(uint32_t i) const
Get the i-th Ptr<DeviceEnergyModel> stored in this container.
uint32_t GetN() const
Get the number of Ptr<DeviceEnergyModel> stored in this container.
Holds a vector of ns3::EnergySource pointers.
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:894
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
Definition: fatal-error.h:179
#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
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