A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
wifi-ps-mode.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2025 Universita' degli Studi di Napoli Federico II
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Stefano Avallone <stavallo@unina.it>
7 */
8
9// This example aims at measuring the performance of a network in which non-AP devices may have one
10// or more affiliated STAs in power save mode.
11//
12// The simulation considers a single AP and a (configurable) number of non-AP devices using the same
13// set of links. The frequency channel used by each link can be configured. All non-AP devices have
14// the same configuration for the Power Management mode of their links. Note that, by default, only
15// the STAs affiliated with non-AP devices and operating on link 0 are in powersave mode; use the
16// --psMode command line argument to modify this configuration. It is possible to generate downlink
17// and/or uplink UDP/TCP traffic between the AP and every non-AP device. The flow data rate needs to
18// be configured for both downlink and uplink, as by default it is set to zero. The rate adaptation
19// manager and the size of every packet can also be configured.
20//
21// Per-flow statistics collected with FlowMonitor are printed at the end of the simulation. It is
22// checked that the throughput of each flow is within a configurable bound of the flow data rate.
23//
24// Example usage and output:
25//
26// ./ns3 run "wifi-ps-mode --dlLoad=10Mbps --ulLoad=25Mbps --simulationTime=500ms --nStas=2
27// --staticSetup=1 --psMode=0:true,1:true --channels=36,0,BAND_5GHZ,0:100,0,BAND_5GHZ,0"
28//
29// The IP address of the AP is 192.168.1.1
30//
31// Flow 1 (192.168.1.2 -> 192.168.1.1)
32// Tx Packets: 520
33// Tx Bytes: 794560
34// TxOffered: 12712960bps
35// Rx Packets: 520
36// Rx Bytes: 794560
37// Throughput: 12712960bps
38// Flow 2 (192.168.1.3 -> 192.168.1.1)
39// Tx Packets: 520
40// Tx Bytes: 794560
41// TxOffered: 12712960bps
42// Rx Packets: 520
43// Rx Bytes: 794560
44// Throughput: 12712960bps
45// Flow 3 (192.168.1.1 -> 192.168.1.2)
46// Tx Packets: 208
47// Tx Bytes: 317824
48// TxOffered: 5085184bps
49// Rx Packets: 182
50// Rx Bytes: 278096
51// Throughput: 4449536bps
52// Flow 4 (192.168.1.1 -> 192.168.1.3)
53// Tx Packets: 208
54// Tx Bytes: 317824
55// TxOffered: 5085184bps
56// Rx Packets: 182
57// Rx Bytes: 278096
58// Throughput: 4449536bps
59
60#include "ns3/boolean.h"
61#include "ns3/command-line.h"
62#include "ns3/config.h"
63#include "ns3/data-rate.h"
64#include "ns3/flow-monitor-helper.h"
65#include "ns3/internet-stack-helper.h"
66#include "ns3/ipv4-address-helper.h"
67#include "ns3/ipv4-flow-classifier.h"
68#include "ns3/log.h"
69#include "ns3/mobility-helper.h"
70#include "ns3/multi-model-spectrum-channel.h"
71#include "ns3/neighbor-cache-helper.h"
72#include "ns3/on-off-helper.h"
73#include "ns3/packet-sink-helper.h"
74#include "ns3/packet-sink.h"
75#include "ns3/spectrum-wifi-helper.h"
76#include "ns3/ssid.h"
77#include "ns3/string.h"
78#include "ns3/uinteger.h"
79#include "ns3/wifi-mac-queue.h"
80#include "ns3/wifi-mac.h"
81#include "ns3/wifi-net-device.h"
82#include "ns3/wifi-static-setup-helper.h"
83
84#include <algorithm>
85#include <unordered_map>
86
87using namespace ns3;
88
89NS_LOG_COMPONENT_DEFINE("WifiPsMode");
90
91int
92main(int argc, char* argv[])
93{
94 std::string standard{"11be"};
95 std::string channels{"36,0,BAND_5GHZ,0"};
96 std::size_t nStas{1};
97 std::string psMode{"0:true"};
98 std::string raa{"ThompsonSamplingWifiManager"};
99 uint32_t payloadSize{1500};
100 bool enableRts{false};
101 bool enablePcap{false};
102 bool useUdp{true};
103 DataRate ulLoad;
104 DataRate dlLoad;
105 bool staticSetup{true};
106 Time simulationTime{"3s"};
107 double tolerance{0.15};
108
109 CommandLine cmd(__FILE__);
110 cmd.AddValue("standard", "Supported standard (11n, 11ac, 11ax, 11be)", standard);
111 cmd.AddValue("channels",
112 "Colon separated (no spaces) list of channel settings for the links of both "
113 "the AP and the STAs",
114 channels);
115 cmd.AddValue("nStas", "the number of non-AP devices", nStas);
116 cmd.AddValue("psMode",
117 "Comma separated (no spaces) list of pairs indicating whether PM mode must be "
118 "enabled on a given link for all non-AP devices (e.g., \"0:true,1:false\" enables "
119 "PM mode only on link 0)",
120 psMode);
121 cmd.AddValue("raa", "TypeId of the rate adaptation algorithm to use", raa);
122 cmd.AddValue("payloadSize", "Payload size in bytes", payloadSize);
123 cmd.AddValue("enableRts", "Enable or disable RTS/CTS", enableRts);
124 cmd.AddValue("enablePcap", "Enable/disable pcap file generation", enablePcap);
125 cmd.AddValue("useUdp", "true to use UDP, false to use TCP", useUdp);
126 cmd.AddValue("dlLoad", "Rate of the total downlink load to generate", dlLoad);
127 cmd.AddValue("ulLoad", "Rate of the total uplink load to generate", ulLoad);
128 cmd.AddValue("staticSetup", "whether to use the static setup helper", staticSetup);
129 cmd.AddValue("simulationTime", "Simulation time", simulationTime);
130 cmd.AddValue("tolerance",
131 "simulation fails if the throughput of every flow is not within this ratio "
132 "of the offered traffic load",
133 tolerance);
134 cmd.Parse(argc, argv);
135
136 Config::SetDefault("ns3::WifiRemoteStationManager::RtsCtsThreshold",
137 enableRts ? StringValue("0")
138 : StringValue(std::to_string(WIFI_MAX_RTS_THRESHOLD)));
139
142
144 wifi.SetRemoteStationManager("ns3::" + raa);
145
146 if (standard == "11be")
147 {
148 wifi.SetStandard(WIFI_STANDARD_80211be);
149 }
150 else if (standard == "11ax")
151 {
152 wifi.SetStandard(WIFI_STANDARD_80211ax);
153 }
154 else if (standard == "11ac")
155 {
156 wifi.SetStandard(WIFI_STANDARD_80211ac);
157 }
158 else if (standard == "11n")
159 {
160 wifi.SetStandard(WIFI_STANDARD_80211n);
161 }
162 else
163 {
164 NS_ABORT_MSG("Unsupported standard (" << standard
165 << "), valid values are 11n, 11ac, 11ax or 11be");
166 }
167
168 std::unordered_map<WifiPhyBand, Ptr<MultiModelSpectrumChannel>> channelMap = {
172
173 auto strings = SplitString(channels, ":");
174 SpectrumWifiPhyHelper phy{static_cast<uint8_t>(strings.size())};
175 phy.SetPcapDataLinkType(WifiPhyHelper::DLT_IEEE802_11_RADIO);
176 linkId_t linkId = 0;
177 for (auto& str : strings)
178 {
179 str = "{" + str + "}";
180 phy.Set(linkId, "ChannelSettings", StringValue(str));
181
182 auto channelConfig = WifiChannelConfig::FromString(str);
183 auto phyBand = channelConfig.front().band;
184 auto freqRange = GetFrequencyRange(phyBand);
185 phy.AddPhyToFreqRangeMapping(linkId, freqRange);
186 phy.AddChannel(channelMap.at(phyBand), freqRange);
187
188 ++linkId;
189 }
190
191 Ssid ssid("wifi-ps-mode");
192
194 mac.SetType("ns3::ApWifiMac", "Ssid", SsidValue(ssid));
195 auto apDevice = wifi.Install(phy, mac, wifiApNode);
196
197 mac.SetType("ns3::StaWifiMac", "Ssid", SsidValue(ssid));
198 // adjust psMode string to make it compatible with the format of the PowerSaveMode attribute
199 std::replace(psMode.begin(), psMode.end(), ':', ' ');
200 mac.SetPowerSaveManager("ns3::DefaultPowerSaveManager", "PowerSaveMode", StringValue(psMode));
201 auto staDevices = wifi.Install(phy, mac, wifiStaNodes);
202
203 int64_t streamNumber = 150;
204 streamNumber += WifiHelper::AssignStreams(apDevice, streamNumber);
205 streamNumber += WifiHelper::AssignStreams(staDevices, streamNumber);
206
207 // Setting mobility model
210 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
211
212 positionAlloc->Add(Vector(0.0, 0.0, 0.0));
213 positionAlloc->Add(Vector(1.0, 0.0, 0.0));
214
215 mobility.SetPositionAllocator(positionAlloc);
216 mobility.Install(wifiApNode);
217 mobility.Install(wifiStaNodes);
218
219 if (staticSetup)
220 {
221 /* static setup of association and BA agreements */
222 auto apDev = DynamicCast<WifiNetDevice>(apDevice.Get(0));
223 NS_ASSERT(apDev);
225 WifiStaticSetupHelper::SetStaticBlockAck(apDev, staDevices, {0});
226 }
227
228 // Internet stack
230 stack.Install(wifiApNode);
231 stack.Install(wifiStaNodes);
232
234 address.SetBase("192.168.1.0", "255.255.255.0");
235 auto apInterface = address.Assign(apDevice);
236 auto staInterfaces = address.Assign(staDevices);
237
238 std::cout << "The IP address of the AP is " << apInterface.GetAddress(0) << "\n\n";
239
240 /* static setup of ARP cache */
241 NeighborCacheHelper nbCache;
242 nbCache.PopulateNeighborCache();
243
244 // allow for some time to associate and establish BA agreement if static setup helper is not
245 // used
246 Time startTime = staticSetup ? Time{0} : MilliSeconds(500);
247
248 // Setting applications
249 const uint16_t port = 9; // Discard port (RFC 863)
250 auto socketFactory = useUdp ? "ns3::UdpSocketFactory" : "ns3::TcpSocketFactory";
251
252 // Install client and server apps for UL flow (if data rate > 0)
253 if (ulLoad.GetBitRate() > 0)
254 {
255 OnOffHelper onoff(socketFactory,
256 Address(InetSocketAddress(apInterface.GetAddress(0), port)));
257 onoff.SetConstantRate(ulLoad * (1. / nStas), payloadSize);
258
259 for (uint32_t i = 0; i < wifiStaNodes.GetN(); ++i)
260 {
261 auto clientApp = onoff.Install(wifiStaNodes.Get(i));
262 clientApp.Start(startTime);
263 clientApp.Stop(startTime + simulationTime);
264 }
265
266 // Create a packet sink to receive these packets
267 PacketSinkHelper sink(socketFactory,
269 auto serverApp = sink.Install(wifiApNode.Get(0));
270 serverApp.Start(Time{0});
271 }
272
273 // Install client and server apps for DL flow (if data rate > 0)
274 if (dlLoad.GetBitRate() > 0)
275 {
276 for (uint32_t i = 0; i < staInterfaces.GetN(); ++i)
277 {
278 OnOffHelper onoff(socketFactory,
279 Address(InetSocketAddress(staInterfaces.GetAddress(i), port)));
280 onoff.SetConstantRate(dlLoad * (1. / nStas), payloadSize);
281
282 auto clientApp = onoff.Install(wifiApNode.Get(0));
283 clientApp.Start(startTime);
284 clientApp.Stop(startTime + simulationTime);
285
286 // Create a packet sink to receive these packets
287 PacketSinkHelper sink(socketFactory,
289 auto serverApp = sink.Install(wifiStaNodes.Get(i));
290 serverApp.Start(Time{0});
291 }
292 }
293
294 if (enablePcap)
295 {
296 phy.EnablePcap("wifi_PS_mode_AP", apDevice);
297 phy.EnablePcap("wifi_PS_mode_STA", staDevices);
298 }
299
300 FlowMonitorHelper flowmon;
301 auto monitor = flowmon.InstallAll();
302
303 Simulator::Stop(startTime + simulationTime);
305
306 monitor->CheckForLostPackets();
307 auto classifier = DynamicCast<Ipv4FlowClassifier>(flowmon.GetClassifier());
308 auto stats = monitor->GetFlowStats();
309 for (const auto& [flowId, flowStats] : stats)
310 {
311 auto t = classifier->FindFlow(flowId);
312
313 const auto load = DataRate((flowStats.txBytes * 8.0) / simulationTime.GetSeconds());
314 const auto tput = DataRate((flowStats.rxBytes * 8.0) / simulationTime.GetSeconds());
315
316 std::cout << "Flow " << flowId << " (" << t.sourceAddress << " -> " << t.destinationAddress
317 << ")\n";
318 std::cout << " Tx Packets: " << flowStats.txPackets << "\n";
319 std::cout << " Tx Bytes: " << flowStats.txBytes << "\n";
320 std::cout << " TxOffered: " << load << "\n";
321 std::cout << " Rx Packets: " << flowStats.rxPackets << "\n";
322 std::cout << " Rx Bytes: " << flowStats.rxBytes << "\n";
323 std::cout << " Throughput: " << tput << "\n";
324
325 const auto minExpectedTput = load * (1.0 - tolerance);
326 const auto maxExpectedTput = load * (1.0 + tolerance);
327 if (tput < minExpectedTput || tput > maxExpectedTput)
328 {
329 NS_LOG_ERROR("Throughput " << tput << " is outside expected range [" << minExpectedTput
330 << ", " << maxExpectedTput << "]");
331 exit(1);
332 }
333 }
334
336
337 return 0;
338}
a polymophic address class
Definition address.h:114
Parse command-line arguments.
Class for representing data rates.
Definition data-rate.h:78
uint64_t GetBitRate() const
Get the underlying bitrate.
Definition data-rate.cc:198
Helper to enable IP flow monitoring on a set of Nodes.
Ptr< FlowClassifier > GetClassifier()
Retrieve the FlowClassifier object for IPv4 created by the Install* methods.
Ptr< FlowMonitor > InstallAll()
Enable flow monitoring on all nodes.
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()
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.
keep track of a set of node pointers.
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:70
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition simulator.cc:125
static void Run()
Run the simulation.
Definition simulator.cc:161
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition simulator.cc:169
Make it easy to create and manage PHY objects for the spectrum model.
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:95
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.
@ DLT_IEEE802_11_RADIO
Include Radiotap link layer information.
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.
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
void SetDefault(std::string name, const AttributeValue &value)
Definition config.cc:886
#define NS_ABORT_MSG(msg)
Unconditional abnormal program termination with a message.
Definition abort.h:38
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
Definition log.h:246
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:194
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:627
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1290
@ WIFI_STANDARD_80211be
@ WIFI_STANDARD_80211n
@ WIFI_STANDARD_80211ax
@ WIFI_STANDARD_80211ac
@ WIFI_PHY_BAND_6GHZ
The 6 GHz band.
@ 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.
FrequencyRange GetFrequencyRange(WifiPhyBand band)
Get the frequency range corresponding to the given PHY band.
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:605
StringVector SplitString(const std::string &str, const std::string &delim)
Split a string on a delimiter.
Definition string.cc:23
uint8_t linkId_t
IEEE 802.11be D7.0 Figure 9-207e—Link ID Info field format.
Definition wifi-utils.h:74
static constexpr uint32_t WIFI_MAX_RTS_THRESHOLD
The maximum value for dot11RTSThreshold (C.3 MIB detail in IEEE Std 802.11-2020).
staDevices
Definition third.py:87
ssid
Definition third.py:82
mac
Definition third.py:81
wifi
Definition third.py:84
wifiApNode
Definition third.py:75
mobility
Definition third.py:92
wifiStaNodes
Definition third.py:73
phy
Definition third.py:78
static WifiChannelConfig FromString(const std::string &settings, WifiStandard standard=WIFI_STANDARD_UNSPECIFIED)
Get the wifi channel config from a WifiPhy::ChannelSettings string.
Definition wifi-types.cc:24
Ptr< PacketSink > sink
Pointer to the packet sink application.
Definition wifi-tcp.cc:44