A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
frame-counter-update.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/*
10 * This script simulates a complex scenario with multiple gateways and end
11 * devices. The metric of interest for this script is the throughput of the
12 * network.
13 */
14
15#include "ns3/building-allocator.h"
16#include "ns3/building-penetration-loss.h"
17#include "ns3/buildings-helper.h"
18#include "ns3/callback.h"
19#include "ns3/class-a-end-device-lorawan-mac.h"
20#include "ns3/command-line.h"
21#include "ns3/constant-position-mobility-model.h"
22#include "ns3/correlated-shadowing-propagation-loss-model.h"
23#include "ns3/double.h"
24#include "ns3/end-device-lora-phy.h"
25#include "ns3/forwarder-helper.h"
26#include "ns3/gateway-lora-phy.h"
27#include "ns3/gateway-lorawan-mac.h"
28#include "ns3/log.h"
29#include "ns3/lora-helper.h"
30#include "ns3/lorawan-mac-header.h"
31#include "ns3/mobility-helper.h"
32#include "ns3/network-server-helper.h"
33#include "ns3/node-container.h"
34#include "ns3/one-shot-sender-helper.h"
35#include "ns3/periodic-sender-helper.h"
36#include "ns3/pointer.h"
37#include "ns3/position-allocator.h"
38#include "ns3/random-variable-stream.h"
39#include "ns3/simulator.h"
40
41#include <algorithm>
42#include <ctime>
43
44using namespace ns3;
45using namespace lorawan;
46
47NS_LOG_COMPONENT_DEFINE("FrameCounterUpdateExample");
48
49// Network settings
50int nGateways = 1; //!< Number of gateway nodes to create
51double simulationTimeSeconds = 3600; //!< Scenario duration (s) in simulated time
52
53/**
54 * Record a packet TX start by the PHY layer of an end device
55 *
56 * \param packet The packet being transmitted.
57 * \param index Id of end device transmitting the packet.
58 */
59void
61{
62 Ptr<Packet> packetCopy = packet->Copy();
63
65 packetCopy->RemoveHeader(mHdr);
66 LoraFrameHeader fHdr;
67 packetCopy->RemoveHeader(fHdr);
68
69 NS_LOG_DEBUG("Sent a packet with Frame Counter " << fHdr.GetFCnt());
70 // NS_LOG_DEBUG ("MAC Header:");
71 // NS_LOG_DEBUG (mHdr);
72 // NS_LOG_DEBUG ("Frame Header:");
73 // NS_LOG_DEBUG (fHdr);
74}
75
76/**
77 * Record the exit status of a MAC layer packet retransmission process of an end device
78 *
79 * \param transmissions Number of transmissions attempted during the process.
80 * \param successful Whether the retransmission procedure was successful.
81 * \param firstAttempt Timestamp of the initial transmission attempt.
82 * \param packet The packet being retransmitted.
83 */
84void
85OnMacPacketOutcome(uint8_t transmissions, bool successful, Time firstAttempt, Ptr<Packet> packet)
86{
87 if (successful)
88 {
89 NS_LOG_INFO("Packet was successful");
90 }
91 else
92 {
93 NS_LOG_INFO("Giving up");
94 }
95}
96
97/**
98 * Set the position of an end device as either in range or out of range.
99 *
100 * \param endDevice A pointer to the Node of the end device.
101 * \param inRange Whether to set the end device in range or out of range.
102 */
103void
104ChangeEndDevicePosition(Ptr<Node> endDevice, bool inRange)
105{
106 if (inRange)
107 {
108 NS_LOG_INFO("Moving end device in range");
109 endDevice->GetObject<MobilityModel>()->SetPosition(Vector(0.0, 0.0, 0.0));
110 }
111 else
112 {
113 NS_LOG_INFO("Moving end device out of range");
114 endDevice->GetObject<MobilityModel>()->SetPosition(Vector(10000.0, 0.0, 0.0));
115 }
116}
117
118int
119main(int argc, char* argv[])
120{
121 CommandLine cmd(__FILE__);
122 cmd.AddValue("simulationTime", "The time (s) for which to simulate", simulationTimeSeconds);
123 cmd.AddValue("MaxTransmissions", "ns3::EndDeviceLorawanMac::MaxTransmissions");
124 cmd.AddValue("MType", "ns3::EndDeviceLorawanMac::MType");
125 cmd.Parse(argc, argv);
126
127 // Set up logging
128 LogComponentEnable("FrameCounterUpdateExample", LOG_LEVEL_ALL);
129
130 /***********
131 * Setup *
132 ***********/
133
134 // Mobility
137 // Make it so that nodes are at a certain height > 0
138 allocator->Add(Vector(100000.0, 0.0, 15.0)); // End device position
139 allocator->Add(Vector(0.0, 0.0, 15.0)); // Gateway position
140 mobility.SetPositionAllocator(allocator);
141 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
142
143 /************************
144 * Create the channel *
145 ************************/
146
147 // Create the lora channel object
149 loss->SetPathLossExponent(3.76);
150 loss->SetReference(1, 7.7);
151
153
155
156 /************************
157 * Create the helpers *
158 ************************/
159
160 // Create the LoraPhyHelper
161 LoraPhyHelper phyHelper = LoraPhyHelper();
162 phyHelper.SetChannel(channel);
163
164 // Create the LorawanMacHelper
166
167 // Create the LoraHelper
168 LoraHelper helper = LoraHelper();
169 helper.EnablePacketTracking(); // Output filename
170
171 // Create the NetworkServerHelper
173
174 // Create the ForwarderHelper
175 ForwarderHelper forHelper = ForwarderHelper();
176
177 /************************
178 * Create End Devices *
179 ************************/
180
181 // Create a set of nodes
182 NodeContainer endDevices;
183 endDevices.Create(1);
184
185 // Assign a mobility model to each node
186 mobility.Install(endDevices);
187
188 // Make it so that nodes are at a certain height > 0
189 for (auto j = endDevices.Begin(); j != endDevices.End(); ++j)
190 {
191 Ptr<MobilityModel> mobility = (*j)->GetObject<MobilityModel>();
192 Vector position = mobility->GetPosition();
193 position.z = 1.2;
194 mobility->SetPosition(position);
195 }
196
197 // Create the LoraNetDevices of the end devices
198 uint8_t nwkId = 54;
199 uint32_t nwkAddr = 1864;
202
203 // Create the LoraNetDevices of the end devices
204 macHelper.SetAddressGenerator(addrGen);
207 macHelper.Set("DataRate", UintegerValue(5));
208 helper.Install(phyHelper, macHelper, endDevices);
209
210 // Connect trace sources
211 for (auto j = endDevices.Begin(); j != endDevices.End(); ++j)
212 {
213 Ptr<Node> node = *j;
214 Ptr<LoraNetDevice> loraNetDevice = DynamicCast<LoraNetDevice>(node->GetDevice(0));
215 Ptr<LoraPhy> phy = loraNetDevice->GetPhy();
217 phy->TraceConnectWithoutContext("StartSending", MakeCallback(&OnPhySentPacket));
218 mac->TraceConnectWithoutContext("RequiredTransmissions", MakeCallback(&OnMacPacketOutcome));
219 }
220
221 // Create the gateway nodes (allocate them uniformly on the disc)
222 NodeContainer gateways;
223 gateways.Create(nGateways);
224
225 // Make it so that nodes are at a certain height > 0
226 mobility.SetPositionAllocator(allocator);
227 mobility.Install(gateways);
228
229 // Create a netdevice for each gateway
232 helper.Install(phyHelper, macHelper, gateways);
233
234 NS_LOG_INFO("Completed configuration");
235
236 /*********************************************
237 * Install applications on the end devices *
238 *********************************************/
239
240 Time appStopTime = Seconds(simulationTimeSeconds);
242 appHelper.SetSendTime(Seconds(0));
243 ApplicationContainer appContainer = appHelper.Install(endDevices);
244 appHelper.SetSendTime(Seconds(100));
245 appContainer.Add(appHelper.Install(endDevices));
246 appHelper.SetSendTime(Seconds(200));
247 appContainer.Add(appHelper.Install(endDevices));
248
249 appContainer.Start(Seconds(0));
250 appContainer.Stop(appStopTime);
251
252 Simulator::Schedule(Seconds(110), &ChangeEndDevicePosition, endDevices.Get(0), true);
253 Simulator::Schedule(Seconds(201), &ChangeEndDevicePosition, endDevices.Get(0), false);
254 Simulator::Schedule(Seconds(204), &ChangeEndDevicePosition, endDevices.Get(0), true);
255
256 /**************************
257 * Create network server *
258 ***************************/
259
260 // Create the network server node
261 Ptr<Node> networkServer = CreateObject<Node>();
262
263 // PointToPoint links between gateways and server
265 p2p.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
266 p2p.SetChannelAttribute("Delay", StringValue("2ms"));
267 // Store network server app registration details for later
268 P2PGwRegistration_t gwRegistration;
269 for (auto gw = gateways.Begin(); gw != gateways.End(); ++gw)
270 {
271 auto container = p2p.Install(networkServer, *gw);
272 auto serverP2PNetDev = DynamicCast<PointToPointNetDevice>(container.Get(0));
273 gwRegistration.emplace_back(serverP2PNetDev, *gw);
274 }
275
276 // Create a network server for the network
277 nsHelper.SetGatewaysP2P(gwRegistration);
278 nsHelper.SetEndDevices(endDevices);
279 nsHelper.Install(networkServer);
280
281 // Create a forwarder for each gateway
282 forHelper.Install(gateways);
283
284 ////////////////
285 // Simulation //
286 ////////////////
287
288 Simulator::Stop(appStopTime + Hours(1));
289
290 NS_LOG_INFO("Running simulation...");
292
294
295 ///////////////////////////
296 // Print results to file //
297 ///////////////////////////
298
299 LoraPacketTracker& tracker = helper.GetPacketTracker();
300 NS_LOG_INFO("Printing total sent MAC-layer packets and successful MAC-layer packets");
301 std::cout << tracker.CountMacPacketsGlobally(Seconds(0), appStopTime + Hours(1)) << std::endl;
302
303 return 0;
304}
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 Add(ApplicationContainer other)
Append the contents of another ApplicationContainer to the end of this container.
Parse command-line arguments.
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.
Ptr< Node > Get(uint32_t i) const
Get the Ptr<Node> stored in this container at a given index.
Build a set of PointToPointNetDevice objects.
Smart pointer class similar to boost::intrusive_ptr.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:560
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
Hold variables of type string.
Definition string.h:45
Simulation virtual time values and global simulation resolution.
Definition nstime.h:94
Hold an unsigned integer type.
Definition uinteger.h:34
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 Frame header (FHDR) used in a LoraWAN network.
uint16_t GetFCnt() const
Get the FCnt value.
Helps to create LoraNetDevice objects.
Definition lora-helper.h:37
void EnablePacketTracking()
Enable tracking of packets via trace sources.
LoraPacketTracker & GetPacketTracker()
Get a reference to the Packet Tracker object.
virtual NetDeviceContainer Install(const LoraPhyHelper &phyHelper, const LorawanMacHelper &macHelper, NodeContainer c) const
Install LoraNetDevices on a list of nodes.
Tracks and stores packets sent in the simulation and provides aggregation functionality.
std::string CountMacPacketsGlobally(Time startTime, Time stopTime)
In a time interval, count packets to evaluate the global performance at MAC level of the whole networ...
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.
This class represents the Mac header of a LoRaWAN packet.
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.
void Set(std::string name, const AttributeValue &v)
Set an attribute of the underlying MAC object.
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 OneShotSender applications on multiple nodes at once.
void SetSendTime(Time sendTime)
Set the send time of the applications.
ApplicationContainer Install(NodeContainer c) const
Install a OneShotSender application on each node of the input container configured with all the attri...
void OnPhySentPacket(Ptr< const Packet > packet, uint32_t index)
Record a packet TX start by the PHY layer of an end device.
double simulationTimeSeconds
Scenario duration (s) in simulated time.
void OnMacPacketOutcome(uint8_t transmissions, bool successful, Time firstAttempt, Ptr< Packet > packet)
Record the exit status of a MAC layer packet retransmission process of an end device.
void ChangeEndDevicePosition(Ptr< Node > endDevice, bool inRange)
Set the position of an end device as either in range or out of range.
int nGateways
Number of gateway nodes to create.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:257
#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 Hours(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1284
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:291
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
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:580
@ LOG_LEVEL_ALL
Print everything.
Definition log.h:105
channel
Definition third.py:77
mac
Definition third.py:81
mobility
Definition third.py:92
phy
Definition third.py:78