A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
uan-cw-example.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2009 University of Washington
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Leonard Tracy <lentracy@gmail.com>
7 */
8
9/**
10 * @file uan-cw-example.cc
11 * @ingroup uan
12 *
13 * This example showcases the "CW-MAC" described in System Design Considerations
14 * for Undersea Networks article in the IEEE Journal on Selected Areas of
15 * Communications 2008 by Nathan Parrish, Leonard Tracy and Sumit Roy.
16 * The MAC protocol is implemented in the class UanMacCw. CW-MAC is similar
17 * in nature to the IEEE 802.11 DCF with a constant backoff window.
18 * It requires two parameters to be set, the slot time and
19 * the contention window size. The contention window size is
20 * the backoff window size in slots, and the slot time is
21 * the duration of each slot. These parameters should be set
22 * according to the overall network size, internode spacing and
23 * the number of nodes in the network.
24 *
25 * This example deploys nodes randomly (according to RNG seed of course)
26 * in a finite square region with the X and Y coordinates of the nodes
27 * distributed uniformly. The CW parameter is varied throughout
28 * the simulation in order to show the variation in throughput
29 * with respect to changes in CW.
30 */
31
32#include "uan-cw-example.h"
33
34#include "ns3/applications-module.h"
35#include "ns3/core-module.h"
36#include "ns3/mobility-module.h"
37#include "ns3/network-module.h"
38#include "ns3/stats-module.h"
39
40#include <fstream>
41
42using namespace ns3;
43
44NS_LOG_COMPONENT_DEFINE("UanCwExample");
45
47 : m_numNodes(15),
48 m_dataRate(80),
49 m_depth(70),
50 m_boundary(500),
51 m_packetSize(32),
52 m_bytesTotal(0),
53 m_cwMin(10),
54 m_cwMax(400),
55 m_cwStep(10),
56 m_avgs(3),
57 m_slotTime(Seconds(0.2)),
58 m_simTime(Seconds(1000)),
59 m_gnudatfile("uan-cw-example.gpl"),
60 m_asciitracefile("uan-cw-example.asc"),
61 m_bhCfgFile("uan-apps/dat/default.cfg")
62{
63}
64
65void
67{
68 NS_LOG_DEBUG(Now().As(Time::S) << " Resetting data");
70 m_bytesTotal = 0;
71}
72
73void
75{
77
78 double avgThroughput = 0.0;
79 for (uint32_t i = 0; i < m_avgs; i++)
80 {
81 avgThroughput += m_throughputs[i];
82 }
83 avgThroughput /= m_avgs;
84 m_data.Add(cw, avgThroughput);
85 m_throughputs.clear();
86
87 Config::Set("/NodeList/*/DeviceList/*/Mac/CW", UintegerValue(cw + m_cwStep));
88
90
91 NS_LOG_DEBUG("Average for cw=" << cw << " over " << m_avgs << " runs: " << avgThroughput);
92}
93
94void
96{
97 NS_LOG_DEBUG(Now().As(Time::S) << " Updating positions");
98 auto it = nodes.Begin();
100 for (; it != nodes.End(); it++)
101 {
102 Ptr<MobilityModel> mp = (*it)->GetObject<MobilityModel>();
103 mp->SetPosition(Vector(uv->GetValue(0, m_boundary), uv->GetValue(0, m_boundary), 70.0));
104 }
105}
106
107void
109{
110 Ptr<Packet> packet;
111
112 while ((packet = socket->Recv()))
113 {
114 m_bytesTotal += packet->GetSize();
115 }
116 packet = nullptr;
117}
118
121{
122 uan.SetMac("ns3::UanMacCw", "CW", UintegerValue(m_cwMin), "SlotTime", TimeValue(m_slotTime));
125 nc.Create(m_numNodes);
126 sink.Create(1);
127
128 PacketSocketHelper socketHelper;
129 socketHelper.Install(nc);
130 socketHelper.Install(sink);
131
132#ifdef UAN_PROP_BH_INSTALLED
134 CreateObjectWithAttributes<UanPropModelBh>("ConfigFile", StringValue("exbhconfig.cfg"));
135#else
137#endif // UAN_PROP_BH_INSTALLED
138 Ptr<UanChannel> channel =
139 CreateObjectWithAttributes<UanChannel>("PropagationModel", PointerValue(prop));
140
141 // Create net device and nodes with UanHelper
142 NetDeviceContainer devices = uan.Install(nc, channel);
143 NetDeviceContainer sinkdev = uan.Install(sink, channel);
144
145 MobilityHelper mobility;
147
148 {
150 pos->Add(Vector(m_boundary / 2.0, m_boundary / 2.0, m_depth));
151 double rsum = 0;
152
153 double minr = 2 * m_boundary;
154 for (uint32_t i = 0; i < m_numNodes; i++)
155 {
156 double x = urv->GetValue(0, m_boundary);
157 double y = urv->GetValue(0, m_boundary);
158 double newr = std::sqrt((x - m_boundary / 2.0) * (x - m_boundary / 2.0) +
159 (y - m_boundary / 2.0) * (y - m_boundary / 2.0));
160 rsum += newr;
161 minr = std::min(minr, newr);
162 pos->Add(Vector(x, y, m_depth));
163 }
164 NS_LOG_DEBUG("Mean range from gateway: " << rsum / m_numNodes << " min. range " << minr);
165
166 mobility.SetPositionAllocator(pos);
167 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
168 mobility.Install(sink);
169
171 "Position of sink: " << sink.Get(0)->GetObject<MobilityModel>()->GetPosition());
172 mobility.Install(nc);
173
174 PacketSocketAddress socket;
175 socket.SetSingleDevice(sinkdev.Get(0)->GetIfIndex());
176 socket.SetPhysicalAddress(sinkdev.Get(0)->GetAddress());
177 socket.SetProtocol(0);
178
179 OnOffHelper app("ns3::PacketSocketFactory", Address(socket));
180 app.SetAttribute("OnTime", StringValue("ns3::ConstantRandomVariable[Constant=1]"));
181 app.SetAttribute("OffTime", StringValue("ns3::ConstantRandomVariable[Constant=0]"));
182 app.SetAttribute("DataRate", DataRateValue(m_dataRate));
183 app.SetAttribute("PacketSize", UintegerValue(m_packetSize));
184
185 ApplicationContainer apps = app.Install(nc);
186 apps.Start(Seconds(0.5));
187 Time nextEvent = Seconds(0.5);
188
189 for (uint32_t cw = m_cwMin; cw <= m_cwMax; cw += m_cwStep)
190 {
191 for (uint32_t an = 0; an < m_avgs; an++)
192 {
193 nextEvent += m_simTime;
196 }
197 Simulator::Schedule(nextEvent, &Experiment::IncrementCw, this, cw);
198 }
199 apps.Stop(nextEvent + m_simTime);
200
201 Ptr<Node> sinkNode = sink.Get(0);
202 TypeId psfid = TypeId::LookupByName("ns3::PacketSocketFactory");
203 if (!sinkNode->GetObject<SocketFactory>(psfid))
204 {
206 sinkNode->AggregateObject(psf);
207 }
208 Ptr<Socket> sinkSocket = Socket::CreateSocket(sinkNode, psfid);
209 sinkSocket->Bind(socket);
210 sinkSocket->SetRecvCallback(MakeCallback(&Experiment::ReceivePacket, this));
211
212 m_bytesTotal = 0;
213
214 std::ofstream ascii(m_asciitracefile);
215 if (!ascii.is_open())
216 {
217 NS_FATAL_ERROR("Could not open ascii trace file: " << m_asciitracefile);
218 }
220
222 sinkNode = nullptr;
223 sinkSocket = nullptr;
224 pos = nullptr;
225 channel = nullptr;
226 prop = nullptr;
227 for (uint32_t i = 0; i < nc.GetN(); i++)
228 {
229 nc.Get(i) = nullptr;
230 }
231 for (uint32_t i = 0; i < sink.GetN(); i++)
232 {
233 sink.Get(i) = nullptr;
234 }
235
236 for (uint32_t i = 0; i < devices.GetN(); i++)
237 {
238 devices.Get(i) = nullptr;
239 }
240 for (uint32_t i = 0; i < sinkdev.GetN(); i++)
241 {
242 sinkdev.Get(i) = nullptr;
243 }
244
246 return m_data;
247 }
248}
249
250int
251main(int argc, char** argv)
252{
253 Experiment exp;
254 bool quiet = false;
255
256 std::string gnudatfile("cwexpgnuout.dat");
257 std::string perModel = "ns3::UanPhyPerGenDefault";
258 std::string sinrModel = "ns3::UanPhyCalcSinrDefault";
259
260 CommandLine cmd(__FILE__);
261 cmd.AddValue("NumNodes", "Number of transmitting nodes", exp.m_numNodes);
262 cmd.AddValue("Depth", "Depth of transmitting and sink nodes", exp.m_depth);
263 cmd.AddValue("RegionSize", "Size of boundary in meters", exp.m_boundary);
264 cmd.AddValue("PacketSize", "Generated packet size in bytes", exp.m_packetSize);
265 cmd.AddValue("DataRate", "DataRate in bps", exp.m_dataRate);
266 cmd.AddValue("CwMin", "Min CW to simulate", exp.m_cwMin);
267 cmd.AddValue("CwMax", "Max CW to simulate", exp.m_cwMax);
268 cmd.AddValue("SlotTime", "Slot time duration", exp.m_slotTime);
269 cmd.AddValue("Averages", "Number of topologies to test for each cw point", exp.m_avgs);
270 cmd.AddValue("GnuFile", "Name for GNU Plot output", exp.m_gnudatfile);
271 cmd.AddValue("PerModel", "PER model name", perModel);
272 cmd.AddValue("SinrModel", "SINR model name", sinrModel);
273 cmd.AddValue("Quiet", "Run in quiet mode (disable logging)", quiet);
274 cmd.Parse(argc, argv);
275
276 if (!quiet)
277 {
278 LogComponentEnable("UanCwExample", LOG_LEVEL_ALL);
279 }
280
281 ObjectFactory obf;
282 obf.SetTypeId(perModel);
283 Ptr<UanPhyPer> per = obf.Create<UanPhyPer>();
284 obf.SetTypeId(sinrModel);
286
287 UanHelper uan;
288 UanTxMode mode;
290 exp.m_dataRate,
291 exp.m_dataRate,
292 12000,
293 exp.m_dataRate,
294 2,
295 "Default mode");
296 UanModesList myModes;
297 myModes.AppendMode(mode);
298
299 uan.SetPhy("ns3::UanPhyGen",
300 "PerModel",
301 PointerValue(per),
302 "SinrModel",
303 PointerValue(sinr),
304 "SupportedModes",
305 UanModesListValue(myModes));
306
307 Gnuplot gp;
309 ds = exp.Run(uan);
310
311 gp.AddDataset(ds);
312
313 std::ofstream of(exp.m_gnudatfile);
314 if (!of.is_open())
315 {
316 NS_FATAL_ERROR("Can not open GNU Plot outfile: " << exp.m_gnudatfile);
317 }
318 gp.GenerateOutput(of);
319
320 per = nullptr;
321 sinr = nullptr;
322
323 return 0;
324}
WiFi adhoc experiment class.
Definition wifi-adhoc.cc:34
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.
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:86
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.
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:90
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.
AttributeValue implementation for DataRate.
Definition data-rate.h:285
Class to represent a 2D points plot.
Definition gnuplot.h:105
void Add(double x, double y)
Definition gnuplot.cc:366
a simple class to generate gnuplot-ready plotting commands from a set of datasets.
Definition gnuplot.h:359
void AddDataset(const GnuplotDataset &dataset)
Definition gnuplot.cc:785
void GenerateOutput(std::ostream &os)
Writes gnuplot commands and data values to a single output stream.
Definition gnuplot.cc:791
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
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.
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
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.
AttributeValue implementation for Pointer.
Smart pointer class similar to boost::intrusive_ptr.
static void SetRun(uint64_t run)
Set the run number of simulation.
static uint64_t GetRun()
Get the current run number.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:561
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition simulator.cc:131
static void Run()
Run the simulation.
Definition simulator.cc:167
Object to create transport layer instances that provide a socket API to applications.
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
@ S
second
Definition nstime.h:105
AttributeValue implementation for Time.
Definition nstime.h:1432
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
UAN configuration helper.
Definition uan-helper.h:31
void SetMac(std::string type, Ts &&... args)
Set MAC attributes.
Definition uan-helper.h:186
NetDeviceContainer Install(NodeContainer c) const
This method creates a simple ns3::UanChannel (with a default ns3::UanNoiseModelDefault and ns3::UanPr...
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...
Container for UanTxModes.
void AppendMode(UanTxMode mode)
Add mode to this list.
AttributeValue implementation for UanModesList.
Class used for calculating SINR of packet in UanPhy.
Definition uan-phy.h:33
Calculate packet error probability, based on received SINR and modulation (mode).
Definition uan-phy.h:100
static UanTxMode CreateMode(UanTxMode::ModulationType type, uint32_t dataRateBps, uint32_t phyRateSps, uint32_t cfHz, uint32_t bwHz, uint32_t constSize, std::string name)
Abstraction of packet modulation information.
Definition uan-tx-mode.h:32
@ FSK
Frequency shift keying.
Definition uan-tx-mode.h:44
Hold an unsigned integer type.
Definition uinteger.h:34
#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 Set(std::string path, const AttributeValue &value)
Definition config.cc:872
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:257
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
Ptr< T > CreateObjectWithAttributes(Args... args)
Allocate an Object on the heap and initialize with a set of attributes.
Time Now()
create an ns3::Time instance which contains the current simulation time.
Definition simulator.cc:294
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1345
NodeContainer nodes
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
@ LOG_LEVEL_ALL
Print everything.
Definition log.h:105
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition wifi-tcp.cc:44