A Discrete-Event Network Simulator
API
uan-cw-example.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2009 University of Washington
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: Leonard Tracy <lentracy@gmail.com>
18  */
19 
43 #include "uan-cw-example.h"
44 
45 #include "ns3/applications-module.h"
46 #include "ns3/core-module.h"
47 #include "ns3/mobility-module.h"
48 #include "ns3/network-module.h"
49 #include "ns3/stats-module.h"
50 
51 #include <fstream>
52 
53 using namespace ns3;
54 
55 NS_LOG_COMPONENT_DEFINE("UanCwExample");
56 
58  : m_numNodes(15),
59  m_dataRate(80),
60  m_depth(70),
61  m_boundary(500),
62  m_packetSize(32),
63  m_bytesTotal(0),
64  m_cwMin(10),
65  m_cwMax(400),
66  m_cwStep(10),
67  m_avgs(3),
68  m_slotTime(Seconds(0.2)),
69  m_simTime(Seconds(1000)),
70  m_gnudatfile("uan-cw-example.gpl"),
71  m_asciitracefile("uan-cw-example.asc"),
72  m_bhCfgFile("uan-apps/dat/default.cfg")
73 {
74 }
75 
76 void
78 {
79  NS_LOG_DEBUG(Now().As(Time::S) << " Resetting data");
80  m_throughputs.push_back(m_bytesTotal * 8.0 / m_simTime.GetSeconds());
81  m_bytesTotal = 0;
82 }
83 
84 void
86 {
87  NS_ASSERT(m_throughputs.size() == m_avgs);
88 
89  double avgThroughput = 0.0;
90  for (uint32_t i = 0; i < m_avgs; i++)
91  {
92  avgThroughput += m_throughputs[i];
93  }
94  avgThroughput /= m_avgs;
95  m_data.Add(cw, avgThroughput);
96  m_throughputs.clear();
97 
98  Config::Set("/NodeList/*/DeviceList/*/Mac/CW", UintegerValue(cw + m_cwStep));
99 
100  SeedManager::SetRun(SeedManager::GetRun() + 1);
101 
102  NS_LOG_DEBUG("Average for cw=" << cw << " over " << m_avgs << " runs: " << avgThroughput);
103 }
104 
105 void
107 {
108  NS_LOG_DEBUG(Now().As(Time::S) << " Updating positions");
109  auto it = nodes.Begin();
110  Ptr<UniformRandomVariable> uv = CreateObject<UniformRandomVariable>();
111  for (; it != nodes.End(); it++)
112  {
114  mp->SetPosition(Vector(uv->GetValue(0, m_boundary), uv->GetValue(0, m_boundary), 70.0));
115  }
116 }
117 
118 void
120 {
121  Ptr<Packet> packet;
122 
123  while ((packet = socket->Recv()))
124  {
125  m_bytesTotal += packet->GetSize();
126  }
127  packet = nullptr;
128 }
129 
132 {
133  uan.SetMac("ns3::UanMacCw", "CW", UintegerValue(m_cwMin), "SlotTime", TimeValue(m_slotTime));
136  nc.Create(m_numNodes);
137  sink.Create(1);
138 
139  PacketSocketHelper socketHelper;
140  socketHelper.Install(nc);
141  socketHelper.Install(sink);
142 
143 #ifdef UAN_PROP_BH_INSTALLED
144  Ptr<UanPropModelBh> prop =
145  CreateObjectWithAttributes<UanPropModelBh>("ConfigFile", StringValue("exbhconfig.cfg"));
146 #else
147  Ptr<UanPropModelIdeal> prop = CreateObjectWithAttributes<UanPropModelIdeal>();
148 #endif // UAN_PROP_BH_INSTALLED
150  CreateObjectWithAttributes<UanChannel>("PropagationModel", PointerValue(prop));
151 
152  // Create net device and nodes with UanHelper
154  NetDeviceContainer sinkdev = uan.Install(sink, channel);
155 
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  NS_LOG_DEBUG("Mean range from gateway: " << rsum / m_numNodes << " min. range " << minr);
176 
177  mobility.SetPositionAllocator(pos);
178  mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
179  mobility.Install(sink);
180 
181  NS_LOG_DEBUG(
182  "Position of sink: " << sink.Get(0)->GetObject<MobilityModel>()->GetPosition());
183  mobility.Install(nc);
184 
185  PacketSocketAddress socket;
186  socket.SetSingleDevice(sinkdev.Get(0)->GetIfIndex());
187  socket.SetPhysicalAddress(sinkdev.Get(0)->GetAddress());
188  socket.SetProtocol(0);
189 
190  OnOffHelper app("ns3::PacketSocketFactory", Address(socket));
191  app.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=1]"));
192  app.SetAttribute("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0]"));
193  app.SetAttribute("DataRate", DataRateValue(m_dataRate));
194  app.SetAttribute("PacketSize", UintegerValue(m_packetSize));
195 
196  ApplicationContainer apps = app.Install(nc);
197  apps.Start(Seconds(0.5));
198  Time nextEvent = Seconds(0.5);
199 
200  for (uint32_t cw = m_cwMin; cw <= m_cwMax; cw += m_cwStep)
201  {
202  for (uint32_t an = 0; an < m_avgs; an++)
203  {
204  nextEvent += m_simTime;
205  Simulator::Schedule(nextEvent, &Experiment::ResetData, this);
206  Simulator::Schedule(nextEvent, &Experiment::UpdatePositions, this, nc);
207  }
208  Simulator::Schedule(nextEvent, &Experiment::IncrementCw, this, cw);
209  }
210  apps.Stop(nextEvent + m_simTime);
211 
212  Ptr<Node> sinkNode = sink.Get(0);
213  TypeId psfid = TypeId::LookupByName("ns3::PacketSocketFactory");
214  if (!sinkNode->GetObject<SocketFactory>(psfid))
215  {
216  Ptr<PacketSocketFactory> psf = CreateObject<PacketSocketFactory>();
217  sinkNode->AggregateObject(psf);
218  }
219  Ptr<Socket> sinkSocket = Socket::CreateSocket(sinkNode, psfid);
220  sinkSocket->Bind(socket);
222 
223  m_bytesTotal = 0;
224 
225  std::ofstream ascii(m_asciitracefile);
226  if (!ascii.is_open())
227  {
228  NS_FATAL_ERROR("Could not open ascii trace file: " << m_asciitracefile);
229  }
230  UanHelper::EnableAsciiAll(ascii);
231 
232  Simulator::Run();
233  sinkNode = nullptr;
234  sinkSocket = nullptr;
235  pos = nullptr;
236  channel = nullptr;
237  prop = nullptr;
238  for (uint32_t i = 0; i < nc.GetN(); i++)
239  {
240  nc.Get(i) = nullptr;
241  }
242  for (uint32_t i = 0; i < sink.GetN(); i++)
243  {
244  sink.Get(i) = nullptr;
245  }
246 
247  for (uint32_t i = 0; i < devices.GetN(); i++)
248  {
249  devices.Get(i) = nullptr;
250  }
251  for (uint32_t i = 0; i < sinkdev.GetN(); i++)
252  {
253  sinkdev.Get(i) = nullptr;
254  }
255 
256  Simulator::Destroy();
257  return m_data;
258  }
259 }
260 
261 int
262 main(int argc, char** argv)
263 {
264  Experiment exp;
265  bool quiet = false;
266 
267  std::string gnudatfile("cwexpgnuout.dat");
268  std::string perModel = "ns3::UanPhyPerGenDefault";
269  std::string sinrModel = "ns3::UanPhyCalcSinrDefault";
270 
271  CommandLine cmd(__FILE__);
272  cmd.AddValue("NumNodes", "Number of transmitting nodes", exp.m_numNodes);
273  cmd.AddValue("Depth", "Depth of transmitting and sink nodes", exp.m_depth);
274  cmd.AddValue("RegionSize", "Size of boundary in meters", exp.m_boundary);
275  cmd.AddValue("PacketSize", "Generated packet size in bytes", exp.m_packetSize);
276  cmd.AddValue("DataRate", "DataRate in bps", exp.m_dataRate);
277  cmd.AddValue("CwMin", "Min CW to simulate", exp.m_cwMin);
278  cmd.AddValue("CwMax", "Max CW to simulate", exp.m_cwMax);
279  cmd.AddValue("SlotTime", "Slot time duration", exp.m_slotTime);
280  cmd.AddValue("Averages", "Number of topologies to test for each cw point", exp.m_avgs);
281  cmd.AddValue("GnuFile", "Name for GNU Plot output", exp.m_gnudatfile);
282  cmd.AddValue("PerModel", "PER model name", perModel);
283  cmd.AddValue("SinrModel", "SINR model name", sinrModel);
284  cmd.AddValue("Quiet", "Run in quiet mode (disable logging)", quiet);
285  cmd.Parse(argc, argv);
286 
287  if (!quiet)
288  {
289  LogComponentEnable("UanCwExample", LOG_LEVEL_ALL);
290  }
291 
292  ObjectFactory obf;
293  obf.SetTypeId(perModel);
294  Ptr<UanPhyPer> per = obf.Create<UanPhyPer>();
295  obf.SetTypeId(sinrModel);
297 
298  UanHelper uan;
299  UanTxMode mode;
300  mode = UanTxModeFactory::CreateMode(UanTxMode::FSK,
301  exp.m_dataRate,
302  exp.m_dataRate,
303  12000,
304  exp.m_dataRate,
305  2,
306  "Default mode");
307  UanModesList myModes;
308  myModes.AppendMode(mode);
309 
310  uan.SetPhy("ns3::UanPhyGen",
311  "PerModel",
312  PointerValue(per),
313  "SinrModel",
314  PointerValue(sinr),
315  "SupportedModes",
316  UanModesListValue(myModes));
317 
318  Gnuplot gp;
319  Gnuplot2dDataset ds;
320  ds = exp.Run(uan);
321 
322  gp.AddDataset(ds);
323 
324  std::ofstream of(exp.m_gnudatfile);
325  if (!of.is_open())
326  {
327  NS_FATAL_ERROR("Can not open GNU Plot outfile: " << exp.m_gnudatfile);
328  }
329  gp.GenerateOutput(of);
330 
331  per = nullptr;
332  sinr = nullptr;
333 
334  return 0;
335 }
#define min(a, b)
Definition: 80211b.c:41
WiFi adhoc experiment class.
Definition: wifi-adhoc.cc:45
uint32_t m_packetSize
Packet size.
double m_depth
Depth of transmitting and sink nodes.
Gnuplot2dDataset Run(const WifiHelper &wifi, const YansWifiPhyHelper &wifiPhy, const WifiMacHelper &wifiMac, const YansWifiChannelHelper &wifiChannel)
Run an experiment.
Definition: wifi-adhoc.cc:162
std::string m_asciitracefile
Name for ascii trace file, default uan-cw-example.asc.
uint32_t m_cwMin
Min CW to simulate.
uint32_t m_bytesTotal
The number of received bytes.
Definition: wifi-adhoc.cc:97
Time m_simTime
Simulation run time, default 1000 s.
uint32_t m_cwMax
Max CW to simulate.
uint32_t m_avgs
Number of topologies to test for each cw point.
void ResetData()
Save the throughput from a single run.
uint32_t m_dataRate
DataRate in bps.
Gnuplot2dDataset m_data
Container for the simulation data.
void ReceivePacket(Ptr< Socket > socket)
Receive a packet.
Definition: wifi-adhoc.cc:142
Time m_slotTime
Slot time duration.
std::string m_gnudatfile
Name for GNU Plot output, default uan-cw-example.gpl.
std::vector< double > m_throughputs
Throughput for each run.
void IncrementCw(uint32_t cw)
Compute average throughput for a set of runs, then increment CW.
uint32_t m_numNodes
Number of transmitting nodes.
double m_boundary
Size of boundary in meters.
void UpdatePositions(NodeContainer &nodes) const
Assign new random positions to a set of nodes.
uint32_t m_cwStep
CW step size, default 10.
a polymophic address class
Definition: address.h:101
holds a vector of ns3::Application pointers.
void Start(Time start) const
Start all of the Applications in this container at the start time given as a parameter.
void Stop(Time stop) const
Arrange for all of the Applications in this container to Stop() at the Time given as a parameter.
Parse command-line arguments.
Definition: command-line.h:232
Class to represent a 2D points plot.
Definition: gnuplot.h:118
void Add(double x, double y)
Definition: gnuplot.cc:362
a simple class to generate gnuplot-ready plotting commands from a set of datasets.
Definition: gnuplot.h:373
void AddDataset(const GnuplotDataset &dataset)
Definition: gnuplot.cc:759
void GenerateOutput(std::ostream &os)
Writes gnuplot commands and data values to a single output stream.
Definition: gnuplot.cc:765
Helper class used to assign positions and mobility models to nodes.
Keep track of the current position and velocity of an object.
Vector GetPosition() const
void SetPosition(const Vector &position)
holds a vector of ns3::NetDevice pointers
uint32_t GetN() const
Get the number of Ptr<NetDevice> stored in this container.
Ptr< NetDevice > Get(uint32_t i) const
Get the Ptr<NetDevice> stored in this container at a given index.
keep track of a set of node pointers.
Iterator End() const
Get an iterator which indicates past-the-last Node in the container.
uint32_t GetN() const
Get the number of Ptr<Node> stored in this container.
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
Iterator Begin() const
Get an iterator which refers to the first Node in the container.
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
Instantiate subclasses of ns3::Object.
Ptr< Object > Create() const
Create an Object instance of the configured TypeId.
void SetTypeId(TypeId tid)
Set the TypeId of the Objects to be created by this factory.
Ptr< T > GetObject() const
Get a pointer to the requested aggregated Object.
Definition: object.h:471
void AggregateObject(Ptr< Object > other)
Aggregate two Objects together.
Definition: object.cc:259
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
Definition: on-off-helper.h:44
uint32_t GetSize() const
Returns the the size in bytes of the packet (including the zero-filled initial payload).
Definition: packet.h:861
an address for a packet socket
void SetProtocol(uint16_t protocol)
Set the protocol.
void SetPhysicalAddress(const Address address)
Set the destination address.
void SetSingleDevice(uint32_t device)
Set the address to match only a specified NetDevice.
Give ns3::PacketSocket powers to ns3::Node.
void Install(Ptr< Node > node) const
Aggregate an instance of a ns3::PacketSocketFactory onto the provided node.
Hold objects of type Ptr<T>.
Definition: pointer.h:37
Object to create transport layer instances that provide a socket API to applications.
void SetRecvCallback(Callback< void, Ptr< Socket >> receivedData)
Notify application when new data is available to be read.
Definition: socket.cc:128
virtual Ptr< Packet > Recv(uint32_t maxSize, uint32_t flags)=0
Read data from the socket.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
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:403
a unique identifier for an interface.
Definition: type-id.h:59
UAN configuration helper.
Definition: uan-helper.h:42
void SetMac(std::string type, Ts &&... args)
Set MAC attributes.
Definition: uan-helper.h:197
NetDeviceContainer Install(NodeContainer c) const
This method creates a simple ns3::UanChannel (with a default ns3::UanNoiseModelDefault and ns3::UanPr...
Definition: uan-helper.cc:145
Container for UanTxModes.
Definition: uan-tx-mode.h:259
void AppendMode(UanTxMode mode)
Add mode to this list.
Definition: uan-tx-mode.cc:230
Class used for calculating SINR of packet in UanPhy.
Definition: uan-phy.h:44
Calculate packet error probability, based on received SINR and modulation (mode).
Definition: uan-phy.h:110
Abstraction of packet modulation information.
Definition: uan-tx-mode.h:43
Hold an unsigned integer type.
Definition: uinteger.h:45
double GetValue(double min, double max)
Get the next random value drawn from the distribution.
#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 Set(std::string path, const AttributeValue &value)
Definition: config.cc:876
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
Definition: fatal-error.h:179
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:202
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition: log.h:268
Time Now()
create an ns3::Time instance which contains the current simulation time.
Definition: simulator.cc:305
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1326
NodeContainer nodes
devices
Definition: first.py:42
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:704
@ LOG_LEVEL_ALL
Print everything.
Definition: log.h:116
cmd
Definition: second.py:40
channel
Definition: third.py:88
mobility
Definition: third.py:105
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition: wifi-tcp.cc:55