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