A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
aloha-throughput.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2017 University of Padova
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Davide Magrin <magrinda@dei.unipd.it>
7 */
8
9#include "ns3/core-module.h"
10#include "ns3/lorawan-module.h"
11#include "ns3/mobility-helper.h"
12#include "ns3/point-to-point-helper.h"
13
14using namespace ns3;
15using namespace lorawan;
16
17NS_LOG_COMPONENT_DEFINE("AlohaThroughput");
18
19// Network settings
20int nDevices = 200; //!< Number of end device nodes to create
21int nGateways = 1; //!< Number of gateway nodes to create
22double radiusMeters = 1000; //!< Radius (m) of the deployment
23double simulationTimeSeconds = 100; //!< Scenario duration (s) in simulated time
24
25// Channel model
26bool realisticChannelModel = false; //!< Whether to use a more realistic channel model with
27 //!< buildings and correlated shadowing
28
29/** Record received pkts by Data Rate (DR) [index 0 -> DR5, index 5 -> DR0]. */
30auto packetsSent = std::vector<int>(6, 0);
31/** Record received pkts by Data Rate (DR) [index 0 -> DR5, index 5 -> DR0]. */
32auto packetsReceived = std::vector<int>(6, 0);
33
34/**
35 * Record the beginning of a transmission by an end device.
36 *
37 * @param packet A pointer to the packet sent.
38 * @param senderNodeId Node id of the sender end device.
39 */
40void
42{
43 NS_LOG_FUNCTION(packet << senderNodeId);
44 LoraTag tag;
45 packet->PeekPacketTag(tag);
46 packetsSent.at(tag.GetSpreadingFactor() - 7)++;
47}
48
49/**
50 * Record the correct reception of a packet by a gateway.
51 *
52 * @param packet A pointer to the packet received.
53 * @param receiverNodeId Node id of the receiver gateway.
54 */
55void
57{
58 NS_LOG_FUNCTION(packet << receiverNodeId);
59 LoraTag tag;
60 packet->PeekPacketTag(tag);
61 packetsReceived.at(tag.GetSpreadingFactor() - 7)++;
62}
63
64int
65main(int argc, char* argv[])
66{
67 std::string interferenceMatrix = "aloha";
68
69 CommandLine cmd(__FILE__);
70 cmd.AddValue("nDevices", "Number of end devices to include in the simulation", nDevices);
71 cmd.AddValue("simulationTime", "Simulation Time (s)", simulationTimeSeconds);
72 cmd.AddValue("interferenceMatrix",
73 "Interference matrix to use [aloha, goursaud]",
74 interferenceMatrix);
75 cmd.AddValue("radius", "Radius (m) of the deployment", radiusMeters);
76 cmd.Parse(argc, argv);
77
79
80 // Set up logging
81 LogComponentEnable("AlohaThroughput", LOG_LEVEL_ALL);
82
83 // Make all devices use SF7 (i.e., DR5)
84 // Config::SetDefault ("ns3::EndDeviceLorawanMac::DataRate", UintegerValue (5));
85
86 if (interferenceMatrix == "aloha")
87 {
89 }
90 else if (interferenceMatrix == "goursaud")
91 {
93 }
94
95 /***********
96 * Setup *
97 ***********/
98
99 // Mobility
101 mobility.SetPositionAllocator("ns3::UniformDiscPositionAllocator",
102 "rho",
104 "X",
105 DoubleValue(0.0),
106 "Y",
107 DoubleValue(0.0));
108 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
109
110 /************************
111 * Create the channel *
112 ************************/
113
114 // Create the lora channel object
116 loss->SetPathLossExponent(3.76);
117 loss->SetReference(1, 7.7);
118
120 {
121 // Create the correlated shadowing component
124
125 // Aggregate shadowing to the logdistance loss
126 loss->SetNext(shadowing);
127
128 // Add the effect to the channel propagation loss
130
131 shadowing->SetNext(buildingLoss);
132 }
133
135
137
138 /************************
139 * Create the helpers *
140 ************************/
141
142 // Create the LoraPhyHelper
143 LoraPhyHelper phyHelper = LoraPhyHelper();
144 phyHelper.SetChannel(channel);
145
146 // Create the LorawanMacHelper
149
150 // Create the LoraHelper
151 LoraHelper helper = LoraHelper();
152 helper.EnablePacketTracking(); // Output filename
153
154 // Create the NetworkServerHelper
156
157 // Create the ForwarderHelper
158 ForwarderHelper forHelper = ForwarderHelper();
159
160 /************************
161 * Create End Devices *
162 ************************/
163
164 // Create a set of nodes
165 NodeContainer endDevices;
166 endDevices.Create(nDevices);
167
168 // Assign a mobility model to each node
169 mobility.Install(endDevices);
170
171 // Make it so that nodes are at a certain height > 0
172 for (auto j = endDevices.Begin(); j != endDevices.End(); ++j)
173 {
174 Ptr<MobilityModel> mobility = (*j)->GetObject<MobilityModel>();
175 Vector position = mobility->GetPosition();
176 position.z = 1.2;
177 mobility->SetPosition(position);
178 }
179
180 // Create the LoraNetDevices of the end devices
181 uint8_t nwkId = 54;
182 uint32_t nwkAddr = 1864;
185
186 // Create the LoraNetDevices of the end devices
187 macHelper.SetAddressGenerator(addrGen);
190 helper.Install(phyHelper, macHelper, endDevices);
191
192 // Now end devices are connected to the channel
193
194 // Connect trace sources
195 for (auto j = endDevices.Begin(); j != endDevices.End(); ++j)
196 {
197 Ptr<Node> node = *j;
198 Ptr<LoraNetDevice> loraNetDevice = DynamicCast<LoraNetDevice>(node->GetDevice(0));
199 Ptr<LoraPhy> phy = loraNetDevice->GetPhy();
200 }
201
202 /*********************
203 * Create Gateways *
204 *********************/
205
206 // Create the gateway nodes (allocate them uniformly on the disc)
207 NodeContainer gateways;
208 gateways.Create(nGateways);
209
211 // Make it so that nodes are at a certain height > 0
212 allocator->Add(Vector(0.0, 0.0, 15.0));
213 mobility.SetPositionAllocator(allocator);
214 mobility.Install(gateways);
215
216 // Create a netdevice for each gateway
219 helper.Install(phyHelper, macHelper, gateways);
220
221 NS_LOG_DEBUG("Completed configuration");
222
223 /*********************************************
224 * Install applications on the end devices *
225 *********************************************/
226
227 Time appStopTime = Seconds(simulationTimeSeconds);
228 int packetSize = 50;
231 appHelper.SetPacketSize(packetSize);
232 ApplicationContainer appContainer = appHelper.Install(endDevices);
233
234 appContainer.Start(Time(0));
235 appContainer.Stop(appStopTime);
236
237 std::ofstream outputFile;
238 // Delete contents of the file as it is opened
239 outputFile.open("durations.txt", std::ofstream::out | std::ofstream::trunc);
240 for (uint8_t sf = 7; sf <= 12; sf++)
241 {
242 LoraTxParameters txParams;
243 txParams.sf = sf;
244 txParams.headerDisabled = false;
245 txParams.codingRate = CodingRate::CR_4_5;
246 txParams.bandwidthHz = 125000;
247 txParams.nPreamble = 8;
248 txParams.crcEnabled = true;
251
252 LoraFrameHeader frameHdr = LoraFrameHeader();
253 frameHdr.SetAsUplink();
254 frameHdr.SetFPort(1);
255 frameHdr.SetAddress(LoraDeviceAddress());
256 frameHdr.SetAdr(false);
257 frameHdr.SetAdrAckReq(false);
258 frameHdr.SetFCnt(0);
259 pkt->AddHeader(frameHdr);
260
263 macHdr.SetMajor(1);
264 pkt->AddHeader(macHdr);
265
266 outputFile << LoraPhy::GetOnAirTime(pkt, txParams).GetMicroSeconds() << " ";
267 }
268 outputFile.close();
269
270 /**************************
271 * Create network server *
272 ***************************/
273
274 // Create the network server node
275 Ptr<Node> networkServer = CreateObject<Node>();
276
277 // PointToPoint links between gateways and server
279 p2p.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
280 p2p.SetChannelAttribute("Delay", StringValue("2ms"));
281 // Store network server app registration details for later
282 P2PGwRegistration_t gwRegistration;
283 for (auto gw = gateways.Begin(); gw != gateways.End(); ++gw)
284 {
285 auto container = p2p.Install(networkServer, *gw);
286 auto serverP2PNetDev = DynamicCast<PointToPointNetDevice>(container.Get(0));
287 gwRegistration.emplace_back(serverP2PNetDev, *gw);
288 }
289
290 // Create a network server for the network
291 nsHelper.SetGatewaysP2P(gwRegistration);
292 nsHelper.SetEndDevices(endDevices);
293 nsHelper.Install(networkServer);
294
295 // Create a forwarder for each gateway
296 forHelper.Install(gateways);
297
298 // Install trace sources
299 for (auto node = gateways.Begin(); node != gateways.End(); node++)
300 {
301 DynamicCast<LoraNetDevice>((*node)->GetDevice(0))
302 ->GetPhy()
303 ->TraceConnectWithoutContext("ReceivedPacket", MakeCallback(OnPacketReceptionCallback));
304 }
305
306 // Install trace sources
307 for (auto node = endDevices.Begin(); node != endDevices.End(); node++)
308 {
309 DynamicCast<LoraNetDevice>((*node)->GetDevice(0))
310 ->GetPhy()
311 ->TraceConnectWithoutContext("StartSending", MakeCallback(OnTransmissionCallback));
312 }
313
314 LorawanMacHelper::SetSpreadingFactorsUp(endDevices, gateways, channel);
315
316 ////////////////
317 // Simulation //
318 ////////////////
319
320 Simulator::Stop(appStopTime + Hours(1));
321
322 NS_LOG_INFO("Running simulation...");
324
326
327 /////////////////////////////
328 // Print results to stdout //
329 /////////////////////////////
330 NS_LOG_INFO("Computing performance metrics...");
331
332 for (int i = 0; i < 6; i++)
333 {
334 std::cout << packetsSent.at(i) << " " << packetsReceived.at(i) << std::endl;
335 }
336
337 return 0;
338}
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.
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
Helper class used to assign positions and mobility models to nodes.
Keep track of the current position and velocity of an object.
keep track of a set of node pointers.
Iterator End() const
Get an iterator which indicates past-the-last Node in the 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.
Build a set of PointToPointNetDevice objects.
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
Hold variables of type string.
Definition string.h:45
Simulation virtual time values and global simulation resolution.
Definition nstime.h:95
int64_t GetMicroSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
Definition nstime.h:408
This class can be used to install Forwarder applications on a set of gateways.
ApplicationContainer Install(NodeContainer c) const
Install a Forwarder application on each node of the input container configured with all the attribute...
This class represents the device address of a LoraWAN end device.
This class represents the Frame header (FHDR) used in a LoraWAN network.
void SetFCnt(uint16_t fCnt)
Set the FCnt value.
void SetAdr(bool adr)
Set the value of the ADR bit field.
void SetAddress(LoraDeviceAddress address)
Set the address.
void SetAsUplink()
State that this is an uplink message.
void SetAdrAckReq(bool adrAckReq)
Set the value of the ADRACKReq bit field.
void SetFPort(uint8_t fPort)
Set the FPort value.
Helps to create LoraNetDevice objects.
Definition lora-helper.h:34
void EnablePacketTracking()
Enable tracking of packets via trace sources.
virtual NetDeviceContainer Install(const LoraPhyHelper &phyHelper, const LorawanMacHelper &macHelper, NodeContainer c) const
Install LoraNetDevices on a list of nodes.
static CollisionMatrix collisionMatrix
Collision matrix type set by the constructor.
Helper to install LoraPhy instances on multiple Nodes.
void SetDeviceType(enum DeviceType dt)
Set the kind of PHY this helper will create.
void SetChannel(Ptr< LoraChannel > channel)
Set the LoraChannel to connect the PHYs to.
static Time GetOnAirTime(Ptr< Packet > packet, LoraTxParameters txParams)
Compute the time that a packet with certain characteristics will take to be transmitted.
Definition lora-phy.cc:155
static Time GetTSym(LoraTxParameters txParams)
Compute the symbol time from spreading factor and bandwidth.
Definition lora-phy.cc:149
Tag used to save various data about a packet, like its Spreading Factor and data about interference.
Definition lora-tag.h:26
uint8_t GetSpreadingFactor() const
Read which Spreading Factor this packet was transmitted with.
Definition lora-tag.cc:80
This class represents the Mac header of a LoRaWAN packet.
void SetMajor(uint8_t major)
Set the major version of this header.
void SetMType(enum MType mtype)
Set the message type.
Helper class for configuring and installing the LorawanMac class on devices and gateways.
void SetDeviceType(enum DeviceType dt)
Set the kind of MAC this helper will create.
void SetAddressGenerator(Ptr< LoraDeviceAddressGenerator > addrGen)
Set the address generator to use for creation of these nodes.
static std::vector< int > SetSpreadingFactorsUp(NodeContainer endDevices, NodeContainer gateways, Ptr< LoraChannel > channel)
Initialize the end devices' data rate parameter.
void SetRegion(enum Regions region)
Set the region in which the device is to operate.
This class can install a NetworkServer application on a node.
void SetGatewaysP2P(const P2PGwRegistration_t &registration)
Register gateways connected with point-to-point to this network server.
void SetEndDevices(NodeContainer endDevices)
Set which end devices will be managed by this network server.
ApplicationContainer Install(Ptr< Node > node)
Create one lorawan network server application on the Node.
This class can be used to install PeriodicSender applications on a wide range of nodes.
void SetPeriod(Time period)
Set the period to be used by the applications created by this helper.
void SetPacketSize(uint8_t size)
Set the base value for applications packet size in bytes.
ApplicationContainer Install(NodeContainer c) const
Install a PeriodicSender application on each node of the input container configured with all the attr...
auto packetsReceived
Record received pkts by Data Rate (DR) [index 0 -> DR5, index 5 -> DR0].
void OnPacketReceptionCallback(Ptr< const Packet > packet, uint32_t receiverNodeId)
Record the correct reception of a packet by a gateway.
double simulationTimeSeconds
Scenario duration (s) in simulated time.
auto packetsSent
Record received pkts by Data Rate (DR) [index 0 -> DR5, index 5 -> DR0].
int nDevices
Number of end device nodes to create.
bool realisticChannelModel
Whether to use a more realistic channel model with buildings and correlated shadowing.
int nGateways
Number of gateway nodes to create.
double radiusMeters
Radius (m) of the deployment.
void OnTransmissionCallback(Ptr< const Packet > packet, uint32_t senderNodeId)
Record the beginning of a transmission by an end device.
int appPeriodSeconds
Duration (s) of the inter-transmission time of end devices.
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:690
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:194
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:260
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:267
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:627
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:454
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1273
Time Hours(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1244
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1290
std::list< std::pair< Ptr< PointToPointNetDevice >, Ptr< Node > > > P2PGwRegistration_t
Store network server app registration details for gateway nodes having a P2P link with the network se...
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:279
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:605
@ LOG_LEVEL_ALL
Print everything.
Definition log.h:108
channel
Definition third.py:77
mobility
Definition third.py:92
phy
Definition third.py:78
Structure to collect all parameters that are used to compute the duration of a packet (excluding payl...
Definition lora-phy.h:54
uint32_t nPreamble
Number of preamble symbols.
Definition lora-phy.h:59
CodingRate codingRate
Code rate (obtained as 4/(codingRate+4)).
Definition lora-phy.h:57
uint32_t bandwidthHz
Bandwidth in Hz.
Definition lora-phy.h:58
bool headerDisabled
Whether to use implicit header mode.
Definition lora-phy.h:56
bool lowDataRateOptimizationEnabled
Whether low data rate optimization is enabled.
Definition lora-phy.h:61
bool crcEnabled
Whether Cyclic Redundancy Check (CRC) is enabled.
Definition lora-phy.h:60
uint8_t sf
Spreading Factor.
Definition lora-phy.h:55
static const uint32_t packetSize
Packet size generated at the AP.