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/core-module.h"
16#include "ns3/lorawan-module.h"
17#include "ns3/mobility-helper.h"
18#include "ns3/point-to-point-helper.h"
19
20using namespace ns3;
21using namespace lorawan;
22
23NS_LOG_COMPONENT_DEFINE("FrameCounterUpdateExample");
24
25// Network settings
26int nGateways = 1; //!< Number of gateway nodes to create
27double simulationTimeSeconds = 3600; //!< Scenario duration (s) in simulated time
28
29/**
30 * Record a packet TX start by the PHY layer of an end device
31 *
32 * @param packet The packet being transmitted.
33 * @param index Id of end device transmitting the packet.
34 */
35void
37{
38 Ptr<Packet> packetCopy = packet->Copy();
39
41 packetCopy->RemoveHeader(mHdr);
42 LoraFrameHeader fHdr;
43 packetCopy->RemoveHeader(fHdr);
44
45 NS_LOG_DEBUG("Sent a packet with Frame Counter " << fHdr.GetFCnt());
46 // NS_LOG_DEBUG ("MAC Header:");
47 // NS_LOG_DEBUG (mHdr);
48 // NS_LOG_DEBUG ("Frame Header:");
49 // NS_LOG_DEBUG (fHdr);
50}
51
52/**
53 * Record the exit status of a MAC layer packet retransmission process of an end device
54 *
55 * @param transmissions Number of transmissions attempted during the process.
56 * @param successful Whether the retransmission procedure was successful.
57 * @param firstAttempt Timestamp of the initial transmission attempt.
58 * @param packet The packet being retransmitted.
59 */
60void
61OnMacPacketOutcome(uint8_t transmissions, bool successful, Time firstAttempt, Ptr<Packet> packet)
62{
63 if (successful)
64 {
65 NS_LOG_INFO("Packet was successful");
66 }
67 else
68 {
69 NS_LOG_INFO("Giving up");
70 }
71}
72
73/**
74 * Set the position of an end device as either in range or out of range.
75 *
76 * @param endDevice A pointer to the Node of the end device.
77 * @param inRange Whether to set the end device in range or out of range.
78 */
79void
80ChangeEndDevicePosition(Ptr<Node> endDevice, bool inRange)
81{
82 if (inRange)
83 {
84 NS_LOG_INFO("Moving end device in range");
85 endDevice->GetObject<MobilityModel>()->SetPosition(Vector(0.0, 0.0, 0.0));
86 }
87 else
88 {
89 NS_LOG_INFO("Moving end device out of range");
90 endDevice->GetObject<MobilityModel>()->SetPosition(Vector(10000.0, 0.0, 0.0));
91 }
92}
93
94int
95main(int argc, char* argv[])
96{
97 CommandLine cmd(__FILE__);
98 cmd.AddValue("simulationTime", "The time (s) for which to simulate", simulationTimeSeconds);
99 cmd.AddValue("MaxTransmissions", "ns3::EndDeviceLorawanMac::MaxTransmissions");
100 cmd.AddValue("MType", "ns3::EndDeviceLorawanMac::MType");
101 cmd.Parse(argc, argv);
102
103 // Set up logging
104 LogComponentEnable("FrameCounterUpdateExample", LOG_LEVEL_ALL);
105
106 /***********
107 * Setup *
108 ***********/
109
110 // Mobility
113 // Make it so that nodes are at a certain height > 0
114 allocator->Add(Vector(100000.0, 0.0, 15.0)); // End device position
115 allocator->Add(Vector(0.0, 0.0, 15.0)); // Gateway position
116 mobility.SetPositionAllocator(allocator);
117 mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
118
119 /************************
120 * Create the channel *
121 ************************/
122
123 // Create the lora channel object
125 loss->SetPathLossExponent(3.76);
126 loss->SetReference(1, 7.7);
127
129
131
132 /************************
133 * Create the helpers *
134 ************************/
135
136 // Create the LoraPhyHelper
137 LoraPhyHelper phyHelper = LoraPhyHelper();
138 phyHelper.SetChannel(channel);
139
140 // Create the LorawanMacHelper
142
143 // Create the LoraHelper
144 LoraHelper helper = LoraHelper();
145 helper.EnablePacketTracking(); // Output filename
146
147 // Create the NetworkServerHelper
149
150 // Create the ForwarderHelper
151 ForwarderHelper forHelper = ForwarderHelper();
152
153 /************************
154 * Create End Devices *
155 ************************/
156
157 // Create a set of nodes
158 NodeContainer endDevices;
159 endDevices.Create(1);
160
161 // Assign a mobility model to each node
162 mobility.Install(endDevices);
163
164 // Make it so that nodes are at a certain height > 0
165 for (auto j = endDevices.Begin(); j != endDevices.End(); ++j)
166 {
167 Ptr<MobilityModel> mobility = (*j)->GetObject<MobilityModel>();
168 Vector position = mobility->GetPosition();
169 position.z = 1.2;
170 mobility->SetPosition(position);
171 }
172
173 // Create the LoraNetDevices of the end devices
174 uint8_t nwkId = 54;
175 uint32_t nwkAddr = 1864;
178
179 // Create the LoraNetDevices of the end devices
180 macHelper.SetAddressGenerator(addrGen);
183 macHelper.Set("DataRate", UintegerValue(5));
184 helper.Install(phyHelper, macHelper, endDevices);
185
186 // Connect trace sources
187 for (auto j = endDevices.Begin(); j != endDevices.End(); ++j)
188 {
189 Ptr<Node> node = *j;
190 Ptr<LoraNetDevice> loraNetDevice = DynamicCast<LoraNetDevice>(node->GetDevice(0));
191 Ptr<LoraPhy> phy = loraNetDevice->GetPhy();
193 phy->TraceConnectWithoutContext("StartSending", MakeCallback(&OnPhySentPacket));
194 mac->TraceConnectWithoutContext("RequiredTransmissions", MakeCallback(&OnMacPacketOutcome));
195 }
196
197 // Create the gateway nodes (allocate them uniformly on the disc)
198 NodeContainer gateways;
199 gateways.Create(nGateways);
200
201 // Make it so that nodes are at a certain height > 0
202 mobility.SetPositionAllocator(allocator);
203 mobility.Install(gateways);
204
205 // Create a netdevice for each gateway
208 helper.Install(phyHelper, macHelper, gateways);
209
210 NS_LOG_INFO("Completed configuration");
211
212 /*********************************************
213 * Install applications on the end devices *
214 *********************************************/
215
216 Time appStopTime = Seconds(simulationTimeSeconds);
218 appHelper.SetSendTime(Time(0));
219 ApplicationContainer appContainer = appHelper.Install(endDevices);
220 appHelper.SetSendTime(Seconds(100));
221 appContainer.Add(appHelper.Install(endDevices));
222 appHelper.SetSendTime(Seconds(200));
223 appContainer.Add(appHelper.Install(endDevices));
224
225 appContainer.Start(Time(0));
226 appContainer.Stop(appStopTime);
227
228 Simulator::Schedule(Seconds(110), &ChangeEndDevicePosition, endDevices.Get(0), true);
229 Simulator::Schedule(Seconds(201), &ChangeEndDevicePosition, endDevices.Get(0), false);
230 Simulator::Schedule(Seconds(204), &ChangeEndDevicePosition, endDevices.Get(0), true);
231
232 /**************************
233 * Create network server *
234 ***************************/
235
236 // Create the network server node
237 Ptr<Node> networkServer = CreateObject<Node>();
238
239 // PointToPoint links between gateways and server
241 p2p.SetDeviceAttribute("DataRate", StringValue("5Mbps"));
242 p2p.SetChannelAttribute("Delay", StringValue("2ms"));
243 // Store network server app registration details for later
244 P2PGwRegistration_t gwRegistration;
245 for (auto gw = gateways.Begin(); gw != gateways.End(); ++gw)
246 {
247 auto container = p2p.Install(networkServer, *gw);
248 auto serverP2PNetDev = DynamicCast<PointToPointNetDevice>(container.Get(0));
249 gwRegistration.emplace_back(serverP2PNetDev, *gw);
250 }
251
252 // Create a network server for the network
253 nsHelper.SetGatewaysP2P(gwRegistration);
254 nsHelper.SetEndDevices(endDevices);
255 nsHelper.Install(networkServer);
256
257 // Create a forwarder for each gateway
258 forHelper.Install(gateways);
259
260 ////////////////
261 // Simulation //
262 ////////////////
263
264 Simulator::Stop(appStopTime + Hours(1));
265
266 NS_LOG_INFO("Running simulation...");
268
270
271 ///////////////////////////
272 // Print results to file //
273 ///////////////////////////
274
275 LoraPacketTracker& tracker = helper.GetPacketTracker();
276 NS_LOG_INFO("Printing total sent MAC-layer packets and successful MAC-layer packets");
277 std::cout << tracker.CountMacPacketsGlobally(Time(0), appStopTime + Hours(1)) << std::endl;
278
279 return 0;
280}
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.
Definition ptr.h:70
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:580
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
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:34
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...
double simulationTimeSeconds
Scenario duration (s) in simulated time.
int nGateways
Number of gateway nodes to create.
void OnPhySentPacket(Ptr< const Packet > packet, uint32_t index)
Record a packet TX start by the PHY layer of an end device.
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.
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_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
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
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
mac
Definition third.py:81
mobility
Definition third.py:92
phy
Definition third.py:78