A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
wifi-ht-network.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2009 MIRKO BANCHI
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Authors: Mirko Banchi <mk.banchi@gmail.com>
7 * Sebastien Deronne <sebastien.deronne@gmail.com>
8 */
9
10#include "ns3/attribute-container.h"
11#include "ns3/boolean.h"
12#include "ns3/command-line.h"
13#include "ns3/config.h"
14#include "ns3/double.h"
15#include "ns3/enum.h"
16#include "ns3/ht-phy.h"
17#include "ns3/internet-stack-helper.h"
18#include "ns3/ipv4-address-helper.h"
19#include "ns3/ipv4-global-routing-helper.h"
20#include "ns3/log.h"
21#include "ns3/mobility-helper.h"
22#include "ns3/neighbor-cache-helper.h"
23#include "ns3/on-off-helper.h"
24#include "ns3/packet-sink-helper.h"
25#include "ns3/packet-sink.h"
26#include "ns3/ssid.h"
27#include "ns3/string.h"
28#include "ns3/tuple.h"
29#include "ns3/udp-client-server-helper.h"
30#include "ns3/udp-server.h"
31#include "ns3/uinteger.h"
32#include "ns3/wifi-static-setup-helper.h"
33#include "ns3/yans-wifi-channel.h"
34#include "ns3/yans-wifi-helper.h"
35
36#include <algorithm>
37#include <vector>
38
39// This is a simple example in order to show how to configure an IEEE 802.11n Wi-Fi network.
40//
41// It outputs the UDP or TCP goodput for every HT MCS value, which depends on the MCS value (0 to
42// 7), the channel width (20 or 40 MHz) and the guard interval (long or short). The PHY bitrate is
43// constant over all the simulation run. The user can also specify the distance between the access
44// point and the station: the larger the distance the smaller the goodput.
45//
46// The simulation assumes a single station in an infrastructure network:
47//
48// STA AP
49// * *
50// | |
51// n1 n2
52//
53// Packets in this simulation belong to BestEffort Access Class (AC_BE).
54
55using namespace ns3;
56
57NS_LOG_COMPONENT_DEFINE("ht-wifi-network");
58
59int
60main(int argc, char* argv[])
61{
62 bool udp{true};
63 bool useRts{false};
64 Time simulationTime{"10s"};
65 bool staticSetup{true};
66 auto clientAppStartTime = Seconds(1);
67 meter_u distance{1.0};
68 double frequency{5}; // whether 2.4 or 5 GHz
69 std::string mcsStr;
70 std::vector<uint64_t> mcsValues;
71 int channelWidth{-1}; // in MHz, -1 indicates an unset value
72 int guardInterval{-1}; // in nanoseconds, -1 indicates an unset value
73 double minExpectedThroughput{0.0};
74 double maxExpectedThroughput{0.0};
75
76 CommandLine cmd(__FILE__);
77 cmd.AddValue("staticSetup",
78 "Whether devices are configured using the static setup helper",
79 staticSetup);
80 cmd.AddValue("frequency",
81 "Whether working in the 2.4 or 5.0 GHz band (other values gets rejected)",
82 frequency);
83 cmd.AddValue("distance",
84 "Distance in meters between the station and the access point",
85 distance);
86 cmd.AddValue("simulationTime", "Simulation time", simulationTime);
87 cmd.AddValue("udp", "UDP if set to 1, TCP otherwise", udp);
88 cmd.AddValue("useRts", "Enable/disable RTS/CTS", useRts);
89 cmd.AddValue(
90 "mcs",
91 "list of comma separated MCS values to test; if unset, all MCS values (0-7) are tested",
92 mcsStr);
93 cmd.AddValue(
94 "channelWidth",
95 "if set, limit testing to a specific channel width expressed in MHz (20 or 40 MHz)",
96 channelWidth);
97 cmd.AddValue("guardInterval",
98 "if set, limit testing to a specific guard interval duration expressed in "
99 "nanoseconds (800 or 400 ns)",
100 guardInterval);
101 cmd.AddValue("minExpectedThroughput",
102 "if set, simulation fails if the lowest throughput is below this value",
103 minExpectedThroughput);
104 cmd.AddValue("maxExpectedThroughput",
105 "if set, simulation fails if the highest throughput is above this value",
106 maxExpectedThroughput);
107 cmd.Parse(argc, argv);
108
109 if (useRts)
110 {
111 Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue("0"));
112 }
113
114 double prevThroughput[8] = {0};
115
116 std::cout << "MCS value"
117 << "\t\t"
118 << "Channel width"
119 << "\t\t"
120 << "short GI"
121 << "\t\t"
122 << "Throughput" << '\n';
123 uint8_t minMcs = 0;
124 uint8_t maxMcs = 7;
125
126 if (mcsStr.empty())
127 {
128 for (uint8_t mcs = minMcs; mcs <= maxMcs; ++mcs)
129 {
130 mcsValues.push_back(mcs);
131 }
132 }
133 else
134 {
135 AttributeContainerValue<UintegerValue, ',', std::vector> attr;
137 checker->SetItemChecker(MakeUintegerChecker<uint8_t>());
138 attr.DeserializeFromString(mcsStr, checker);
139 mcsValues = attr.Get();
140 std::sort(mcsValues.begin(), mcsValues.end());
141 }
142
143 int minChannelWidth = 20;
144 int maxChannelWidth = 40;
145 if ((channelWidth != -1) &&
146 ((channelWidth < minChannelWidth) || (channelWidth > maxChannelWidth)))
147 {
148 NS_FATAL_ERROR("Invalid channel width: " << channelWidth << " MHz");
149 }
150 if (channelWidth >= minChannelWidth && channelWidth <= maxChannelWidth)
151 {
152 minChannelWidth = channelWidth;
153 maxChannelWidth = channelWidth;
154 }
155 int minGi = 400;
156 int maxGi = 800;
157 if (guardInterval >= minGi && guardInterval <= maxGi)
158 {
159 minGi = guardInterval;
160 maxGi = guardInterval;
161 }
162
163 for (const auto mcs : mcsValues)
164 {
165 uint8_t index = 0;
166 double previous = 0;
167 for (int width = minChannelWidth; width <= maxChannelWidth; width *= 2) // MHz
168 {
169 for (int gi = maxGi; gi >= minGi; gi /= 2) // Nanoseconds
170 {
171 const auto sgi = (gi == 400);
172 uint32_t payloadSize; // 1500 byte IP packet
173 if (udp)
174 {
175 payloadSize = 1472; // bytes
176 }
177 else
178 {
179 payloadSize = 1448; // bytes
180 Config::SetDefault("ns3::TcpSocket::SegmentSize", UintegerValue(payloadSize));
181 }
182
183 NodeContainer wifiStaNode;
184 wifiStaNode.Create(1);
186 wifiApNode.Create(1);
187
190 phy.SetChannel(channel.Create());
191
194 std::ostringstream ossControlMode;
195
196 if (frequency == 5.0)
197 {
198 ossControlMode << "OfdmRate";
199 wifi.SetStandard(WIFI_STANDARD_80211n);
200 }
201 else if (frequency == 2.4)
202 {
203 wifi.SetStandard(WIFI_STANDARD_80211n);
204 ossControlMode << "ErpOfdmRate";
205 Config::SetDefault("ns3::LogDistancePropagationLossModel::ReferenceLoss",
206 DoubleValue(40.046));
207 }
208 else
209 {
210 NS_FATAL_ERROR("Wrong frequency value!");
211 }
212
213 auto nonHtRefRateMbps = HtPhy::GetNonHtReferenceRate(mcs) / 1e6;
214 ossControlMode << nonHtRefRateMbps << "Mbps";
215
216 std::ostringstream ossDataMode;
217 ossDataMode << "HtMcs" << mcs;
218 wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
219 "DataMode",
220 StringValue(ossDataMode.str()),
221 "ControlMode",
222 StringValue(ossControlMode.str()));
223 // Set guard interval
224 wifi.ConfigHtOptions("ShortGuardIntervalSupported", BooleanValue(sgi));
225
226 Ssid ssid = Ssid("ns3-80211n");
229 ';'>
230 channelValue;
231 WifiPhyBand band = (frequency == 5.0 ? WIFI_PHY_BAND_5GHZ : WIFI_PHY_BAND_2_4GHZ);
232 channelValue.Set(WifiPhy::ChannelSegments{{0, width, band, 0}});
233
234 mac.SetType("ns3::StaWifiMac", "Ssid", SsidValue(ssid));
235 phy.Set("ChannelSettings", channelValue);
236
237 NetDeviceContainer staDevice;
238 staDevice = wifi.Install(phy, mac, wifiStaNode);
239
240 mac.SetType("ns3::ApWifiMac",
241 "EnableBeaconJitter",
242 BooleanValue(false),
243 "BeaconGeneration",
244 BooleanValue(!staticSetup),
245 "Ssid",
246 SsidValue(ssid));
247
248 NetDeviceContainer apDevice;
249 apDevice = wifi.Install(phy, mac, wifiApNode);
250
251 int64_t streamNumber = 150;
252 streamNumber += WifiHelper::AssignStreams(apDevice, streamNumber);
253 streamNumber += WifiHelper::AssignStreams(staDevice, streamNumber);
254
255 // mobility.
258
259 positionAlloc->Add(Vector(0.0, 0.0, 0.0));
260 positionAlloc->Add(Vector(distance, 0.0, 0.0));
261 mobility.SetPositionAllocator(positionAlloc);
262
263 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
264
265 mobility.Install(wifiApNode);
266 mobility.Install(wifiStaNode);
267
268 if (staticSetup)
269 {
270 /* static setup of association and BA agreements */
271 auto apDev = DynamicCast<WifiNetDevice>(apDevice.Get(0));
272 NS_ASSERT(apDev);
274 WifiStaticSetupHelper::SetStaticBlockAck(apDev, staDevice, {0});
275 clientAppStartTime = MilliSeconds(1);
276 }
277
278 /* Internet stack*/
280 stack.Install(wifiApNode);
281 stack.Install(wifiStaNode);
282 streamNumber += stack.AssignStreams(wifiApNode, streamNumber);
283 streamNumber += stack.AssignStreams(wifiStaNode, streamNumber);
284
286 address.SetBase("192.168.1.0", "255.255.255.0");
287 Ipv4InterfaceContainer staNodeInterface;
288 Ipv4InterfaceContainer apNodeInterface;
289
290 staNodeInterface = address.Assign(staDevice);
291 apNodeInterface = address.Assign(apDevice);
292
293 if (staticSetup)
294 {
295 /* static setup of ARP cache */
296 NeighborCacheHelper nbCache;
297 nbCache.PopulateNeighborCache();
298 }
299
300 /* Setting applications */
301 const auto maxLoad = HtPhy::GetDataRate(mcs,
302 MHz_u{static_cast<double>(width)},
303 NanoSeconds(sgi ? 400 : 800),
304 1);
305 ApplicationContainer serverApp;
306 if (udp)
307 {
308 // UDP flow
309 uint16_t port = 9;
311 serverApp = server.Install(wifiStaNode.Get(0));
312 streamNumber += server.AssignStreams(wifiStaNode.Get(0), streamNumber);
313
314 serverApp.Start(Seconds(0));
315 serverApp.Stop(simulationTime + clientAppStartTime);
316 const auto packetInterval = payloadSize * 8.0 / maxLoad;
317
318 UdpClientHelper client(staNodeInterface.GetAddress(0), port);
319 client.SetAttribute("MaxPackets", UintegerValue(4294967295U));
320 client.SetAttribute("Interval", TimeValue(Seconds(packetInterval)));
321 client.SetAttribute("PacketSize", UintegerValue(payloadSize));
322 ApplicationContainer clientApp = client.Install(wifiApNode.Get(0));
323 streamNumber += client.AssignStreams(wifiApNode.Get(0), streamNumber);
324
325 clientApp.Start(clientAppStartTime);
326 clientApp.Stop(simulationTime + clientAppStartTime);
327 }
328 else
329 {
330 // TCP flow
331 uint16_t port = 50000;
333 PacketSinkHelper packetSinkHelper("ns3::TcpSocketFactory", localAddress);
334 serverApp = packetSinkHelper.Install(wifiStaNode.Get(0));
335 streamNumber +=
336 packetSinkHelper.AssignStreams(wifiStaNode.Get(0), streamNumber);
337
338 serverApp.Start(Seconds(0));
339 serverApp.Stop(simulationTime + clientAppStartTime);
340
341 OnOffHelper onoff("ns3::TcpSocketFactory", Ipv4Address::GetAny());
342 onoff.SetAttribute("OnTime",
343 StringValue("ns3::ConstantRandomVariable[Constant=1]"));
344 onoff.SetAttribute("OffTime",
345 StringValue("ns3::ConstantRandomVariable[Constant=0]"));
346 onoff.SetAttribute("PacketSize", UintegerValue(payloadSize));
347 onoff.SetAttribute("DataRate", DataRateValue(maxLoad));
349 InetSocketAddress(staNodeInterface.GetAddress(0), port));
350 onoff.SetAttribute("Remote", remoteAddress);
351 ApplicationContainer clientApp = onoff.Install(wifiApNode.Get(0));
352 streamNumber += onoff.AssignStreams(wifiApNode.Get(0), streamNumber);
353
354 clientApp.Start(clientAppStartTime);
355 clientApp.Stop(simulationTime + clientAppStartTime);
356 }
357
359
360 Simulator::Stop(simulationTime + clientAppStartTime);
362
363 auto rxBytes = 0.0;
364 if (udp)
365 {
366 rxBytes = payloadSize * DynamicCast<UdpServer>(serverApp.Get(0))->GetReceived();
367 }
368 else
369 {
370 rxBytes = DynamicCast<PacketSink>(serverApp.Get(0))->GetTotalRx();
371 }
372 auto throughput = (rxBytes * 8) / simulationTime.GetMicroSeconds(); // Mbit/s
373
375
376 std::cout << mcs << "\t\t\t" << width << " MHz\t\t\t" << std::boolalpha << sgi
377 << "\t\t\t" << throughput << " Mbit/s" << std::endl;
378
379 // test first element
380 if (mcs == minMcs && width == 20 && !sgi)
381 {
382 if (throughput < minExpectedThroughput)
383 {
384 NS_FATAL_ERROR("Obtained throughput " << throughput << " is not expected!");
385 }
386 }
387 // test last element
388 if (mcs == maxMcs && width == 40 && sgi)
389 {
390 if (maxExpectedThroughput > 0 && throughput > maxExpectedThroughput)
391 {
392 NS_FATAL_ERROR("Obtained throughput " << throughput << " is not expected!");
393 }
394 }
395 // test previous throughput is smaller (for the same mcs)
396 if (throughput > previous)
397 {
398 previous = throughput;
399 }
400 else
401 {
402 NS_FATAL_ERROR("Obtained throughput " << throughput << " is not expected!");
403 }
404 // test previous throughput is smaller (for the same channel width and GI)
405 if (throughput > prevThroughput[index])
406 {
407 prevThroughput[index] = throughput;
408 }
409 else
410 {
411 NS_FATAL_ERROR("Obtained throughput " << throughput << " is not expected!");
412 }
413 index++;
414 }
415 }
416 }
417 return 0;
418}
a polymophic address class
Definition address.h:90
AttributeValue implementation for Address.
Definition address.h:275
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.
A container for one type of attribute.
void Set(const T &c)
Copy items from container c.
AttributeValue implementation for Boolean.
Definition boolean.h:26
Parse command-line arguments.
AttributeValue implementation for DataRate.
Definition data-rate.h:285
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
static uint64_t GetNonHtReferenceRate(uint8_t mcsValue)
Calculate the rate in bps of the non-HT Reference Rate corresponding to the supplied HT MCS index.
Definition ht-phy.cc:731
static uint64_t GetDataRate(uint8_t mcsValue, MHz_u channelWidth, Time guardInterval, uint8_t nss)
Return the data rate corresponding to the supplied HT MCS index, channel width, guard interval,...
Definition ht-phy.cc:693
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.
static Ipv4Address GetAny()
static void PopulateRoutingTables()
Build a routing database and initialize the routing tables of the nodes in the simulation.
holds a vector of std::pair of Ptr<Ipv4> and interface index.
Ipv4Address GetAddress(uint32_t i, uint32_t j=0) const
Helper class used to assign positions and mobility models to nodes.
A helper class to populate neighbor cache.
void PopulateNeighborCache()
Populate neighbor ARP and NDISC caches for all devices.
holds a vector of ns3::NetDevice pointers
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.
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.
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.
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:67
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
AttributeValue implementation for Ssid.
Definition ssid.h:85
Hold variables of type string.
Definition string.h:45
Simulation virtual time values and global simulation resolution.
Definition nstime.h:96
AttributeValue implementation for Time.
Definition nstime.h:1456
AttributeValue implementation for Tuple.
Definition tuple.h:67
Create a client application which sends UDP packets carrying a 32bit sequence number and a 64 bit tim...
Create a server application which waits for input UDP packets and uses the information carried into t...
Hold an unsigned integer type.
Definition uinteger.h:34
helps to create WifiNetDevice objects
static int64_t AssignStreams(NetDeviceContainer c, int64_t stream)
Assign a fixed random variable stream number to the random variables used by the PHY and MAC aspects ...
create MAC layers for a ns3::WifiNetDevice.
std::list< WifiChannelConfig::TupleWithoutUnits > ChannelSegments
segments identifying an operating channel
Definition wifi-phy.h:952
static void SetStaticAssociation(Ptr< WifiNetDevice > bssDev, const NetDeviceContainer &clientDevs)
Bypass static capabilities exchange for input devices.
static void SetStaticBlockAck(Ptr< WifiNetDevice > apDev, const NetDeviceContainer &clientDevs, const std::set< tid_t > &tids, std::optional< Mac48Address > gcrGroupAddr=std::nullopt)
Bypass ADDBA Request-Response exchange sequence between AP and STAs for given TIDs.
manage and create wifi channel objects for the YANS model.
static YansWifiChannelHelper Default()
Create a channel helper in a default working state.
Make it easy to create and manage PHY objects for the YANS model.
uint16_t port
Definition dsdv-manet.cc:33
#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
Ptr< AttributeChecker > MakeAttributeContainerChecker()
Make uninitialized AttributeContainerChecker using explicit types.
Ptr< const AttributeChecker > MakeUintegerChecker()
Definition uinteger.h:85
void SetDefault(std::string name, const AttributeValue &value)
Definition config.cc:886
#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
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:619
Time NanoSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1405
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1369
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1381
WifiPhyBand
Identifies the PHY band.
@ WIFI_STANDARD_80211n
@ WIFI_PHY_BAND_2_4GHZ
The 2.4 GHz band.
@ WIFI_PHY_BAND_5GHZ
The 5 GHz band.
address
Definition first.py:36
stack
Definition first.py:33
Every class exported by the ns3 library is enclosed in the ns3 namespace.
double MHz_u
MHz weak type.
Definition wifi-units.h:31
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:585
double meter_u
meter weak type
Definition wifi-units.h:32
ssid
Definition third.py:82
channel
Definition third.py:77
mac
Definition third.py:81
wifi
Definition third.py:84
wifiApNode
Definition third.py:75
mobility
Definition third.py:92
phy
Definition third.py:78
std::ofstream throughput