A Discrete-Event Network Simulator
API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
energy-model-example.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: Sidharth Nabar <snabar@uw.edu>, He Wu <mdzz@u.washington.edu>
19  */
20 
21 #include "ns3/core-module.h"
22 #include "ns3/network-module.h"
23 #include "ns3/mobility-module.h"
24 #include "ns3/config-store-module.h"
25 #include "ns3/wifi-module.h"
26 #include "ns3/energy-module.h"
27 #include "ns3/internet-module.h"
28 
29 #include <iostream>
30 #include <fstream>
31 #include <vector>
32 #include <string>
33 
34 NS_LOG_COMPONENT_DEFINE ("EnergyExample");
35 
36 using namespace ns3;
37 
38 static inline std::string
40 {
42 
43  std::ostringstream oss;
44  oss << "--\nReceived one packet! Socket: " << iaddr.GetIpv4 ()
45  << " port: " << iaddr.GetPort ()
46  << " at time = " << Simulator::Now ().GetSeconds ()
47  << "\n--";
48 
49  return oss.str ();
50 }
51 
57 void
59 {
60  Ptr<Packet> packet;
61  Address from;
62  while ((packet = socket->RecvFrom (from)))
63  {
64  if (packet->GetSize () > 0)
65  {
67  }
68  }
69 }
70 
80 static void
81 GenerateTraffic (Ptr<Socket> socket, uint32_t pktSize, Ptr<Node> n,
82  uint32_t pktCount, Time pktInterval)
83 {
84  if (pktCount > 0)
85  {
86  socket->Send (Create<Packet> (pktSize));
87  Simulator::Schedule (pktInterval, &GenerateTraffic, socket, pktSize, n,
88  pktCount - 1, pktInterval);
89  }
90  else
91  {
92  socket->Close ();
93  }
94 }
95 
97 void
98 RemainingEnergy (double oldValue, double remainingEnergy)
99 {
100  NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
101  << "s Current remaining energy = " << remainingEnergy << "J");
102 }
103 
105 void
106 TotalEnergy (double oldValue, double totalEnergy)
107 {
108  NS_LOG_UNCOND (Simulator::Now ().GetSeconds ()
109  << "s Total energy consumed by radio = " << totalEnergy << "J");
110 }
111 
112 int
113 main (int argc, char *argv[])
114 {
115  /*
116  LogComponentEnable ("EnergySource", LOG_LEVEL_DEBUG);
117  LogComponentEnable ("BasicEnergySource", LOG_LEVEL_DEBUG);
118  LogComponentEnable ("DeviceEnergyModel", LOG_LEVEL_DEBUG);
119  LogComponentEnable ("WifiRadioEnergyModel", LOG_LEVEL_DEBUG);
120  */
121 
122  std::string phyMode ("DsssRate1Mbps");
123  double Prss = -80; // dBm
124  uint32_t PpacketSize = 200; // bytes
125  bool verbose = false;
126 
127  // simulation parameters
128  uint32_t numPackets = 10000; // number of packets to send
129  double interval = 1; // seconds
130  double startTime = 0.0; // seconds
131  double distanceToRx = 100.0; // meters
132  /*
133  * This is a magic number used to set the transmit power, based on other
134  * configuration.
135  */
136  double offset = 81;
137 
138  CommandLine cmd;
139  cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
140  cmd.AddValue ("Prss", "Intended primary RSS (dBm)", Prss);
141  cmd.AddValue ("PpacketSize", "size of application packet sent", PpacketSize);
142  cmd.AddValue ("numPackets", "Total number of packets to send", numPackets);
143  cmd.AddValue ("startTime", "Simulation start time", startTime);
144  cmd.AddValue ("distanceToRx", "X-Axis distance between nodes", distanceToRx);
145  cmd.AddValue ("verbose", "Turn on all device log components", verbose);
146  cmd.Parse (argc, argv);
147 
148  // Convert to time object
149  Time interPacketInterval = Seconds (interval);
150 
151  // disable fragmentation for frames below 2200 bytes
152  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold",
153  StringValue ("2200"));
154  // turn off RTS/CTS for frames below 2200 bytes
155  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold",
156  StringValue ("2200"));
157  // Fix non-unicast data rate to be the same as that of unicast
158  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",
159  StringValue (phyMode));
160 
161  NodeContainer c;
162  c.Create (2); // create 2 nodes
163  NodeContainer networkNodes;
164  networkNodes.Add (c.Get (0));
165  networkNodes.Add (c.Get (1));
166 
167  // The below set of helpers will help us to put together the wifi NICs we want
168  WifiHelper wifi;
169  if (verbose)
170  {
171  wifi.EnableLogComponents ();
172  }
174 
176  /***************************************************************************/
178  wifiPhy.Set ("RxGain", DoubleValue (-10));
179  wifiPhy.Set ("TxGain", DoubleValue (offset + Prss));
180  wifiPhy.Set ("CcaMode1Threshold", DoubleValue (0.0));
181  /***************************************************************************/
182 
184  YansWifiChannelHelper wifiChannel;
185  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
186  wifiChannel.AddPropagationLoss ("ns3::FriisPropagationLossModel");
187  // create wifi channel
188  Ptr<YansWifiChannel> wifiChannelPtr = wifiChannel.Create ();
189  wifiPhy.SetChannel (wifiChannelPtr);
190 
192  // Add a non-QoS upper MAC, and disable rate control
194  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager", "DataMode",
195  StringValue (phyMode), "ControlMode",
196  StringValue (phyMode));
197  // Set it to ad-hoc mode
198  wifiMac.SetType ("ns3::AdhocWifiMac");
199 
201  NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, networkNodes);
202 
204  MobilityHelper mobility;
205  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
206  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
207  positionAlloc->Add (Vector (2 * distanceToRx, 0.0, 0.0));
208  mobility.SetPositionAllocator (positionAlloc);
209  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
210  mobility.Install (c);
211 
213  /***************************************************************************/
214  /* energy source */
215  BasicEnergySourceHelper basicSourceHelper;
216  // configure energy source
217  basicSourceHelper.Set ("BasicEnergySourceInitialEnergyJ", DoubleValue (0.1));
218  // install source
219  EnergySourceContainer sources = basicSourceHelper.Install (c);
220  /* device energy model */
221  WifiRadioEnergyModelHelper radioEnergyHelper;
222  // configure radio energy model
223  radioEnergyHelper.Set ("TxCurrentA", DoubleValue (0.0174));
224  // install device model
225  DeviceEnergyModelContainer deviceModels = radioEnergyHelper.Install (devices, sources);
226  /***************************************************************************/
227 
229  InternetStackHelper internet;
230  internet.Install (networkNodes);
231 
232  Ipv4AddressHelper ipv4;
233  NS_LOG_INFO ("Assign IP Addresses.");
234  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
235  Ipv4InterfaceContainer i = ipv4.Assign (devices);
236 
237  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
238  Ptr<Socket> recvSink = Socket::CreateSocket (networkNodes.Get (1), tid); // node 1, receiver
240  recvSink->Bind (local);
242 
243  Ptr<Socket> source = Socket::CreateSocket (networkNodes.Get (0), tid); // node 0, sender
245  source->SetAllowBroadcast (true);
246  source->Connect (remote);
247 
249  /***************************************************************************/
250  // all sources are connected to node 1
251  // energy source
252  Ptr<BasicEnergySource> basicSourcePtr = DynamicCast<BasicEnergySource> (sources.Get (1));
253  basicSourcePtr->TraceConnectWithoutContext ("RemainingEnergy", MakeCallback (&RemainingEnergy));
254  // device energy model
255  Ptr<DeviceEnergyModel> basicRadioModelPtr =
256  basicSourcePtr->FindDeviceEnergyModels ("ns3::WifiRadioEnergyModel").Get (0);
257  NS_ASSERT (basicRadioModelPtr != NULL);
258  basicRadioModelPtr->TraceConnectWithoutContext ("TotalEnergyConsumption", MakeCallback (&TotalEnergy));
259  /***************************************************************************/
260 
261 
263  // start traffic
264  Simulator::Schedule (Seconds (startTime), &GenerateTraffic, source, PpacketSize,
265  networkNodes.Get (0), numPackets, interPacketInterval);
266 
267  Simulator::Stop (Seconds (10.0));
268  Simulator::Run ();
270 
271  return 0;
272 }
void AddPropagationLoss(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())
DeviceEnergyModelContainer Install(Ptr< NetDevice > device, Ptr< EnergySource > source) const
static std::string PrintReceivedPacket(Address &from)
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:79
Assign WifiRadioEnergyModel to wifi devices.
an Inet address class
Ipv4Address GetIpv4(void) const
static Ipv4Address GetAny(void)
Holds a vector of ns3::EnergySource pointers.
tuple devices
Definition: first.py:32
holds a vector of std::pair of Ptr and interface index.
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:18
virtual bool SetAllowBroadcast(bool allowBroadcast)=0
Configure whether broadcast datagram transmissions are allowed.
Make it easy to create and manage PHY objects for the yans model.
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())
static void GenerateTraffic(Ptr< Socket > socket, uint32_t pktSize, Ptr< Node > n, uint32_t pktCount, Time pktInterval)
void ReceivePacket(Ptr< Socket > socket)
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file...
Definition: assert.h:61
static void Run(void)
Run the simulation until one of:
Definition: simulator.cc:157
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:170
aggregate IP/TCP/UDP functionality to existing Nodes.
uint32_t GetSize(void) const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
Definition: packet.h:744
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:223
void Set(std::string name, const AttributeValue &v)
static YansWifiPhyHelper Default(void)
Create a phy helper in a default working state.
static EventId Schedule(Time const &time, MEM mem_ptr, OBJ obj)
Schedule an event to expire at the relative time "time" is reached.
Definition: simulator.h:825
helps to create WifiNetDevice objects
Definition: wifi-helper.h:88
a 3d vector
Definition: vector.h:31
Holds a vector of ns3::DeviceEnergyModel pointers.
virtual NetDeviceContainer Install(const WifiPhyHelper &phy, const WifiMacHelper &mac, NodeContainer c) const
Definition: wifi-helper.cc:102
a polymophic address class
Definition: address.h:86
void SetChannel(Ptr< YansWifiChannel > channel)
double GetSeconds(void) const
Definition: nstime.h:272
void TotalEnergy(double oldValue, double totalEnergy)
Trace function for total energy consumption at node.
void Install(Ptr< Node > node) const
"Layout" a single node according to the current position allocator type.
double startTime
Creates a BasicEnergySource object.
holds a vector of ns3::NetDevice pointers
virtual void SetStandard(enum WifiPhyStandard standard)
Definition: wifi-helper.cc:96
void RemainingEnergy(double oldValue, double remainingEnergy)
Trace function for remaining energy at node.
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1242
static NqosWifiMacHelper Default(void)
Create a mac helper in a default working state.
void SetRecvCallback(Callback< void, Ptr< Socket > >)
Notify application when new data is available to be read.
Definition: socket.cc:127
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:70
create non QoS-enabled MAC layers for a ns3::WifiNetDevice.
Parse command-line arguments.
Definition: command-line.h:177
static Ipv4Address GetBroadcast(void)
static void Destroy(void)
Every event scheduled by the Simulator::insertAtDestroy method is invoked.
Definition: simulator.cc:121
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
Ptr< DeviceEnergyModel > Get(uint32_t i) const
Get the i-th Ptr stored in this container.
bool TraceConnectWithoutContext(std::string name, const CallbackBase &cb)
Definition: object-base.cc:284
void SetDefault(std::string name, const AttributeValue &value)
Definition: config.cc:667
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
keep track of a set of node pointers.
DSSS PHY (Clause 15) and HR/DSSS PHY (Clause 18)
void Set(std::string name, const AttributeValue &v)
EnergySourceContainer Install(Ptr< Node > node) const
void SetMobilityModel(std::string type, 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(), std::string n8="", const AttributeValue &v8=EmptyAttributeValue(), std::string n9="", const AttributeValue &v9=EmptyAttributeValue())
void Install(std::string nodeName) const
Aggregate implementations of the ns3::Ipv4, ns3::Ipv6, ns3::Udp, and ns3::Tcp classes onto the provid...
#define NS_LOG_UNCOND(msg)
Output the requested message unconditionaly.
manage and create wifi channel objects for the yans model.
static Time Now(void)
Return the "current simulation time".
Definition: simulator.cc:180
Ptr< EnergySource > Get(uint32_t i) const
Get the i-th Ptr stored in this container.
Helper class used to assign positions and mobility models to nodes.
static void EnableLogComponents(void)
Helper to enable all WifiNetDevice log components with one statement.
Definition: wifi-helper.cc:142
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
void Add(NodeContainer other)
Append the contents of another NodeContainer to the end of this container.
int main(int argc, char *argv[])
void AddValue(const std::string &name, const std::string &help, T &value)
Add a program argument, assigning to POD.
Definition: command-line.h:435
static void Stop(void)
If an event invokes this method, it will be the last event scheduled by the Simulator::run method bef...
Definition: simulator.cc:165
Ptr< Node > Get(uint32_t i) const
Get the Ptr stored in this container at a given index.
void Set(std::string name, const AttributeValue &v)
void Parse(int argc, char *argv[])
Parse the program arguments.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
DeviceEnergyModelContainer FindDeviceEnergyModels(TypeId tid)
uint16_t GetPort(void) const
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
virtual Ptr< Packet > RecvFrom(uint32_t maxSize, uint32_t flags, Address &fromAddress)=0
Read a single packet from the socket and retrieve the sender address.
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())
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
void SetPositionAllocator(Ptr< PositionAllocator > allocator)
Set the position allocator which will be used to allocate the initial position of every node initiali...
virtual int Close(void)=0
Close a socket.
Hold a floating point type.
Definition: double.h:41
a unique identifier for an interface.
Definition: type-id.h:49
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
bool verbose
static TypeId LookupByName(std::string name)
Definition: type-id.cc:535