A Discrete-Event Network Simulator
API
basic-energy-model-test.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2010 Network Security Lab, University of Washington, Seattle.
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  * Author: He Wu <mdzz@u.washington.edu>
19  */
20 
21 #include "ns3/basic-energy-source.h"
22 #include "ns3/wifi-radio-energy-model.h"
23 #include "ns3/basic-energy-source-helper.h"
24 #include "ns3/wifi-radio-energy-model-helper.h"
25 #include "ns3/energy-source-container.h"
26 #include "ns3/device-energy-model-container.h"
27 #include "ns3/log.h"
28 #include "ns3/test.h"
29 #include "ns3/node.h"
30 #include "ns3/simulator.h"
31 #include "ns3/double.h"
32 #include "ns3/config.h"
33 #include "ns3/string.h"
34 #include "ns3/yans-wifi-helper.h"
35 #include "ns3/nqos-wifi-mac-helper.h"
36 #include <cmath>
37 
38 using namespace ns3;
39 
40 NS_LOG_COMPONENT_DEFINE ("BasicEnergyModelTestSuite");
41 
47 {
48 public:
50  virtual ~BasicEnergyUpdateTest ();
51 
52 private:
53  void DoRun (void);
54 
62  bool StateSwitchTest (WifiPhy::State state);
63 
64 private:
65  double m_timeS; // in seconds
66  double m_tolerance; // tolerance for power estimation
67 
70 };
71 
73  : TestCase ("Basic energy model update remaining energy test case")
74 {
75  m_timeS = 15.5; // idle for 15 seconds before changing state
76  m_tolerance = 1.0e-13; //
77 }
78 
80 {
81 }
82 
83 void
85 {
86  // set types
87  m_energySource.SetTypeId ("ns3::BasicEnergySource");
88  m_deviceEnergyModel.SetTypeId ("ns3::WifiRadioEnergyModel");
89 
90  // run state switch tests
91  NS_TEST_ASSERT_MSG_EQ (StateSwitchTest (WifiPhy::IDLE), false, "Problem with state switch test (WifiPhy idle).");
92  NS_TEST_ASSERT_MSG_EQ (StateSwitchTest (WifiPhy::CCA_BUSY), false, "Problem with state switch test (WifiPhy cca busy).");
93  NS_TEST_ASSERT_MSG_EQ (StateSwitchTest (WifiPhy::TX), false, "Problem with state switch test (WifiPhy tx).");
94  NS_TEST_ASSERT_MSG_EQ (StateSwitchTest (WifiPhy::RX), false, "Problem with state switch test (WifiPhy rx).");
95  NS_TEST_ASSERT_MSG_EQ (StateSwitchTest (WifiPhy::SWITCHING), false, "Problem with state switch test (WifiPhy switching).");
96  NS_TEST_ASSERT_MSG_EQ (StateSwitchTest (WifiPhy::SLEEP), false, "Problem with state switch test (WifiPhy sleep).");
97 }
98 
99 bool
101 {
102  // create node
103  Ptr<Node> node = CreateObject<Node> ();
104 
105  // create energy source
107  // aggregate energy source to node
108  node->AggregateObject (source);
109 
110  // create device energy model
113  // set energy source pointer
114  model->SetEnergySource (source);
115  // add device energy model to model list in energy source
116  source->AppendDeviceEnergyModel (model);
117 
118  // retrieve device energy model from energy source
120  source->FindDeviceEnergyModels ("ns3::WifiRadioEnergyModel");
121  // check list
122  NS_TEST_ASSERT_MSG_EQ_RETURNS_BOOL (false, (models.GetN () == 0), "Model list is empty!");
123  // get pointer
124  Ptr<WifiRadioEnergyModel> devModel =
125  DynamicCast<WifiRadioEnergyModel> (models.Get (0));
126  // check pointer
127  NS_TEST_ASSERT_MSG_NE_RETURNS_BOOL (0, devModel, "NULL pointer to device model!");
128 
129  /*
130  * The radio will stay IDLE for m_timeS seconds. Then it will switch into a
131  * different state.
132  */
133 
134  // schedule change of state
135  Simulator::Schedule (Seconds (m_timeS),
136  &WifiRadioEnergyModel::ChangeState, devModel, state);
137 
138  // Calculate remaining energy at simulation stop time
139  Simulator::Schedule (Seconds (m_timeS * 2),
140  &BasicEnergySource::UpdateEnergySource, source);
141 
142  double timeDelta = 0.000000001; // 1 nanosecond
143  // run simulation; stop just after last scheduled event
144  Simulator::Stop (Seconds (m_timeS * 2 + timeDelta));
145  Simulator::Run ();
146 
147  // energy = current * voltage * time
148 
149  // calculate idle power consumption
150  double estRemainingEnergy = source->GetInitialEnergy ();
151  double voltage = source->GetSupplyVoltage ();
152  estRemainingEnergy -= devModel->GetIdleCurrentA () * voltage * m_timeS;
153 
154  /*
155  * Manually calculate the number of periodic updates performed by the source.
156  * This is to check if the periodic updates are performed correctly.
157  */
158  double actualTime = m_timeS;
159  actualTime /= source->GetEnergyUpdateInterval ().GetSeconds ();
160  actualTime = floor (actualTime); // rounding for update interval
161  actualTime *= source->GetEnergyUpdateInterval ().GetSeconds ();
162 
163  // calculate new state power consumption
164  double current = 0.0;
165  switch (state)
166  {
167  case WifiPhy::IDLE:
168  current = devModel->GetIdleCurrentA ();
169  break;
170  case WifiPhy::CCA_BUSY:
171  current = devModel->GetCcaBusyCurrentA ();
172  break;
173  case WifiPhy::TX:
174  current = devModel->GetTxCurrentA ();
175  break;
176  case WifiPhy::RX:
177  current = devModel->GetRxCurrentA ();
178  break;
179  case WifiPhy::SWITCHING:
180  current = devModel->GetSwitchingCurrentA ();
181  break;
182  case WifiPhy::SLEEP:
183  current = devModel->GetSleepCurrentA ();
184  break;
185  default:
186  NS_FATAL_ERROR ("Undefined radio state: " << state);
187  break;
188  }
189  estRemainingEnergy -= current * voltage * m_timeS;
190 
191  // obtain remaining energy from source
192  double remainingEnergy = source->GetRemainingEnergy ();
193  NS_LOG_DEBUG ("Remaining energy is " << remainingEnergy);
194  NS_LOG_DEBUG ("Estimated remaining energy is " << estRemainingEnergy);
195  NS_LOG_DEBUG ("Difference is " << estRemainingEnergy - remainingEnergy);
196  // check remaining energy
197  NS_TEST_ASSERT_MSG_EQ_TOL_RETURNS_BOOL (remainingEnergy, estRemainingEnergy, m_tolerance,
198  "Incorrect remaining energy!");
199 
200  // obtain radio state
201  WifiPhy::State endState = devModel->GetCurrentState ();
202  NS_LOG_DEBUG ("Radio state is " << endState);
203  // check end state
204  NS_TEST_ASSERT_MSG_EQ_RETURNS_BOOL (endState, state, "Incorrect end state!");
205  Simulator::Destroy ();
206 
207  return false; // no error
208 }
209 
210 // -------------------------------------------------------------------------- //
211 
217 {
218 public:
220  virtual ~BasicEnergyDepletionTest ();
221 
222 private:
223  void DoRun (void);
224 
228  void DepletionHandler (void);
229 
237  bool DepletionTestCase (double simTimeS, double updateIntervalS);
238 
239 private:
240  int m_numOfNodes; // number of nodes in simulation
241  int m_callbackCount; // counter for # of callbacks invoked
242  double m_simTimeS; // maximum simulation time, in seconds
243  double m_timeStepS; // simulation time step size, in seconds
244  double m_updateIntervalS; // update interval of each device model
245 
246 };
247 
249  : TestCase ("Basic energy model energy depletion test case")
250 {
251  m_numOfNodes = 10;
252  m_callbackCount = 0;
253  m_simTimeS = 4.5;
254  m_timeStepS = 0.5;
255  m_updateIntervalS = 1.5;
256 }
257 
259 {
260 }
261 
262 void
264 {
265  /*
266  * Run simulation with different simulation time and update interval.
267  */
268  for (double simTimeS = 0.0; simTimeS <= m_simTimeS; simTimeS += m_timeStepS)
269  {
270  for (double updateIntervalS = 0.5; updateIntervalS <= m_updateIntervalS;
271  updateIntervalS += m_timeStepS)
272  {
273  NS_TEST_ASSERT_MSG_EQ (DepletionTestCase (simTimeS, updateIntervalS), false, "Depletion test case problem.");
274  // reset callback count
275  m_callbackCount = 0;
276  }
277  }
278 }
279 
280 void
282 {
283  m_callbackCount++;
284 }
285 
286 bool
288  double updateIntervalS)
289 {
290  // create node
291  NodeContainer c;
292  c.Create (m_numOfNodes);
293 
294  std::string phyMode ("DsssRate1Mbps");
295 
296  // disable fragmentation for frames below 2200 bytes
297  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold",
298  StringValue ("2200"));
299  // turn off RTS/CTS for frames below 2200 bytes
300  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold",
301  StringValue ("2200"));
302  // Fix non-unicast data rate to be the same as that of unicast
303  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",
304  StringValue (phyMode));
305 
306  // install YansWifiPhy
307  WifiHelper wifi;
309 
310  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
311  /*
312  * This is one parameter that matters when using FixedRssLossModel, set it to
313  * zero; otherwise, gain will be added.
314  */
315  wifiPhy.Set ("RxGain", DoubleValue (0));
316  // ns-3 supports RadioTap and Prism tracing extensions for 802.11b
317  wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO);
318 
319  YansWifiChannelHelper wifiChannel;
320  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
321  wifiPhy.SetChannel (wifiChannel.Create ());
322 
323  // Add a non-QoS upper MAC, and disable rate control
324  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
325  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
326  "DataMode", StringValue (phyMode),
327  "ControlMode", StringValue (phyMode));
328  // Set it to ad-hoc mode
329  wifiMac.SetType ("ns3::AdhocWifiMac");
330  NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, c);
331 
332  /*
333  * Create and install energy source and a single basic radio energy model on
334  * the node using helpers.
335  */
336  // source helper
337  BasicEnergySourceHelper basicSourceHelper;
338  // set energy to 0 so that we deplete energy at the beginning of simulation
339  basicSourceHelper.Set ("BasicEnergySourceInitialEnergyJ", DoubleValue (0.0));
340  // set update interval
341  basicSourceHelper.Set ("PeriodicEnergyUpdateInterval",
342  TimeValue (Seconds (updateIntervalS)));
343  // install source
344  EnergySourceContainer sources = basicSourceHelper.Install (c);
345 
346  // device energy model helper
347  WifiRadioEnergyModelHelper radioEnergyHelper;
348  // set energy depletion callback
351  radioEnergyHelper.SetDepletionCallback (callback);
352  // install on node
353  DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install (devices, sources);
354 
355  // run simulation
356  Simulator::Stop (Seconds (simTimeS));
357  Simulator::Run ();
358  Simulator::Destroy ();
359 
360  NS_LOG_DEBUG ("Simulation time = " << simTimeS << "s");
361  NS_LOG_DEBUG ("Update interval = " << updateIntervalS << "s");
362  NS_LOG_DEBUG ("Expected callback count is " << m_numOfNodes);
363  NS_LOG_DEBUG ("Actual callback count is " << m_callbackCount);
364 
365  // check result, call back should only be invoked once
366  NS_TEST_ASSERT_MSG_EQ_RETURNS_BOOL (m_numOfNodes, m_callbackCount, "Not all callbacks are invoked!");
367 
368  return false;
369 }
370 
371 // -------------------------------------------------------------------------- //
372 
379 {
380 public:
382 };
383 
385  : TestSuite ("basic-energy-model", UNIT)
386 {
387  AddTestCase (new BasicEnergyUpdateTest, TestCase::QUICK);
388  AddTestCase (new BasicEnergyDepletionTest, TestCase::QUICK);
389 }
390 
391 // create an instance of the test suite
393 
DeviceEnergyModelContainer Install(Ptr< NetDevice > device, Ptr< EnergySource > source) const
Assign WifiRadioEnergyModel to wifi devices.
Holds a vector of ns3::EnergySource pointers.
tuple devices
Definition: first.py:32
void SetDepletionCallback(WifiRadioEnergyModel::WifiRadioEnergyDepletionCallback callback)
Ptr< YansWifiChannel > Create(void) const
void SetRemoteStationManager(std::string type, std::string n0="", const AttributeValue &v0=EmptyAttributeValue(), std::string n1="", const AttributeValue &v1=EmptyAttributeValue(), std::string n2="", const AttributeValue &v2=EmptyAttributeValue(), std::string n3="", const AttributeValue &v3=EmptyAttributeValue(), std::string n4="", const AttributeValue &v4=EmptyAttributeValue(), std::string n5="", const AttributeValue &v5=EmptyAttributeValue(), std::string n6="", const AttributeValue &v6=EmptyAttributeValue(), std::string n7="", const AttributeValue &v7=EmptyAttributeValue())
Definition: wifi-helper.cc:73
Hold variables of type string.
Definition: string.h:41
Make it easy to create and manage PHY objects for the yans model.
A suite of tests to run.
Definition: test.h:1276
virtual void SetType(std::string type, std::string n0="", const AttributeValue &v0=EmptyAttributeValue(), std::string n1="", const AttributeValue &v1=EmptyAttributeValue(), std::string n2="", const AttributeValue &v2=EmptyAttributeValue(), std::string n3="", const AttributeValue &v3=EmptyAttributeValue(), std::string n4="", const AttributeValue &v4=EmptyAttributeValue(), std::string n5="", const AttributeValue &v5=EmptyAttributeValue(), std::string n6="", const AttributeValue &v6=EmptyAttributeValue(), std::string n7="", const AttributeValue &v7=EmptyAttributeValue())
Channel is IDLE, no packet is being transmitted.
Definition: csma-channel.h:62
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:201
BasicEnergySource decreases/increases remaining energy stored in itself in linearly.
void SetPcapDataLinkType(enum SupportedPcapDataLinkTypes dlt)
Set the data link type of PCAP traces to be used.
void SetTypeId(TypeId tid)
Set the TypeId of the Objects to be created by this factory.
#define NS_FATAL_ERROR(msg)
Fatal error handling.
Definition: fatal-error.h:100
Test case of update remaining energy for BasicEnergySource and WifiRadioEnergyModel.
void Set(std::string name, const AttributeValue &v)
void DoRun(void)
Implementation to actually run this TestCase.
encapsulates test code
Definition: test.h:1108
Unit test suite for energy model.
helps to create WifiNetDevice objects
Definition: wifi-helper.h:92
void DoRun(void)
Implementation to actually run this TestCase.
Holds a vector of ns3::DeviceEnergyModel pointers.
virtual NetDeviceContainer Install(const WifiPhyHelper &phy, const WifiMacHelper &mac, NodeContainer c) const
Definition: wifi-helper.cc:102
#define NS_TEST_ASSERT_MSG_EQ_RETURNS_BOOL(actual, limit, msg)
Test that an actual and expected (limit) value are equal and report and abort if not.
Definition: test.h:216
void SetChannel(Ptr< YansWifiChannel > channel)
double GetCcaBusyCurrentA(void) const
#define NS_TEST_ASSERT_MSG_EQ_TOL_RETURNS_BOOL(actual, limit, tol, msg)
Test that actual and expected (limit) values are equal to plus or minus some tolerance and report and...
Definition: test.h:449
void AddTestCase(TestCase *testCase, enum TestDuration duration)
Add an individual child TestCase to this test suite.
Definition: test.cc:190
static BasicEnergyModelTestSuite g_energyModelTestSuite
AttributeValue implementation for Time.
Definition: nstime.h:928
Ptr< Object > Create(void) const
Create an Object instance of the configured TypeId.
#define NS_TEST_ASSERT_MSG_NE_RETURNS_BOOL(actual, limit, msg)
Test that an actual and expected (limit) value are not equal and report and abort if not...
Definition: test.h:650
#define NS_TEST_ASSERT_MSG_EQ(actual, limit, msg)
Test that an actual and expected (limit) value are equal and report and abort if not.
Definition: test.h:158
Creates a BasicEnergySource object.
holds a vector of ns3::NetDevice pointers
virtual void SetStandard(enum WifiPhyStandard standard)
Definition: wifi-helper.cc:96
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1296
WifiPhy::State GetCurrentState(void) const
bool StateSwitchTest(WifiPhy::State state)
void AggregateObject(Ptr< Object > other)
Aggregate two Objects together.
Definition: object.cc:246
create non QoS-enabled MAC layers for a ns3::WifiNetDevice.
Ptr< DeviceEnergyModel > Get(uint32_t i) const
Get the i-th Ptr stored in this container.
virtual void SetEnergySource(Ptr< EnergySource > source)
Sets pointer to EnergySouce installed on node.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
keep track of a set of node pointers.
DSSS PHY (Clause 15) and HR/DSSS PHY (Clause 18)
EnergySourceContainer Install(Ptr< Node > node) const
Test case of energy depletion handling for BasicEnergySource and WifiRadioEnergyModel.
manage and create wifi channel objects for the yans model.
A WiFi radio energy model.
Instantiate subclasses of ns3::Object.
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition: log.h:236
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:866
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:683
void Set(std::string name, const AttributeValue &v)
uint32_t GetN(void) const
Get the number of Ptr stored in this container.
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
void SetPropagationDelay(std::string name, std::string n0="", const AttributeValue &v0=EmptyAttributeValue(), std::string n1="", const AttributeValue &v1=EmptyAttributeValue(), std::string n2="", const AttributeValue &v2=EmptyAttributeValue(), std::string n3="", const AttributeValue &v3=EmptyAttributeValue(), std::string n4="", const AttributeValue &v4=EmptyAttributeValue(), std::string n5="", const AttributeValue &v5=EmptyAttributeValue(), std::string n6="", const AttributeValue &v6=EmptyAttributeValue(), std::string n7="", const AttributeValue &v7=EmptyAttributeValue())
State
The state of the PHY layer.
Definition: wifi-phy.h:132
This class can be used to hold variables of floating point type such as 'double' or 'float'...
Definition: double.h:41
bool DepletionTestCase(double simTimeS, double updateIntervalS)
void DepletionHandler(void)
Callback invoked when energy is drained from source.
double GetSwitchingCurrentA(void) const