A Discrete-Event Network Simulator
API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
wifi-example-sim.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 /*
3  * This program is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License version 2 as
5  * published by the Free Software Foundation;
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15  *
16  * Authors: Joe Kopena <tjkopena@cs.drexel.edu>
17  *
18  * This program conducts a simple experiment: It places two nodes at a
19  * parameterized distance apart. One node generates packets and the
20  * other node receives. The stat framework collects data on packet
21  * loss. Outside of this program, a control script uses that data to
22  * produce graphs presenting performance at the varying distances.
23  * This isn't a typical simulation but is a common "experiment"
24  * performed in real life and serves as an accessible exemplar for the
25  * stat framework. It also gives some intuition on the behavior and
26  * basic reasonability of the NS-3 WiFi models.
27  *
28  * Applications used by this program are in test02-apps.h and
29  * test02-apps.cc, which should be in the same place as this file.
30  *
31  */
32 
33 #include <ctime>
34 
35 #include <sstream>
36 
37 #include "ns3/core-module.h"
38 #include "ns3/network-module.h"
39 #include "ns3/mobility-module.h"
40 #include "ns3/wifi-module.h"
41 #include "ns3/internet-module.h"
42 
43 #include "ns3/stats-module.h"
44 
45 #include "wifi-example-apps.h"
46 
47 using namespace ns3;
48 using namespace std;
49 
50 NS_LOG_COMPONENT_DEFINE ("WiFiDistanceExperiment");
51 
52 
53 
54 
56  std::string path, Ptr<const Packet> packet) {
57  NS_LOG_INFO ("Sent frame counted in " <<
58  datac->GetKey ());
59  datac->Update ();
60  // end TxCallback
61 }
62 
63 
64 
65 
66 //----------------------------------------------------------------------
67 //-- main
68 //----------------------------------------------
69 int main (int argc, char *argv[]) {
70 
71  double distance = 50.0;
72  string format ("omnet");
73 
74  string experiment ("wifi-distance-test");
75  string strategy ("wifi-default");
76  string input;
77  string runID;
78 
79  {
80  stringstream sstr;
81  sstr << "run-" << time (NULL);
82  runID = sstr.str ();
83  }
84 
85  // Set up command line parameters used to control the experiment.
86  CommandLine cmd;
87  cmd.AddValue ("distance", "Distance apart to place nodes (in meters).",
88  distance);
89  cmd.AddValue ("format", "Format to use for data output.",
90  format);
91  cmd.AddValue ("experiment", "Identifier for experiment.",
92  experiment);
93  cmd.AddValue ("strategy", "Identifier for strategy.",
94  strategy);
95  cmd.AddValue ("run", "Identifier for run.",
96  runID);
97  cmd.Parse (argc, argv);
98 
99  if (format != "omnet" && format != "db") {
100  NS_LOG_ERROR ("Unknown output format '" << format << "'");
101  return -1;
102  }
103 
104  #ifndef STATS_HAS_SQLITE3
105  if (format == "db") {
106  NS_LOG_ERROR ("sqlite support not compiled in.");
107  return -1;
108  }
109  #endif
110 
111  {
112  stringstream sstr ("");
113  sstr << distance;
114  input = sstr.str ();
115  }
116 
117 
118 
119 
120  //------------------------------------------------------------
121  //-- Create nodes and network stacks
122  //--------------------------------------------
123  NS_LOG_INFO ("Creating nodes.");
125  nodes.Create (2);
126 
127  NS_LOG_INFO ("Installing WiFi and Internet stack.");
130  wifiMac.SetType ("ns3::AdhocWifiMac");
133  wifiPhy.SetChannel (wifiChannel.Create ());
134  NetDeviceContainer nodeDevices = wifi.Install (wifiPhy, wifiMac, nodes);
135 
136  InternetStackHelper internet;
137  internet.Install (nodes);
138  Ipv4AddressHelper ipAddrs;
139  ipAddrs.SetBase ("192.168.0.0", "255.255.255.0");
140  ipAddrs.Assign (nodeDevices);
141 
142 
143 
144 
145  //------------------------------------------------------------
146  //-- Setup physical layout
147  //--------------------------------------------
148  NS_LOG_INFO ("Installing static mobility; distance " << distance << " .");
149  MobilityHelper mobility;
150  Ptr<ListPositionAllocator> positionAlloc =
151  CreateObject<ListPositionAllocator>();
152  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
153  positionAlloc->Add (Vector (0.0, distance, 0.0));
154  mobility.SetPositionAllocator (positionAlloc);
155  mobility.Install (nodes);
156 
157 
158 
159 
160  //------------------------------------------------------------
161  //-- Create a custom traffic source and sink
162  //--------------------------------------------
163  NS_LOG_INFO ("Create traffic source & sink.");
164  Ptr<Node> appSource = NodeList::GetNode (0);
165  Ptr<Sender> sender = CreateObject<Sender>();
166  appSource->AddApplication (sender);
167  sender->SetStartTime (Seconds (1));
168 
169  Ptr<Node> appSink = NodeList::GetNode (1);
170  Ptr<Receiver> receiver = CreateObject<Receiver>();
171  appSink->AddApplication (receiver);
172  receiver->SetStartTime (Seconds (0));
173 
174  Config::Set ("/NodeList/*/ApplicationList/*/$Sender/Destination",
175  Ipv4AddressValue ("192.168.0.2"));
176 
177 
178 
179 
180  //------------------------------------------------------------
181  //-- Setup stats and data collection
182  //--------------------------------------------
183 
184  // Create a DataCollector object to hold information about this run.
186  data.DescribeRun (experiment,
187  strategy,
188  input,
189  runID);
190 
191  // Add any information we wish to record about this run.
192  data.AddMetadata ("author", "tjkopena");
193 
194 
195  // Create a counter to track how many frames are generated. Updates
196  // are triggered by the trace signal generated by the WiFi MAC model
197  // object. Here we connect the counter to the signal via the simple
198  // TxCallback() glue function defined above.
200  CreateObject<CounterCalculator<uint32_t> >();
201  totalTx->SetKey ("wifi-tx-frames");
202  totalTx->SetContext ("node[0]");
203  Config::Connect ("/NodeList/0/DeviceList/*/$ns3::WifiNetDevice/Mac/MacTx",
204  MakeBoundCallback (&TxCallback, totalTx));
205  data.AddDataCalculator (totalTx);
206 
207  // This is similar, but creates a counter to track how many frames
208  // are received. Instead of our own glue function, this uses a
209  // method of an adapter class to connect a counter directly to the
210  // trace signal generated by the WiFi MAC.
212  CreateObject<PacketCounterCalculator>();
213  totalRx->SetKey ("wifi-rx-frames");
214  totalRx->SetContext ("node[1]");
215  Config::Connect ("/NodeList/1/DeviceList/*/$ns3::WifiNetDevice/Mac/MacRx",
217  totalRx));
218  data.AddDataCalculator (totalRx);
219 
220 
221 
222 
223  // This counter tracks how many packets---as opposed to frames---are
224  // generated. This is connected directly to a trace signal provided
225  // by our Sender class.
227  CreateObject<PacketCounterCalculator>();
228  appTx->SetKey ("sender-tx-packets");
229  appTx->SetContext ("node[0]");
230  Config::Connect ("/NodeList/0/ApplicationList/*/$Sender/Tx",
232  appTx));
233  data.AddDataCalculator (appTx);
234 
235  // Here a counter for received packets is directly manipulated by
236  // one of the custom objects in our simulation, the Receiver
237  // Application. The Receiver object is given a pointer to the
238  // counter and calls its Update() method whenever a packet arrives.
239  Ptr<CounterCalculator<> > appRx =
240  CreateObject<CounterCalculator<> >();
241  appRx->SetKey ("receiver-rx-packets");
242  appRx->SetContext ("node[1]");
243  receiver->SetCounter (appRx);
244  data.AddDataCalculator (appRx);
245 
246 
247 
248 
262  // This DataCalculator connects directly to the transmit trace
263  // provided by our Sender Application. It records some basic
264  // statistics about the sizes of the packets received (min, max,
265  // avg, total # bytes), although in this scenaro they're fixed.
267  CreateObject<PacketSizeMinMaxAvgTotalCalculator>();
268  appTxPkts->SetKey ("tx-pkt-size");
269  appTxPkts->SetContext ("node[0]");
270  Config::Connect ("/NodeList/0/ApplicationList/*/$Sender/Tx",
273  appTxPkts));
274  data.AddDataCalculator (appTxPkts);
275 
276 
277  // Here we directly manipulate another DataCollector tracking min,
278  // max, total, and average propagation delays. Check out the Sender
279  // and Receiver classes to see how packets are tagged with
280  // timestamps to do this.
282  CreateObject<TimeMinMaxAvgTotalCalculator>();
283  delayStat->SetKey ("delay");
284  delayStat->SetContext (".");
285  receiver->SetDelayTracker (delayStat);
286  data.AddDataCalculator (delayStat);
287 
288 
289 
290 
291  //------------------------------------------------------------
292  //-- Run the simulation
293  //--------------------------------------------
294  NS_LOG_INFO ("Run Simulation.");
295  Simulator::Run ();
296 
297 
298 
299 
300  //------------------------------------------------------------
301  //-- Generate statistics output.
302  //--------------------------------------------
303 
304  // Pick an output writer based in the requested format.
306  if (format == "omnet") {
307  NS_LOG_INFO ("Creating omnet formatted data output.");
308  output = CreateObject<OmnetDataOutput>();
309  } else if (format == "db") {
310  #ifdef STATS_HAS_SQLITE3
311  NS_LOG_INFO ("Creating sqlite formatted data output.");
312  output = CreateObject<SqliteDataOutput>();
313  #endif
314  } else {
315  NS_LOG_ERROR ("Unknown output format " << format);
316  }
317 
318  // Finally, have that writer interrogate the DataCollector and save
319  // the results.
320  if (output != 0)
321  output->Output (data);
322 
323  // Free any memory here at the end of this example.
325 
326  // end main
327 }
uint32_t AddApplication(Ptr< Application > application)
Definition: node.cc:149
void experiment(bool enableCtsRts)
Run single 10 seconds experiment with enabled or disabled RTS/CTS mechanism.
smart pointer class similar to boost::intrusive_ptr
Definition: ptr.h:60
Ptr< YansWifiChannel > Create(void) const
virtual void Output(DataCollector &dc)=0
Outputs information from the provided DataCollector.
static Ptr< Node > GetNode(uint32_t n)
Definition: node-list.cc:240
Make it easy to create and manage PHY objects for the yans model.
static YansWifiChannelHelper Default(void)
Create a channel helper in a default working state.
void SetKey(const std::string key)
Sets the DataCalculator key to the provided key.
Callback< R > MakeBoundCallback(R(*fnPtr)(TX), ARG a1)
Build bound Callbacks which take varying numbers of arguments, and potentially returning a value...
Definition: callback.h:1467
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 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.
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:223
void Set(std::string path, const AttributeValue &value)
Definition: config.cc:662
static YansWifiPhyHelper Default(void)
Create a phy helper in a default working state.
void Connect(std::string path, const CallbackBase &cb)
Definition: config.cc:728
helps to create WifiNetDevice objects
Definition: wifi-helper.h:88
void TxCallback(Ptr< CounterCalculator< uint32_t > > datac, std::string path, Ptr< const Packet > packet)
a 3d vector
Definition: vector.h:31
void PacketUpdate(std::string path, Ptr< const Packet > packet)
Increments the packet stats by the size of the packet.
virtual NetDeviceContainer Install(const WifiPhyHelper &phy, const WifiMacHelper &mac, NodeContainer c) const
Definition: wifi-helper.cc:102
tuple nodes
Definition: first.py:25
void SetChannel(Ptr< YansWifiChannel > channel)
void Install(Ptr< Node > node) const
"Layout" a single node according to the current position allocator type.
uint8_t data[writeSize]
void AddDataCalculator(Ptr< DataCalculator > datac)
Add a DataCalculator object to the DataCollector.
holds a vector of ns3::NetDevice pointers
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1242
void AddMetadata(std::string key, std::string value)
Add the key and the value as a pair of strings to the metadata list.
static NqosWifiMacHelper Default(void)
Create a mac helper in a default working state.
create non QoS-enabled MAC layers for a ns3::WifiNetDevice.
Parse command-line arguments.
Definition: command-line.h:177
static void Destroy(void)
Every event scheduled by the Simulator::insertAtDestroy method is invoked.
Definition: simulator.cc:121
keep track of a set of node pointers.
void PacketUpdate(std::string path, Ptr< const Packet > packet)
Increments the packet counter by one.
void Install(std::string nodeName) const
Aggregate implementations of the ns3::Ipv4, ns3::Ipv6, ns3::Udp, and ns3::Tcp classes onto the provid...
void SetDelayTracker(Ptr< TimeMinMaxAvgTotalCalculator > delay)
manage and create wifi channel objects for the yans model.
hold objects of type ns3::Ipv4Address
Helper class used to assign positions and mobility models to nodes.
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
void AddValue(const std::string &name, const std::string &help, T &value)
Add a program argument, assigning to POD.
Definition: command-line.h:435
Collects data.
void SetContext(const std::string context)
Sets the DataCalculator context to the provided context.
void DescribeRun(std::string experiment, std::string strategy, std::string input, std::string runID, std::string description="")
Provide specific parameters to the DataCollector.
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.
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
Definition: log.h:193
EventId output
void Create(uint32_t n)
Create n nodes and append pointers to them to the end of this NodeContainer.
int main(int argc, char *argv[])
void SetPositionAllocator(Ptr< PositionAllocator > allocator)
Set the position allocator which will be used to allocate the initial position of every node initiali...
void SetStartTime(Time start)
Specify application start time.
Definition: application.cc:68
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
static WifiHelper Default(void)
Definition: wifi-helper.cc:65
void SetCounter(Ptr< CounterCalculator<> > calc)