A Discrete-Event Network Simulator
API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
uan-cw-example.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * Copyright (c) 2009 University of Washington
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: Leonard Tracy <lentracy@gmail.com>
19  */
20 
21 
45 #include "uan-cw-example.h"
46 #include "ns3/core-module.h"
47 #include "ns3/network-module.h"
48 #include "ns3/mobility-module.h"
49 #include "ns3/stats-module.h"
50 #include "ns3/applications-module.h"
51 
52 #include <fstream>
53 
54 using namespace ns3;
55 
56 NS_LOG_COMPONENT_DEFINE ("UanCwExample")
57  ;
58 
60  : m_numNodes (15),
61  m_dataRate (80),
62  m_depth (70),
63  m_boundary (500),
64  m_packetSize (32),
65  m_bytesTotal (0),
66  m_cwMin (10),
67  m_cwMax (400),
68  m_cwStep (10),
69  m_avgs (3),
70  m_slotTime (Seconds (0.2)),
71  m_simTime (Seconds (1000)),
72  m_gnudatfile ("uan-cw-example.gpl"),
73  m_asciitracefile ("uan-cw-example.asc"),
74  m_bhCfgFile ("uan-apps/dat/default.cfg")
75 {
76 }
77 
78 void
80 {
81  NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Resetting data");
82  m_throughputs.push_back (m_bytesTotal * 8.0 / m_simTime.GetSeconds ());
83  m_bytesTotal = 0;
84 }
85 
86 void
88 {
89  NS_ASSERT (m_throughputs.size () == m_avgs);
90 
91  double avgThroughput = 0.0;
92  for (uint32_t i=0; i<m_avgs; i++)
93  {
94  avgThroughput += m_throughputs[i];
95  }
96  avgThroughput /= m_avgs;
97  m_data.Add (cw, avgThroughput);
98  m_throughputs.clear ();
99 
100  Config::Set ("/NodeList/*/DeviceList/*/Mac/CW", UintegerValue (cw + m_cwStep));
101 
102  SeedManager::SetRun (SeedManager::GetRun () + 1);
103 
104  NS_LOG_DEBUG ("Average for cw=" << cw << " over " << m_avgs << " runs: " << avgThroughput);
105 }
106 void
108 {
109 
110  NS_LOG_DEBUG (Simulator::Now ().GetSeconds () << " Updating positions");
111  NodeContainer::Iterator it = nodes.Begin ();
112  Ptr<UniformRandomVariable> uv = CreateObject<UniformRandomVariable> ();
113  for (; it != nodes.End (); it++)
114  {
116  mp->SetPosition (Vector (uv->GetValue (0, m_boundary), uv->GetValue (0, m_boundary), 70.0));
117  }
118 }
119 
120 void
122 {
123  Ptr<Packet> packet;
124 
125  while ((packet = socket->Recv ()))
126  {
127  m_bytesTotal += packet->GetSize ();
128  }
129  packet = 0;
130 }
131 
134 {
135  uan.SetMac ("ns3::UanMacCw", "CW", UintegerValue (m_cwMin), "SlotTime", TimeValue (m_slotTime));
137  NodeContainer sink = NodeContainer ();
138  nc.Create (m_numNodes);
139  sink.Create (1);
140 
141  PacketSocketHelper socketHelper;
142  socketHelper.Install (nc);
143  socketHelper.Install (sink);
144 
145 #ifdef UAN_PROP_BH_INSTALLED
146  Ptr<UanPropModelBh> prop = CreateObjectWithAttributes<UanPropModelBh> ("ConfigFile", StringValue ("exbhconfig.cfg"));
147 #else
148  Ptr<UanPropModelIdeal> prop = CreateObjectWithAttributes<UanPropModelIdeal> ();
149 #endif //UAN_PROP_BH_INSTALLED
150  Ptr<UanChannel> channel = CreateObjectWithAttributes<UanChannel> ("PropagationModel", PointerValue (prop));
151 
152  //Create net device and nodes with UanHelper
153  NetDeviceContainer devices = uan.Install (nc, channel);
154  NetDeviceContainer sinkdev = uan.Install (sink, channel);
155 
156  MobilityHelper mobility;
157  Ptr<ListPositionAllocator> pos = CreateObject<ListPositionAllocator> ();
158 
159  {
160  Ptr<UniformRandomVariable> urv = CreateObject<UniformRandomVariable> ();
161  pos->Add (Vector (m_boundary / 2.0, m_boundary / 2.0, m_depth));
162  double rsum = 0;
163 
164  double minr = 2 * m_boundary;
165  for (uint32_t i = 0; i < m_numNodes; i++)
166  {
167  double x = urv->GetValue (0, m_boundary);
168  double y = urv->GetValue (0, m_boundary);
169  double newr = std::sqrt ((x - m_boundary / 2.0) * (x - m_boundary / 2.0)
170  + (y - m_boundary / 2.0) * (y - m_boundary / 2.0));
171  rsum += newr;
172  minr = std::min (minr, newr);
173  pos->Add (Vector (x, y, m_depth));
174 
175  }
176  NS_LOG_DEBUG ("Mean range from gateway: " << rsum / m_numNodes
177  << " min. range " << minr);
178 
179  mobility.SetPositionAllocator (pos);
180  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
181  mobility.Install (sink);
182 
183  NS_LOG_DEBUG ("Position of sink: "
184  << sink.Get (0)->GetObject<MobilityModel> ()->GetPosition ());
185  mobility.Install (nc);
186 
187  PacketSocketAddress socket;
188  socket.SetSingleDevice (sinkdev.Get (0)->GetIfIndex ());
189  socket.SetPhysicalAddress (sinkdev.Get (0)->GetAddress ());
190  socket.SetProtocol (0);
191 
192  OnOffHelper app ("ns3::PacketSocketFactory", Address (socket));
193  app.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]"));
194  app.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]"));
195  app.SetAttribute ("DataRate", DataRateValue (m_dataRate));
196  app.SetAttribute ("PacketSize", UintegerValue (m_packetSize));
197 
198  ApplicationContainer apps = app.Install (nc);
199  apps.Start (Seconds (0.5));
200  Time nextEvent = Seconds (0.5);
201 
202 
203  for (uint32_t cw = m_cwMin; cw <= m_cwMax; cw += m_cwStep)
204  {
205 
206  for (uint32_t an = 0; an < m_avgs; an++)
207  {
208  nextEvent += m_simTime;
209  Simulator::Schedule (nextEvent, &Experiment::ResetData, this);
210  Simulator::Schedule (nextEvent, &Experiment::UpdatePositions, this, nc);
211  }
212  Simulator::Schedule (nextEvent, &Experiment::IncrementCw, this, cw);
213  }
214  apps.Stop (nextEvent + m_simTime);
215 
216  Ptr<Node> sinkNode = sink.Get (0);
217  TypeId psfid = TypeId::LookupByName ("ns3::PacketSocketFactory");
218  if (sinkNode->GetObject<SocketFactory> (psfid) == 0)
219  {
220  Ptr<PacketSocketFactory> psf = CreateObject<PacketSocketFactory> ();
221  sinkNode->AggregateObject (psf);
222  }
223  Ptr<Socket> sinkSocket = Socket::CreateSocket (sinkNode, psfid);
224  sinkSocket->Bind (socket);
226 
227  m_bytesTotal = 0;
228 
229  std::ofstream ascii (m_asciitracefile.c_str ());
230  if (!ascii.is_open ())
231  {
232  NS_FATAL_ERROR ("Could not open ascii trace file: "
233  << m_asciitracefile);
234  }
235  uan.EnableAsciiAll (ascii);
236 
237  Simulator::Run ();
238  sinkNode = 0;
239  sinkSocket = 0;
240  pos = 0;
241  channel = 0;
242  prop = 0;
243  for (uint32_t i=0; i < nc.GetN (); i++)
244  {
245  nc.Get (i) = 0;
246  }
247  for (uint32_t i=0; i < sink.GetN (); i++)
248  {
249  sink.Get (i) = 0;
250  }
251 
252  for (uint32_t i=0; i < devices.GetN (); i++)
253  {
254  devices.Get (i) = 0;
255  }
256  for (uint32_t i=0; i < sinkdev.GetN (); i++)
257  {
258  sinkdev.Get (i) = 0;
259  }
260 
261  Simulator::Destroy ();
262  return m_data;
263  }
264 }
265 
266 int
267 main (int argc, char **argv)
268 {
269 
270  LogComponentEnable ("UanCwExample", LOG_LEVEL_ALL);
271 
272  Experiment exp;
273 
274  std::string gnudatfile ("cwexpgnuout.dat");
275  std::string perModel = "ns3::UanPhyPerGenDefault";
276  std::string sinrModel = "ns3::UanPhyCalcSinrDefault";
277 
278  CommandLine cmd;
279  cmd.AddValue ("NumNodes", "Number of transmitting nodes", exp.m_numNodes);
280  cmd.AddValue ("Depth", "Depth of transmitting and sink nodes", exp.m_depth);
281  cmd.AddValue ("RegionSize", "Size of boundary in meters", exp.m_boundary);
282  cmd.AddValue ("PacketSize", "Generated packet size in bytes", exp.m_packetSize);
283  cmd.AddValue ("DataRate", "DataRate in bps", exp.m_dataRate);
284  cmd.AddValue ("CwMin", "Min CW to simulate", exp.m_cwMin);
285  cmd.AddValue ("CwMax", "Max CW to simulate", exp.m_cwMax);
286  cmd.AddValue ("SlotTime", "Slot time duration", exp.m_slotTime);
287  cmd.AddValue ("Averages", "Number of topologies to test for each cw point", exp.m_avgs);
288  cmd.AddValue ("GnuFile", "Name for GNU Plot output", exp.m_gnudatfile);
289  cmd.AddValue ("PerModel", "PER model name", perModel);
290  cmd.AddValue ("SinrModel", "SINR model name", sinrModel);
291  cmd.Parse (argc, argv);
292 
293  ObjectFactory obf;
294  obf.SetTypeId (perModel);
295  Ptr<UanPhyPer> per = obf.Create<UanPhyPer> ();
296  obf.SetTypeId (sinrModel);
298 
299  UanHelper uan;
300  UanTxMode mode;
301  mode = UanTxModeFactory::CreateMode (UanTxMode::FSK, exp.m_dataRate,
302  exp.m_dataRate, 12000,
303  exp.m_dataRate, 2,
304  "Default mode");
305  UanModesList myModes;
306  myModes.AppendMode (mode);
307 
308  uan.SetPhy ("ns3::UanPhyGen",
309  "PerModel", PointerValue (per),
310  "SinrModel", PointerValue (sinr),
311  "SupportedModes", UanModesListValue (myModes));
312 
313  Gnuplot gp;
314  Gnuplot2dDataset ds;
315  ds = exp.Run (uan);
316 
317  gp.AddDataset (ds);
318 
319  std::ofstream of (exp.m_gnudatfile.c_str ());
320  if (!of.is_open ())
321  {
322  NS_FATAL_ERROR ("Can not open GNU Plot outfile: " << exp.m_gnudatfile);
323  }
324  gp.GenerateOutput (of);
325 
326  per = 0;
327  sinr = 0;
328 
329 }
330 
UAN configuration helper.
Definition: uan-helper.h:39
Helper class for UAN CW MAC example.
Definition: multirate.cc:71
holds a vector of ns3::Application pointers.
int main(int argc, char **argv)
keep track of time values and allow control of global simulation resolution
Definition: nstime.h:81
uint32_t m_bytesTotal
Total bytes received.
Definition: wifi-adhoc.cc:48
tuple devices
Definition: first.py:32
Vector GetPosition(Ptr< Node > node)
Definition: wifi-adhoc.cc:70
NS_LOG_COMPONENT_DEFINE("GrantedTimeWindowMpiInterface")
Class to represent a 2D points plot.
Definition: gnuplot.h:113
std::vector< Ptr< Node > >::const_iterator Iterator
hold variables of type string
Definition: string.h:19
Ptr< NetDevice > Get(uint32_t i) const
Get the Ptr stored in this container at a given index.
Time m_slotTime
Slot time duration.
an address for a packet socket
#define NS_ASSERT(condition)
Definition: assert.h:64
void SetTypeId(TypeId tid)
uint32_t GetSize(void) const
Definition: packet.h:650
void IncrementCw(uint32_t cw)
Compute average throughput for a set of runs, then increment CW.
void AddDataset(const GnuplotDataset &dataset)
Definition: gnuplot.cc:756
Iterator End(void) const
Get an iterator which indicates past-the-last Node in the container.
Container for UanTxModes.
Definition: uan-tx-mode.h:255
uint32_t m_avgs
Number of topologies to test for each cw point.
void Set(std::string path, const AttributeValue &value)
Definition: config.cc:662
void ReceivePacket(Ptr< Socket > socket)
Definition: multirate.cc:165
Object to create transport layer instances that provide a socket API to applications.
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
Definition: on-off-helper.h:42
a 3d vector
Definition: vector.h:31
Give ns3::PacketSocket powers to ns3::Node.
void SetSingleDevice(uint32_t device)
std::string m_gnudatfile
Name for GNU Plot output, default uan-cw-example.gpl.
#define NS_FATAL_ERROR(msg)
fatal error handling
Definition: fatal-error.h:72
a polymophic address class
Definition: address.h:86
uint32_t GetN(void) const
Get the number of Ptr stored in this container.
uint32_t GetN(void) const
Get the number of Ptr stored in this container.
tuple nodes
Definition: first.py:25
Keep track of the current position and velocity of an object.
double GetSeconds(void) const
Definition: nstime.h:274
double m_depth
Depth of transmitting and sink nodes.
uint32_t m_cwMin
Min CW to simulate.
void Install(Ptr< Node > node) const
"Layout" a single node according to the current position allocator type.
a simple class to generate gnuplot-ready plotting commands from a set of datasets.
Definition: gnuplot.h:367
void SetMac(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())
Set MAC attributes.
Definition: uan-helper.cc:91
hold objects of type ns3::Time
Definition: nstime.h:961
Ptr< Object > Create(void) const
Hold an unsigned integer type.
Definition: uinteger.h:46
Gnuplot2dDataset Run(const WifiHelper &wifi, const YansWifiPhyHelper &wifiPhy, const NqosWifiMacHelper &wifiMac, const YansWifiChannelHelper &wifiChannel, const MobilityHelper &mobility)
Definition: multirate.cc:373
Abstraction of packet modulation information.
Definition: uan-tx-mode.h:41
holds a vector of ns3::NetDevice pointers
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1238
void GenerateOutput(std::ostream &os)
Writes gnuplot commands and data values to a single output stream.
Definition: gnuplot.cc:762
Calculate packet error probability, based on received SINR and modulation (mode). ...
Definition: uan-phy.h:110
Gnuplot2dDataset m_data
Container for the simulation data.
void Add(double x, double y)
Definition: gnuplot.cc:359
void SetRecvCallback(Callback< void, Ptr< Socket > >)
Notify application when new data is available to be read.
Definition: socket.cc:128
std::vector< double > m_throughputs
Throughput for each run.
void Start(Time start)
Arrange for all of the Applications in this container to Start() at the Time given as a parameter...
void AggregateObject(Ptr< Object > other)
Definition: object.cc:243
Parse command-line arguments.
Definition: command-line.h:152
Time m_simTime
Simulation run time, default 1000 s.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
void SetPhysicalAddress(const Address address)
std::string m_asciitracefile
Name for ascii trace file, default uan-cw-example.asc.
keep track of a set of node pointers.
hold objects of type Ptr
Definition: pointer.h:33
virtual Ptr< Packet > Recv(uint32_t maxSize, uint32_t flags)=0
Read data from the socket.
Iterator Begin(void) const
Get an iterator which refers to the first Node in the container.
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())
double GetValue(double min, double max)
Returns a random double from the uniform distribution with the specified range.
void Install(Ptr< Node > node) const
Aggregate an instance of a ns3::PacketSocketFactory onto the provided node.
static void EnableAsciiAll(std::ostream &os)
Enable ascii output on each device which is of the ns3::UanNetDevice type and dump that to the specif...
Definition: uan-helper.cc:202
void SetPosition(const Vector &position)
Class used for calculating SINR of packet in UanPhy.
Definition: uan-phy.h:44
uint32_t m_cwMax
Max CW to simulate.
double m_boundary
Size of boundary in meters.
Helper class used to assign positions and mobility models to nodes.
instantiate subclasses of ns3::Object.
void Stop(Time stop)
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter...
uint32_t m_packetSize
Generated packet size in bytes.
hold objects of type ns3::DataRate
void AddValue(const std::string &name, const std::string &help, T &value)
Add a program argument, assigning to POD.
Definition: command-line.h:408
Time Now(void)
create an ns3::Time instance which contains the current simulation time.
Definition: simulator.cc:287
Ptr< Node > Get(uint32_t i) const
Get the Ptr stored in this container at a given index.
#define NS_LOG_DEBUG(msg)
Definition: log.h:289
void AppendMode(UanTxMode mode)
Add mode to this list.
Definition: uan-tx-mode.cc:232
uint32_t m_cwStep
CW step size, default 10.
void SetProtocol(uint16_t protocol)
void Parse(int argc, char *argv[])
Parse the program arguments.
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
void SetPositionAllocator(Ptr< PositionAllocator > allocator)
Set the position allocator which will be used to allocate the initial position of every node initiali...
NetDeviceContainer Install(NodeContainer c) const
This method creates a simple ns3::UanChannel (with a default ns3::UanNoiseModelDefault and ns3::UanPr...
Definition: uan-helper.cc:208
uint32_t m_dataRate
DataRate in bps.
void UpdatePositions(NodeContainer &nodes)
Assign new random positions to a set of nodes.
Ptr< T > GetObject(void) const
Definition: object.h:361
ApplicationContainer Install(NodeContainer c) const
Install an ns3::OnOffApplication on each node of the input container configured with all the attribut...
a unique identifier for an interface.
Definition: type-id.h:49
void SetAttribute(std::string name, const AttributeValue &value)
Helper function used to set the underlying application attributes.
uint32_t m_numNodes
Number of transmitting nodes.
void LogComponentEnable(char const *name, enum LogLevel level)
Definition: log.cc:311
Attribute Value class for UanTxModes.
void ResetData()
Save the throughput from a single run.