A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
energy-model-example.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: Sidharth Nabar <snabar@uw.edu>, He Wu <mdzz@u.washington.edu>
18 */
19
20#include "ns3/config-store-module.h"
21#include "ns3/core-module.h"
22#include "ns3/energy-module.h"
23#include "ns3/internet-module.h"
24#include "ns3/mobility-module.h"
25#include "ns3/network-module.h"
26#include "ns3/wifi-radio-energy-model-helper.h"
27#include "ns3/yans-wifi-helper.h"
28
29#include <fstream>
30#include <iostream>
31#include <string>
32#include <vector>
33
34using namespace ns3;
35
36NS_LOG_COMPONENT_DEFINE("EnergyExample");
37
44static inline std::string
46{
48
49 std::ostringstream oss;
50 oss << "--\nReceived one packet! Socket: " << iaddr.GetIpv4() << " port: " << iaddr.GetPort()
51 << " at time = " << Simulator::Now().GetSeconds() << "\n--";
52
53 return oss.str();
54}
55
61void
63{
64 Ptr<Packet> packet;
65 Address from;
66 while ((packet = socket->RecvFrom(from)))
67 {
68 if (packet->GetSize() > 0)
69 {
71 }
72 }
73}
74
84static void
87 Ptr<Node> n,
88 uint32_t pktCount,
89 Time pktInterval)
90{
91 if (pktCount > 0)
92 {
93 socket->Send(Create<Packet>(pktSize));
94 Simulator::Schedule(pktInterval,
96 socket,
97 pktSize,
98 n,
99 pktCount - 1,
100 pktInterval);
101 }
102 else
103 {
104 socket->Close();
105 }
106}
107
114void
115RemainingEnergy(double oldValue, double remainingEnergy)
116{
117 NS_LOG_UNCOND(Simulator::Now().GetSeconds()
118 << "s Current remaining energy = " << remainingEnergy << "J");
119}
120
127void
128TotalEnergy(double oldValue, double totalEnergy)
129{
130 NS_LOG_UNCOND(Simulator::Now().GetSeconds()
131 << "s Total energy consumed by radio = " << totalEnergy << "J");
132}
133
134int
135main(int argc, char* argv[])
136{
137 /*
138 LogComponentEnable ("EnergySource", LOG_LEVEL_DEBUG);
139 LogComponentEnable ("BasicEnergySource", LOG_LEVEL_DEBUG);
140 LogComponentEnable ("DeviceEnergyModel", LOG_LEVEL_DEBUG);
141 LogComponentEnable ("WifiRadioEnergyModel", LOG_LEVEL_DEBUG);
142 */
143
144 LogComponentEnable("EnergyExample",
146
147 std::string phyMode("DsssRate1Mbps");
148 double Prss = -80; // dBm
149 uint32_t PpacketSize = 200; // bytes
150 bool verbose = false;
151
152 // simulation parameters
153 uint32_t numPackets = 10000; // number of packets to send
154 double interval = 1; // seconds
155 double startTime = 0.0; // seconds
156 double distanceToRx = 100.0; // meters
157
158 CommandLine cmd(__FILE__);
159 cmd.AddValue("phyMode", "Wifi Phy mode", phyMode);
160 cmd.AddValue("Prss", "Intended primary RSS (dBm)", Prss);
161 cmd.AddValue("PpacketSize", "size of application packet sent", PpacketSize);
162 cmd.AddValue("numPackets", "Total number of packets to send", numPackets);
163 cmd.AddValue("startTime", "Simulation start time", startTime);
164 cmd.AddValue("distanceToRx", "X-Axis distance between nodes", distanceToRx);
165 cmd.AddValue("verbose", "Turn on all device log components", verbose);
166 cmd.Parse(argc, argv);
167
168 // Convert to time object
169 Time interPacketInterval = Seconds(interval);
170
171 // disable fragmentation for frames below 2200 bytes
172 Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
173 StringValue("2200"));
174 // turn off RTS/CTS for frames below 2200 bytes
175 Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("2200"));
176 // Fix non-unicast data rate to be the same as that of unicast
177 Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
178
180 c.Create(2); // create 2 nodes
181 NodeContainer networkNodes;
182 networkNodes.Add(c.Get(0));
183 networkNodes.Add(c.Get(1));
184
185 // The below set of helpers will help us to put together the wifi NICs we want
187 if (verbose)
188 {
190 }
191 wifi.SetStandard(WIFI_STANDARD_80211b);
192
194 /***************************************************************************/
195 YansWifiPhyHelper wifiPhy;
196
198 YansWifiChannelHelper wifiChannel;
199 wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
200 wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
201
202 // create wifi channel
203 Ptr<YansWifiChannel> wifiChannelPtr = wifiChannel.Create();
204 wifiPhy.SetChannel(wifiChannelPtr);
205
207 // Add a MAC and disable rate control
208 WifiMacHelper wifiMac;
209 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
210 "DataMode",
211 StringValue(phyMode),
212 "ControlMode",
213 StringValue(phyMode));
214 // Set it to ad-hoc mode
215 wifiMac.SetType("ns3::AdhocWifiMac");
216
218 NetDeviceContainer devices = wifi.Install(wifiPhy, wifiMac, networkNodes);
219
222 Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator>();
223 positionAlloc->Add(Vector(0.0, 0.0, 0.0));
224 positionAlloc->Add(Vector(2 * distanceToRx, 0.0, 0.0));
225 mobility.SetPositionAllocator(positionAlloc);
226 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
227 mobility.Install(c);
228
230 /***************************************************************************/
231 /* energy source */
232 BasicEnergySourceHelper basicSourceHelper;
233 // configure energy source
234 basicSourceHelper.Set("BasicEnergySourceInitialEnergyJ", DoubleValue(0.1));
235 // install source
236 EnergySourceContainer sources = basicSourceHelper.Install(c);
237 /* device energy model */
238 WifiRadioEnergyModelHelper radioEnergyHelper;
239 // configure radio energy model
240 radioEnergyHelper.Set("TxCurrentA", DoubleValue(0.0174));
241 // install device model
242 DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install(devices, sources);
243 /***************************************************************************/
244
247 internet.Install(networkNodes);
248
250 NS_LOG_INFO("Assign IP Addresses.");
251 ipv4.SetBase("10.1.1.0", "255.255.255.0");
252 Ipv4InterfaceContainer i = ipv4.Assign(devices);
253
254 TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
255 Ptr<Socket> recvSink = Socket::CreateSocket(networkNodes.Get(1), tid); // node 1, receiver
257 recvSink->Bind(local);
258 recvSink->SetRecvCallback(MakeCallback(&ReceivePacket));
259
260 Ptr<Socket> source = Socket::CreateSocket(networkNodes.Get(0), tid); // node 0, sender
262 source->SetAllowBroadcast(true);
263 source->Connect(remote);
264
266 /***************************************************************************/
267 // all sources are connected to node 1
268 // energy source
269 Ptr<BasicEnergySource> basicSourcePtr = DynamicCast<BasicEnergySource>(sources.Get(1));
270 basicSourcePtr->TraceConnectWithoutContext("RemainingEnergy", MakeCallback(&RemainingEnergy));
271 // device energy model
272 Ptr<DeviceEnergyModel> basicRadioModelPtr =
273 basicSourcePtr->FindDeviceEnergyModels("ns3::WifiRadioEnergyModel").Get(0);
274 NS_ASSERT(basicRadioModelPtr);
275 basicRadioModelPtr->TraceConnectWithoutContext("TotalEnergyConsumption",
277 /***************************************************************************/
278
280 // start traffic
281 Simulator::Schedule(Seconds(startTime),
283 source,
284 PpacketSize,
285 networkNodes.Get(0),
286 numPackets,
287 interPacketInterval);
288
291
292 for (DeviceEnergyModelContainer::Iterator iter = deviceModels.Begin();
293 iter != deviceModels.End();
294 iter++)
295 {
296 double energyConsumed = (*iter)->GetTotalEnergyConsumption();
297 NS_LOG_UNCOND("End of simulation ("
298 << Simulator::Now().GetSeconds()
299 << "s) Total energy consumed by radio = " << energyConsumed << "J");
300 NS_ASSERT(energyConsumed <= 0.1);
301 }
302
304
305 return 0;
306}
a polymophic address class
Definition: address.h:100
Creates a BasicEnergySource object.
void Set(std::string name, const AttributeValue &v) override
Parse command-line arguments.
Definition: command-line.h:232
Holds a vector of ns3::DeviceEnergyModel pointers.
std::vector< Ptr< DeviceEnergyModel > >::const_iterator Iterator
Const iterator of DeviceEnergyModel container.
Iterator Begin() const
Get an iterator which refers to the first DeviceEnergyModel pointer in the container.
Iterator End() const
Get an iterator which refers to the last DeviceEnergyModel pointer in the 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.
Ptr< EnergySource > Get(uint32_t i) const
Get the i-th Ptr<EnergySource> stored in this container.
EnergySourceContainer Install(Ptr< Node > node) const
an Inet address class
Ipv4Address GetIpv4() const
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
aggregate IP/TCP/UDP functionality to existing Nodes.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
static Ipv4Address GetBroadcast()
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.
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
void Add(const NodeContainer &nc)
Append the contents of another NodeContainer to the end of this container.
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
Smart pointer class similar to boost::intrusive_ptr.
Definition: ptr.h:78
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition: simulator.h:568
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition: simulator.cc:140
static Time Now()
Return the current simulation virtual time.
Definition: simulator.cc:199
static void Run()
Run the simulation.
Definition: simulator.cc:176
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition: simulator.cc:184
static Ptr< Socket > CreateSocket(Ptr< Node > node, TypeId tid)
This method wraps the creation of sockets that is performed on a given node by a SocketFactory specif...
Definition: socket.cc:72
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:402
a unique identifier for an interface.
Definition: type-id.h:59
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition: type-id.cc:840
helps to create WifiNetDevice objects
Definition: wifi-helper.h:324
static void EnableLogComponents()
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)
Assign WifiRadioEnergyModel to wifi devices.
void Set(std::string name, const AttributeValue &v) override
manage and create wifi channel objects for the YANS model.
void SetPropagationDelay(std::string name, Ts &&... args)
void AddPropagationLoss(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 TotalEnergy(double oldValue, double totalEnergy)
Trace function for total energy consumption at node.
void ReceivePacket(Ptr< Socket > socket)
void RemainingEnergy(double oldValue, double remainingEnergy)
Trace function for remaining energy at node.
static void GenerateTraffic(Ptr< Socket > socket, uint32_t pktSize, Ptr< Node > n, uint32_t pktCount, Time pktInterval)
static std::string PrintReceivedPacket(Address &from)
Print a received packet.
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Definition: assert.h:66
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:891
#define NS_LOG_UNCOND(msg)
Output the requested message unconditionally.
#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:1336
@ WIFI_STANDARD_80211b
ns devices
Definition: first.py:35
Every class exported by the ns3 library is enclosed in the ns3 namespace.
void LogComponentEnable(const std::string &name, LogLevel level)
Enable the logging output associated with that log component.
Definition: log.cc:302
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:702
LogLevel
Logging severity classes and levels.
Definition: log.h:94
@ LOG_PREFIX_TIME
Prefix all trace prints with simulation time.
Definition: log.h:119
@ LOG_PREFIX_NODE
Prefix all trace prints with simulation node.
Definition: log.h:120
@ LOG_LEVEL_INFO
LOG_INFO and above.
Definition: log.h:104
ns cmd
Definition: second.py:33
ns wifi
Definition: third.py:88
ns mobility
Definition: third.py:96
bool verbose
uint32_t pktSize
packet size used for the simulation (in bytes)