A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
mixed-wired-wireless.cc
Go to the documentation of this file.
1/*
2 * SPDX-License-Identifier: GPL-2.0-only
3 *
4 */
5
6//
7// This ns-3 example demonstrates the use of helper functions to ease
8// the construction of simulation scenarios.
9//
10// The simulation topology consists of a mixed wired and wireless
11// scenario in which a hierarchical mobility model is used.
12//
13// The simulation layout consists of N backbone routers interconnected
14// by an ad hoc wifi network.
15// Each backbone router also has a local 802.11 network and is connected
16// to a local LAN. An additional set of (K-1) nodes are connected to
17// this backbone. Finally, a local LAN is connected to each router
18// on the backbone, with L-1 additional hosts.
19//
20// The nodes are populated with TCP/IP stacks, and OLSR unicast routing
21// on the backbone. An example UDP transfer is shown. The simulator
22// be configured to output tcpdumps or traces from different nodes.
23//
24//
25// +--------------------------------------------------------+
26// | |
27// | 802.11 ad hoc, ns-2 mobility |
28// | |
29// +--------------------------------------------------------+
30// | o o o (N backbone routers) |
31// +--------+ +--------+
32// wired LAN | mobile | wired LAN | mobile |
33// -----------| router | -----------| router |
34// --------- ---------
35// | |
36// +----------------+ +----------------+
37// | 802.11 | | 802.11 |
38// | infra net | | infra net |
39// | K-1 hosts | | K-1 hosts |
40// +----------------+ +----------------+
41//
42// We'll send data from the first wired LAN node on the first wired LAN
43// to the last wireless STA on the last infrastructure net, thereby
44// causing packets to traverse CSMA to adhoc to infrastructure links
45//
46// Note that certain mobility patterns may cause packet forwarding
47// to fail (if nodes become disconnected)
48
49#include "ns3/animation-interface.h"
50#include "ns3/command-line.h"
51#include "ns3/csma-helper.h"
52#include "ns3/internet-stack-helper.h"
53#include "ns3/ipv4-address-helper.h"
54#include "ns3/mobility-helper.h"
55#include "ns3/olsr-helper.h"
56#include "ns3/on-off-helper.h"
57#include "ns3/packet-sink-helper.h"
58#include "ns3/qos-txop.h"
59#include "ns3/ssid.h"
60#include "ns3/string.h"
61#include "ns3/yans-wifi-channel.h"
62#include "ns3/yans-wifi-helper.h"
63
64using namespace ns3;
65
66//
67// Define logging keyword for this file
68//
69NS_LOG_COMPONENT_DEFINE("MixedWireless");
70
71/**
72 * This function will be used below as a trace sink, if the command-line
73 * argument or default value "useCourseChangeCallback" is set to true
74 *
75 * \param path The callback path.
76 * \param model The mobility model.
77 */
78static void
80{
81 Vector position = model->GetPosition();
82 std::cout << "CourseChange " << path << " x=" << position.x << ", y=" << position.y
83 << ", z=" << position.z << std::endl;
84}
85
86int
87main(int argc, char* argv[])
88{
89 //
90 // First, we declare and initialize a few local variables that control some
91 // simulation parameters.
92 //
93 uint32_t backboneNodes = 10;
94 uint32_t infraNodes = 2;
95 uint32_t lanNodes = 2;
96 uint32_t stopTime = 20;
97 bool useCourseChangeCallback = false;
98
99 //
100 // Simulation defaults are typically set next, before command line
101 // arguments are parsed.
102 //
103 Config::SetDefault("ns3::OnOffApplication::PacketSize", StringValue("1472"));
104 Config::SetDefault("ns3::OnOffApplication::DataRate", StringValue("100kb/s"));
105
106 //
107 // For convenience, we add the local variables to the command line argument
108 // system so that they can be overridden with flags such as
109 // "--backboneNodes=20"
110 //
111 CommandLine cmd(__FILE__);
112 cmd.AddValue("backboneNodes", "number of backbone nodes", backboneNodes);
113 cmd.AddValue("infraNodes", "number of leaf nodes", infraNodes);
114 cmd.AddValue("lanNodes", "number of LAN nodes", lanNodes);
115 cmd.AddValue("stopTime", "simulation stop time (seconds)", stopTime);
116 cmd.AddValue("useCourseChangeCallback",
117 "whether to enable course change tracing",
118 useCourseChangeCallback);
119
120 //
121 // The system global variables and the local values added to the argument
122 // system can be overridden by command line arguments by using this call.
123 //
124 cmd.Parse(argc, argv);
125
126 if (stopTime < 10)
127 {
128 std::cout << "Use a simulation stop time >= 10 seconds" << std::endl;
129 exit(1);
130 }
131 ///////////////////////////////////////////////////////////////////////////
132 // //
133 // Construct the backbone //
134 // //
135 ///////////////////////////////////////////////////////////////////////////
136
137 //
138 // Create a container to manage the nodes of the adhoc (backbone) network.
139 // Later we'll create the rest of the nodes we'll need.
140 //
141 NodeContainer backbone;
142 backbone.Create(backboneNodes);
143 //
144 // Create the backbone wifi net devices and install them into the nodes in
145 // our container
146 //
149 mac.SetType("ns3::AdhocWifiMac");
150 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
151 "DataMode",
152 StringValue("OfdmRate54Mbps"));
153 YansWifiPhyHelper wifiPhy;
156 wifiPhy.SetChannel(wifiChannel.Create());
157 NetDeviceContainer backboneDevices = wifi.Install(wifiPhy, mac, backbone);
158
159 // We enable OLSR (which will be consulted at a higher priority than
160 // the global routing) on the backbone ad hoc nodes
161 NS_LOG_INFO("Enabling OLSR routing on all backbone nodes");
163 //
164 // Add the IPv4 protocol stack to the nodes in our container
165 //
167 internet.SetRoutingHelper(olsr); // has effect on the next Install ()
168 internet.Install(backbone);
169
170 //
171 // Assign IPv4 addresses to the device drivers (actually to the associated
172 // IPv4 interfaces) we just created.
173 //
174 Ipv4AddressHelper ipAddrs;
175 ipAddrs.SetBase("192.168.0.0", "255.255.255.0");
176 ipAddrs.Assign(backboneDevices);
177
178 //
179 // The ad-hoc network nodes need a mobility model so we aggregate one to
180 // each of the nodes we just finished building.
181 //
183 mobility.SetPositionAllocator("ns3::GridPositionAllocator",
184 "MinX",
185 DoubleValue(20.0),
186 "MinY",
187 DoubleValue(20.0),
188 "DeltaX",
189 DoubleValue(20.0),
190 "DeltaY",
191 DoubleValue(20.0),
192 "GridWidth",
193 UintegerValue(5),
194 "LayoutType",
195 StringValue("RowFirst"));
196 mobility.SetMobilityModel("ns3::RandomDirection2dMobilityModel",
197 "Bounds",
198 RectangleValue(Rectangle(-500, 500, -500, 500)),
199 "Speed",
200 StringValue("ns3::ConstantRandomVariable[Constant=2]"),
201 "Pause",
202 StringValue("ns3::ConstantRandomVariable[Constant=0.2]"));
203 mobility.Install(backbone);
204
205 ///////////////////////////////////////////////////////////////////////////
206 // //
207 // Construct the LANs //
208 // //
209 ///////////////////////////////////////////////////////////////////////////
210
211 // Reset the address base-- all of the CSMA networks will be in
212 // the "172.16 address space
213 ipAddrs.SetBase("172.16.0.0", "255.255.255.0");
214
215 for (uint32_t i = 0; i < backboneNodes; ++i)
216 {
217 NS_LOG_INFO("Configuring local area network for backbone node " << i);
218 //
219 // Create a container to manage the nodes of the LAN. We need
220 // two containers here; one with all of the new nodes, and one
221 // with all of the nodes including new and existing nodes
222 //
223 NodeContainer newLanNodes;
224 newLanNodes.Create(lanNodes - 1);
225 // Now, create the container with all nodes on this link
226 NodeContainer lan(backbone.Get(i), newLanNodes);
227 //
228 // Create the CSMA net devices and install them into the nodes in our
229 // collection.
230 //
232 csma.SetChannelAttribute("DataRate", DataRateValue(DataRate(5000000)));
233 csma.SetChannelAttribute("Delay", TimeValue(MilliSeconds(2)));
234 NetDeviceContainer lanDevices = csma.Install(lan);
235 //
236 // Add the IPv4 protocol stack to the new LAN nodes
237 //
238 internet.Install(newLanNodes);
239 //
240 // Assign IPv4 addresses to the device drivers (actually to the
241 // associated IPv4 interfaces) we just created.
242 //
243 ipAddrs.Assign(lanDevices);
244 //
245 // Assign a new network prefix for the next LAN, according to the
246 // network mask initialized above
247 //
248 ipAddrs.NewNetwork();
249 //
250 // The new LAN nodes need a mobility model so we aggregate one
251 // to each of the nodes we just finished building.
252 //
253 MobilityHelper mobilityLan;
255 for (uint32_t j = 0; j < newLanNodes.GetN(); ++j)
256 {
257 subnetAlloc->Add(Vector(0.0, j * 10 + 10, 0.0));
258 }
259 mobilityLan.PushReferenceMobilityModel(backbone.Get(i));
260 mobilityLan.SetPositionAllocator(subnetAlloc);
261 mobilityLan.SetMobilityModel("ns3::ConstantPositionMobilityModel");
262 mobilityLan.Install(newLanNodes);
263 }
264
265 ///////////////////////////////////////////////////////////////////////////
266 // //
267 // Construct the mobile networks //
268 // //
269 ///////////////////////////////////////////////////////////////////////////
270
271 // Reset the address base-- all of the 802.11 networks will be in
272 // the "10.0" address space
273 ipAddrs.SetBase("10.0.0.0", "255.255.255.0");
274
275 for (uint32_t i = 0; i < backboneNodes; ++i)
276 {
277 NS_LOG_INFO("Configuring wireless network for backbone node " << i);
278 //
279 // Create a container to manage the nodes of the LAN. We need
280 // two containers here; one with all of the new nodes, and one
281 // with all of the nodes including new and existing nodes
282 //
283 NodeContainer stas;
284 stas.Create(infraNodes - 1);
285 // Now, create the container with all nodes on this link
286 NodeContainer infra(backbone.Get(i), stas);
287 //
288 // Create an infrastructure network
289 //
290 WifiHelper wifiInfra;
291 WifiMacHelper macInfra;
292 wifiPhy.SetChannel(wifiChannel.Create());
293 // Create unique ssids for these networks
294 std::string ssidString("wifi-infra");
295 std::stringstream ss;
296 ss << i;
297 ssidString += ss.str();
298 Ssid ssid = Ssid(ssidString);
299 // setup stas
300 macInfra.SetType("ns3::StaWifiMac", "Ssid", SsidValue(ssid));
301 NetDeviceContainer staDevices = wifiInfra.Install(wifiPhy, macInfra, stas);
302 // setup ap.
303 macInfra.SetType("ns3::ApWifiMac", "Ssid", SsidValue(ssid));
304 NetDeviceContainer apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i));
305 // Collect all of these new devices
306 NetDeviceContainer infraDevices(apDevices, staDevices);
307
308 // Add the IPv4 protocol stack to the nodes in our container
309 //
310 internet.Install(stas);
311 //
312 // Assign IPv4 addresses to the device drivers (actually to the associated
313 // IPv4 interfaces) we just created.
314 //
315 ipAddrs.Assign(infraDevices);
316 //
317 // Assign a new network prefix for each mobile network, according to
318 // the network mask initialized above
319 //
320 ipAddrs.NewNetwork();
321 //
322 // The new wireless nodes need a mobility model so we aggregate one
323 // to each of the nodes we just finished building.
324 //
326 for (uint32_t j = 0; j < infra.GetN(); ++j)
327 {
328 subnetAlloc->Add(Vector(0.0, j, 0.0));
329 }
330 mobility.PushReferenceMobilityModel(backbone.Get(i));
331 mobility.SetPositionAllocator(subnetAlloc);
332 mobility.SetMobilityModel("ns3::RandomDirection2dMobilityModel",
333 "Bounds",
334 RectangleValue(Rectangle(-10, 10, -10, 10)),
335 "Speed",
336 StringValue("ns3::ConstantRandomVariable[Constant=3]"),
337 "Pause",
338 StringValue("ns3::ConstantRandomVariable[Constant=0.4]"));
339 mobility.Install(stas);
340 }
341
342 ///////////////////////////////////////////////////////////////////////////
343 // //
344 // Application configuration //
345 // //
346 ///////////////////////////////////////////////////////////////////////////
347
348 // Create the OnOff application to send UDP datagrams of size
349 // 210 bytes at a rate of 10 Kb/s, between two nodes
350 // We'll send data from the first wired LAN node on the first wired LAN
351 // to the last wireless STA on the last infrastructure net, thereby
352 // causing packets to traverse CSMA to adhoc to infrastructure links
353
354 NS_LOG_INFO("Create Applications.");
355 uint16_t port = 9; // Discard port (RFC 863)
356
357 // Let's make sure that the user does not define too few nodes
358 // to make this example work. We need lanNodes > 1 and infraNodes > 1
359 NS_ASSERT(lanNodes > 1 && infraNodes > 1);
360 // We want the source to be the first node created outside of the backbone
361 // Conveniently, the variable "backboneNodes" holds this node index value
362 Ptr<Node> appSource = NodeList::GetNode(backboneNodes);
363 // We want the sink to be the last node created in the topology.
364 uint32_t lastNodeIndex =
365 backboneNodes + backboneNodes * (lanNodes - 1) + backboneNodes * (infraNodes - 1) - 1;
366 Ptr<Node> appSink = NodeList::GetNode(lastNodeIndex);
367 // Let's fetch the IP address of the last node, which is on Ipv4Interface 1
368 Ipv4Address remoteAddr = appSink->GetObject<Ipv4>()->GetAddress(1, 0).GetLocal();
369
370 OnOffHelper onoff("ns3::UdpSocketFactory", Address(InetSocketAddress(remoteAddr, port)));
371
372 ApplicationContainer apps = onoff.Install(appSource);
373 apps.Start(Seconds(3));
374 apps.Stop(Seconds(stopTime - 1));
375
376 // Create a packet sink to receive these packets
377 PacketSinkHelper sink("ns3::UdpSocketFactory", InetSocketAddress(Ipv4Address::GetAny(), port));
378 apps = sink.Install(appSink);
379 apps.Start(Seconds(3));
380
381 ///////////////////////////////////////////////////////////////////////////
382 // //
383 // Tracing configuration //
384 // //
385 ///////////////////////////////////////////////////////////////////////////
386
387 NS_LOG_INFO("Configure Tracing.");
389
390 //
391 // Let's set up some ns-2-like ascii traces, using another helper class
392 //
393 AsciiTraceHelper ascii;
394 Ptr<OutputStreamWrapper> stream = ascii.CreateFileStream("mixed-wireless.tr");
395 wifiPhy.EnableAsciiAll(stream);
396 csma.EnableAsciiAll(stream);
397 internet.EnableAsciiIpv4All(stream);
398
399 // Csma captures in non-promiscuous mode
400 csma.EnablePcapAll("mixed-wireless", false);
401 // pcap captures on the backbone wifi devices
402 wifiPhy.EnablePcap("mixed-wireless", backboneDevices, false);
403 // pcap trace on the application data sink
404 wifiPhy.EnablePcap("mixed-wireless", appSink->GetId(), 0);
405
406 if (useCourseChangeCallback)
407 {
408 Config::Connect("/NodeList/*/$ns3::MobilityModel/CourseChange",
410 }
411
412 AnimationInterface anim("mixed-wireless.xml");
413
414 ///////////////////////////////////////////////////////////////////////////
415 // //
416 // Run simulation //
417 // //
418 ///////////////////////////////////////////////////////////////////////////
419
420 NS_LOG_INFO("Run Simulation.");
424
425 return 0;
426}
a polymophic address class
Definition address.h:90
Interface to network animator.
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.
void EnableAsciiAll(std::string prefix)
Enable ascii trace output on each device (which is of the appropriate type) in the set of all nodes c...
Manage ASCII trace files for device models.
Ptr< OutputStreamWrapper > CreateFileStream(std::string filename, std::ios::openmode filemode=std::ios::out)
Create and initialize an output stream object we'll use to write the traced bits.
Parse command-line arguments.
build a set of CsmaNetDevice objects
Definition csma-helper.h:37
Class for representing data rates.
Definition data-rate.h:78
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
an Inet address class
aggregate IP/TCP/UDP functionality to existing Nodes.
A helper class to make life easier while doing simple IPv4 address assignment in scripts.
void SetBase(Ipv4Address network, Ipv4Mask mask, Ipv4Address base="0.0.0.1")
Set the base network number, network mask and base address.
Ipv4Address NewNetwork()
Increment the network number and reset the IP address counter to the base value provided in the SetBa...
Ipv4InterfaceContainer Assign(const NetDeviceContainer &c)
Assign IP addresses to the net devices specified in the container based on the current network prefix...
Ipv4 addresses are stored in host order in this class.
static Ipv4Address GetAny()
Access to the IPv4 forwarding table, interfaces, and configuration.
Definition ipv4.h:69
Helper class used to assign positions and mobility models to nodes.
void Install(Ptr< Node > node) const
"Layout" a single node according to the current position allocator type.
void SetMobilityModel(std::string type, Ts &&... args)
void PushReferenceMobilityModel(Ptr< Object > reference)
void SetPositionAllocator(Ptr< PositionAllocator > allocator)
Set the position allocator which will be used to allocate the initial position of every node initiali...
holds a vector of ns3::NetDevice pointers
keep track of a set of node pointers.
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.
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
static Ptr< Node > GetNode(uint32_t n)
Definition node-list.cc:240
Helper class that adds OLSR routing to nodes.
Definition olsr-helper.h:31
A helper to make it easier to instantiate an ns3::OnOffApplication on a set of nodes.
A helper to make it easier to instantiate an ns3::PacketSinkApplication on a set of nodes.
void EnablePcap(std::string prefix, Ptr< NetDevice > nd, bool promiscuous=false, bool explicitFilename=false)
Enable pcap output the indicated net device.
Smart pointer class similar to boost::intrusive_ptr.
a 2d rectangle
Definition rectangle.h:24
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition simulator.cc:131
static void Run()
Run the simulation.
Definition simulator.cc:167
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition simulator.cc:175
The IEEE 802.11 SSID Information Element.
Definition ssid.h:25
Hold variables of type string.
Definition string.h:45
Hold an unsigned integer type.
Definition uinteger.h:34
helps to create WifiNetDevice objects
virtual NetDeviceContainer Install(const WifiPhyHelper &phy, const WifiMacHelper &mac, NodeContainer::Iterator first, NodeContainer::Iterator last) const
create MAC layers for a ns3::WifiNetDevice.
void SetType(std::string type, Args &&... args)
void SetPcapDataLinkType(SupportedPcapDataLinkTypes dlt)
Set the data link type of PCAP traces to be used.
@ DLT_IEEE802_11_RADIO
Include Radiotap link layer information.
manage and create wifi channel objects for the YANS model.
static YansWifiChannelHelper Default()
Create a channel helper in a default working state.
Ptr< YansWifiChannel > Create() const
Make it easy to create and manage PHY objects for the YANS model.
void SetChannel(Ptr< YansWifiChannel > channel)
uint16_t port
Definition dsdv-manet.cc:33
Time stopTime
#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 SetDefault(std::string name, const AttributeValue &value)
Definition config.cc:883
void Connect(std::string path, const CallbackBase &cb)
Definition config.cc:967
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:264
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1308
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1320
AnimationInterface * anim
static void CourseChangeCallback(std::string path, Ptr< const MobilityModel > model)
This function will be used below as a trace sink, if the command-line argument or default value "useC...
Every class exported by the ns3 library is enclosed in the ns3 namespace.
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
Definition olsr.py:1
staDevices
Definition third.py:87
ssid
Definition third.py:82
mac
Definition third.py:81
wifi
Definition third.py:84
apDevices
Definition third.py:90
mobility
Definition third.py:92
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition wifi-tcp.cc:44