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 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Sidharth Nabar <snabar@uw.edu>, He Wu <mdzz@u.washington.edu>
7 */
8
9#include "ns3/core-module.h"
10#include "ns3/energy-module.h"
11#include "ns3/internet-module.h"
12#include "ns3/mobility-module.h"
13#include "ns3/network-module.h"
14#include "ns3/wifi-radio-energy-model-helper.h"
15#include "ns3/yans-wifi-helper.h"
16
17#include <fstream>
18#include <iostream>
19#include <string>
20#include <vector>
21
22using namespace ns3;
23using namespace ns3::energy;
24
25NS_LOG_COMPONENT_DEFINE("EnergyExample");
26
27/**
28 * Print a received packet
29 *
30 * @param from sender address
31 * @return a string with the details of the packet: dst {IP, port}, time.
32 */
33static inline std::string
35{
37
38 std::ostringstream oss;
39 oss << "--\nReceived one packet! Socket: " << iaddr.GetIpv4() << " port: " << iaddr.GetPort()
40 << " at time = " << Simulator::Now().GetSeconds() << "\n--";
41
42 return oss.str();
43}
44
45/**
46 * @param socket Pointer to socket.
47 *
48 * Packet receiving sink.
49 */
50void
52{
53 Ptr<Packet> packet;
54 Address from;
55 while ((packet = socket->RecvFrom(from)))
56 {
57 if (packet->GetSize() > 0)
58 {
60 }
61 }
62}
63
64/**
65 * @param socket Pointer to socket.
66 * @param pktSize Packet size.
67 * @param n Pointer to node.
68 * @param pktCount Number of packets to generate.
69 * @param pktInterval Packet sending interval.
70 *
71 * Traffic generator.
72 */
73static void
76 Ptr<Node> n,
79{
80 if (pktCount > 0)
81 {
82 socket->Send(Create<Packet>(pktSize));
85 socket,
86 pktSize,
87 n,
88 pktCount - 1,
90 }
91 else
92 {
93 socket->Close();
94 }
95}
96
97/**
98 * Trace function for remaining energy at node.
99 *
100 * @param oldValue Old value
101 * @param remainingEnergy New value
102 */
103void
105{
106 NS_LOG_UNCOND(Simulator::Now().GetSeconds()
107 << "s Current remaining energy = " << remainingEnergy << "J");
108}
109
110/**
111 * @brief Trace function for total energy consumption at node.
112 *
113 * @param oldValue Old value
114 * @param totalEnergy New value
115 */
116void
118{
119 NS_LOG_UNCOND(Simulator::Now().GetSeconds()
120 << "s Total energy consumed by radio = " << totalEnergy << "J");
121}
122
123int
124main(int argc, char* argv[])
125{
126 /*
127 LogComponentEnable ("EnergySource", LOG_LEVEL_DEBUG);
128 LogComponentEnable ("BasicEnergySource", LOG_LEVEL_DEBUG);
129 LogComponentEnable ("DeviceEnergyModel", LOG_LEVEL_DEBUG);
130 LogComponentEnable ("WifiRadioEnergyModel", LOG_LEVEL_DEBUG);
131 */
132
133 LogComponentEnable("EnergyExample",
135
136 std::string phyMode("DsssRate1Mbps");
137 double Prss = -80; // dBm
138 uint32_t PpacketSize = 200; // bytes
139 bool verbose = false;
140
141 // simulation parameters
142 uint32_t numPackets = 10000; // number of packets to send
143 double interval = 1; // seconds
144 double startTime = 0.0; // seconds
145 double distanceToRx = 100.0; // meters
146
148 cmd.AddValue("phyMode", "Wifi Phy mode", phyMode);
149 cmd.AddValue("Prss", "Intended primary RSS (dBm)", Prss);
150 cmd.AddValue("PpacketSize", "size of application packet sent", PpacketSize);
151 cmd.AddValue("numPackets", "Total number of packets to send", numPackets);
152 cmd.AddValue("startTime", "Simulation start time", startTime);
153 cmd.AddValue("distanceToRx", "X-Axis distance between nodes", distanceToRx);
154 cmd.AddValue("verbose", "Turn on all device log components", verbose);
155 cmd.Parse(argc, argv);
156
157 // Convert to time object
158 Time interPacketInterval = Seconds(interval);
159
160 // disable fragmentation for frames below 2200 bytes
161 Config::SetDefault("ns3::WifiRemoteStationManager::FragmentationThreshold",
162 StringValue("2200"));
163 // turn off RTS/CTS for frames below 2200 bytes
164 Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("2200"));
165 // Fix non-unicast data rate to be the same as that of unicast
166 Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode", StringValue(phyMode));
167
169 c.Create(2); // create 2 nodes
171 networkNodes.Add(c.Get(0));
172 networkNodes.Add(c.Get(1));
173
174 // The below set of helpers will help us to put together the wifi NICs we want
176 if (verbose)
177 {
179 }
180 wifi.SetStandard(WIFI_STANDARD_80211b);
181
182 /** Wifi PHY **/
183 /***************************************************************************/
185
186 /** wifi channel **/
188 wifiChannel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
189 wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel");
190
191 // create wifi channel
193 wifiPhy.SetChannel(wifiChannelPtr);
194
195 /** MAC layer **/
196 // Add a MAC and disable rate control
198 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
199 "DataMode",
201 "ControlMode",
203 // Set it to ad-hoc mode
204 wifiMac.SetType("ns3::AdhocWifiMac");
205
206 /** install PHY + MAC **/
208
209 /** mobility **/
212 positionAlloc->Add(Vector(0.0, 0.0, 0.0));
213 positionAlloc->Add(Vector(2 * distanceToRx, 0.0, 0.0));
214 mobility.SetPositionAllocator(positionAlloc);
215 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
216 mobility.Install(c);
217
218 /** Energy Model **/
219 /***************************************************************************/
220 /* energy source */
222 // configure energy source
223 basicSourceHelper.Set("BasicEnergySourceInitialEnergyJ", DoubleValue(0.1));
224 // install source
226 /* device energy model */
228 // configure radio energy model
229 radioEnergyHelper.Set("TxCurrentA", DoubleValue(0.0174));
230 // install device model
232 /***************************************************************************/
233
234 /** Internet stack **/
236 internet.Install(networkNodes);
237
239 NS_LOG_INFO("Assign IP Addresses.");
240 ipv4.SetBase("10.1.1.0", "255.255.255.0");
241 Ipv4InterfaceContainer i = ipv4.Assign(devices);
242
243 TypeId tid = TypeId::LookupByName("ns3::UdpSocketFactory");
244 Ptr<Socket> recvSink = Socket::CreateSocket(networkNodes.Get(1), tid); // node 1, receiver
246 recvSink->Bind(local);
247 recvSink->SetRecvCallback(MakeCallback(&ReceivePacket));
248
249 Ptr<Socket> source = Socket::CreateSocket(networkNodes.Get(0), tid); // node 0, sender
251 source->SetAllowBroadcast(true);
252 source->Connect(remote);
253
254 /** connect trace sources **/
255 /***************************************************************************/
256 // all sources are connected to node 1
257 // energy source
259 basicSourcePtr->TraceConnectWithoutContext("RemainingEnergy", MakeCallback(&RemainingEnergy));
260 // device energy model
262 basicSourcePtr->FindDeviceEnergyModels("ns3::WifiRadioEnergyModel").Get(0);
264 basicRadioModelPtr->TraceConnectWithoutContext("TotalEnergyConsumption",
266 /***************************************************************************/
267
268 /** simulation setup **/
269 // start traffic
270 Simulator::Schedule(Seconds(startTime),
272 source,
274 networkNodes.Get(0),
276 interPacketInterval);
277
280
281 for (auto iter = deviceModels.Begin(); iter != deviceModels.End(); iter++)
282 {
283 double energyConsumed = (*iter)->GetTotalEnergyConsumption();
284 NS_LOG_UNCOND("End of simulation ("
285 << Simulator::Now().GetSeconds()
286 << "s) Total energy consumed by radio = " << energyConsumed << "J");
288 }
289
291
292 return 0;
293}
a polymophic address class
Definition address.h:90
Creates a BasicEnergySource object.
void Set(std::string name, const AttributeValue &v) override
Parse command-line arguments.
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
an Inet address class
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.
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:66
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:560
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition simulator.cc:131
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:197
static void Run()
Run the simulation.
Definition simulator.cc:167
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition simulator.cc:175
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:61
Hold variables of type string.
Definition string.h:45
Simulation virtual time values and global simulation resolution.
Definition nstime.h:94
double GetSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
Definition nstime.h:392
a unique identifier for an interface.
Definition type-id.h:49
static TypeId LookupByName(std::string name)
Get a TypeId by name.
Definition type-id.cc:872
helps to create WifiNetDevice objects
static void EnableLogComponents(LogLevel logLevel=LOG_LEVEL_ALL)
Helper to enable all WifiNetDevice log components with one statement.
create MAC layers for a ns3::WifiNetDevice.
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)
Make it easy to create and manage PHY objects for the YANS model.
Holds a vector of ns3::DeviceEnergyModel pointers.
Holds a vector of ns3::EnergySource pointers.
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:55
void SetDefault(std::string name, const AttributeValue &value)
Definition config.cc:883
#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:191
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:264
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:436
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1344
@ WIFI_STANDARD_80211b
devices
Definition first.py:31
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:291
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:684
LogLevel
Logging severity classes and levels.
Definition log.h:83
@ LOG_PREFIX_TIME
Prefix all trace prints with simulation time.
Definition log.h:108
@ LOG_PREFIX_NODE
Prefix all trace prints with simulation node.
Definition log.h:109
@ LOG_LEVEL_INFO
LOG_INFO and above.
Definition log.h:93
wifi
Definition third.py:84
mobility
Definition third.py:92
bool verbose
uint32_t pktSize
packet size used for the simulation (in bytes)