A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
adr-component.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2018 University of Padova
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Matteo Perin <matteo.perin.2@studenti.unipd.it
7 */
8
9#include "adr-component.h"
10
12
13#include "ns3/log.h"
14
15namespace ns3
16{
17namespace lorawan
18{
19
20////////////////////////////////////////
21// LinkAdrRequest commands management //
22////////////////////////////////////////
23
24NS_LOG_COMPONENT_DEFINE("AdrComponent");
25
27
28TypeId
30{
31 static TypeId tid =
32 TypeId("ns3::AdrComponent")
33 .SetGroupName("lorawan")
35 .SetParent<NetworkControllerComponent>()
36 .AddAttribute("MultipleGwCombiningMethod",
37 "Whether to average the received power of gateways or to use the maximum",
41 "avg",
43 "max",
45 "min"))
46 .AddAttribute("MultiplePacketsCombiningMethod",
47 "Whether to average SNRs from multiple packets or to use the maximum",
51 "avg",
53 "max",
55 "min"))
56 .AddAttribute("HistoryRange",
57 "Number of packets to use for averaging",
58 IntegerValue(20),
61 .AddAttribute("ChangeTransmissionPower",
62 "Whether to toggle the transmission power or not",
63 BooleanValue(true),
66 return tid;
67}
68
72
76
77void
80 Ptr<NetworkStatus> networkStatus)
81{
82 NS_LOG_FUNCTION(this->GetTypeId() << packet << networkStatus);
83
84 // We will only act just before reply, when all Gateways will have received
85 // the packet, since we need their respective received power.
86}
87
88void
90{
91 NS_LOG_FUNCTION(this << status << networkStatus);
92
93 Ptr<Packet> myPacket = status->GetLastPacketReceivedFromDevice()->Copy();
95 LoraFrameHeader fHdr;
96 fHdr.SetAsUplink();
97 myPacket->RemoveHeader(mHdr);
98 myPacket->RemoveHeader(fHdr);
99
100 // Execute the Adaptive Data Rate (ADR) algorithm only if the request bit is set
101 if (fHdr.GetAdr())
102 {
103 if (int(status->GetReceivedPacketList().size()) < historyRange)
104 {
105 NS_LOG_ERROR("Not enough packets received by this device ("
106 << status->GetReceivedPacketList().size()
107 << ") for the algorithm to work (need " << historyRange << ")");
108 }
109 else
110 {
111 NS_LOG_DEBUG("New Adaptive Data Rate (ADR) request");
112
113 // Get the spreading factor used by the device
114 uint8_t spreadingFactor = status->GetFirstReceiveWindowSpreadingFactor();
115
116 // Get the device transmission power (dBm)
117 double transmissionPowerDbm = status->GetMac()->GetTransmissionPowerDbm();
118
119 // New parameters for the end-device
120 uint8_t newDataRate;
121 double newTxPowerDbm;
122
123 // Adaptive Data Rate (ADR) Algorithm
124 AdrImplementation(&newDataRate, &newTxPowerDbm, status);
125
126 // Change the power back to the default if we don't want to change it
127 if (!m_toggleTxPower)
128 {
129 newTxPowerDbm = transmissionPowerDbm;
130 }
131
132 if (newDataRate != SfToDr(spreadingFactor) || newTxPowerDbm != transmissionPowerDbm)
133 {
134 // Create a list with mandatory channel indexes
135 int channels[] = {0, 1, 2};
136 std::list<int> enabledChannels(channels, channels + sizeof(channels) / sizeof(int));
137
138 // Repetitions Setting
139 const int rep = 1;
140
141 NS_LOG_DEBUG("Sending LinkAdrReq with DR = "
142 << (unsigned)newDataRate << " and TP = " << newTxPowerDbm << "dBm");
143
144 status->m_reply.frameHeader.AddLinkAdrReq(newDataRate,
145 GetTxPowerIndex(newTxPowerDbm),
146 enabledChannels,
147 rep);
148 status->m_reply.frameHeader.SetAsDownlink();
149 status->m_reply.macHeader.SetFType(LorawanMacHeader::UNCONFIRMED_DATA_DOWN);
150
151 status->m_reply.needsReply = true;
152 }
153 else
154 {
155 NS_LOG_DEBUG("Skipped request");
156 }
157 }
158 }
159 else
160 {
161 // Do nothing
162 }
163}
164
165void
167{
168 NS_LOG_FUNCTION(this->GetTypeId() << networkStatus);
169}
170
171void
173 double* newTxPower,
175{
176 // Compute the maximum or median SNR, based on the boolean value historyAveraging
177 double m_SNR = 0;
178 switch (historyAveraging)
179 {
181 m_SNR = GetAverageSNR(status->GetReceivedPacketList(), historyRange);
182 break;
184 m_SNR = GetMaxSNR(status->GetReceivedPacketList(), historyRange);
185 break;
187 m_SNR = GetMinSNR(status->GetReceivedPacketList(), historyRange);
188 }
189
190 NS_LOG_DEBUG("m_SNR = " << m_SNR);
191
192 // Get the spreading factor used by the device
193 uint8_t spreadingFactor = status->GetFirstReceiveWindowSpreadingFactor();
194
195 NS_LOG_DEBUG("SF = " << (unsigned)spreadingFactor);
196
197 // Get the device data rate and use it to get the SNR demodulation threshold
198 double req_SNR = threshold[SfToDr(spreadingFactor)];
199
200 NS_LOG_DEBUG("Required SNR = " << req_SNR);
201
202 // Get the device transmission power (dBm)
203 double transmissionPower = status->GetMac()->GetTransmissionPowerDbm();
204
205 NS_LOG_DEBUG("Transmission Power = " << transmissionPower);
206
207 // Compute the SNR margin taking into consideration the SNR of
208 // previously received packets
209 double margin_SNR = m_SNR - req_SNR;
210
211 NS_LOG_DEBUG("Margin = " << margin_SNR);
212
213 // Number of steps to decrement the spreading factor (thereby increasing the data rate)
214 // and the TP.
215 int steps = std::floor(margin_SNR / 3);
216
217 NS_LOG_DEBUG("steps = " << steps);
218
219 // If the number of steps is positive (margin_SNR is positive, so its
220 // decimal value is high) increment the data rate, if there are some
221 // leftover steps after reaching the maximum possible data rate
222 //(corresponding to the minimum spreading factor) decrement the transmission power as
223 // well for the number of steps left.
224 // If, on the other hand, the number of steps is negative (margin_SNR is
225 // negative, so its decimal value is low) increase the transmission power
226 //(note that the spreading factor is not incremented as this particular algorithm
227 // expects the node itself to raise its spreading factor whenever necessary).
228 while (steps > 0 && spreadingFactor > min_spreadingFactor)
229 {
230 spreadingFactor--;
231 steps--;
232 NS_LOG_DEBUG("Decreased SF by 1");
233 }
234 while (steps > 0 && transmissionPower > min_transmissionPower)
235 {
236 transmissionPower -= 2;
237 steps--;
238 NS_LOG_DEBUG("Decreased Ptx by 2");
239 }
240 while (steps < 0 && transmissionPower < max_transmissionPower)
241 {
242 transmissionPower += 2;
243 steps++;
244 NS_LOG_DEBUG("Increased Ptx by 2");
245 }
246
247 *newDataRate = SfToDr(spreadingFactor);
248 *newTxPower = transmissionPower;
249}
250
251uint8_t
253{
254 switch (sf)
255 {
256 case 12:
257 return 0;
258 break;
259 case 11:
260 return 1;
261 break;
262 case 10:
263 return 2;
264 break;
265 case 9:
266 return 3;
267 break;
268 case 8:
269 return 4;
270 break;
271 default:
272 return 5;
273 break;
274 }
275}
276
277double
278AdrComponent::RxPowerToSNR(double transmissionPower) const
279{
280 // The following conversion ignores interfering packets
281 return transmissionPower + 174 - 10 * log10(B) - NF;
282}
283
284// Get the maximum received power (it considers the values in dB!)
285double
287{
288 auto it = gwList.begin();
289 double min = it->second.rxPower;
290
291 for (; it != gwList.end(); it++)
292 {
293 if (it->second.rxPower < min)
294 {
295 min = it->second.rxPower;
296 }
297 }
298
299 return min;
300}
301
302// Get the maximum received power (it considers the values in dB!)
303double
305{
306 auto it = gwList.begin();
307 double max = it->second.rxPower;
308
309 for (; it != gwList.end(); it++)
310 {
311 if (it->second.rxPower > max)
312 {
313 max = it->second.rxPower;
314 }
315 }
316
317 return max;
318}
319
320// Get the maximum received power
321double
323{
324 double sum = 0;
325
326 for (auto it = gwList.begin(); it != gwList.end(); it++)
327 {
328 NS_LOG_DEBUG("Gateway at " << it->first << " has TP " << it->second.rxPower);
329 sum += it->second.rxPower;
330 }
331
332 double average = sum / gwList.size();
333
334 NS_LOG_DEBUG("TP (average) = " << average);
335
336 return average;
337}
338
339double
341{
342 switch (tpAveraging)
343 {
345 return GetAverageTxFromGateways(gwList);
347 return GetMaxTxFromGateways(gwList);
349 return GetMinTxFromGateways(gwList);
350 default:
351 return -1;
352 }
353}
354
355// TODO Make this more elegant
356double
358{
359 double m_SNR;
360
361 // Take elements from the list starting at the end
362 auto it = packetList.rbegin();
363 double min = RxPowerToSNR(GetReceivedPower(it->second.gwList));
364
365 for (int i = 0; i < historyRange; i++, it++)
366 {
367 m_SNR = RxPowerToSNR(GetReceivedPower(it->second.gwList));
368
369 NS_LOG_DEBUG("Received power: " << GetReceivedPower(it->second.gwList));
370 NS_LOG_DEBUG("m_SNR = " << m_SNR);
371
372 if (m_SNR < min)
373 {
374 min = m_SNR;
375 }
376 }
377
378 NS_LOG_DEBUG("SNR (min) = " << min);
379
380 return min;
381}
382
383double
385{
386 double m_SNR;
387
388 // Take elements from the list starting at the end
389 auto it = packetList.rbegin();
390 double max = RxPowerToSNR(GetReceivedPower(it->second.gwList));
391
392 for (int i = 0; i < historyRange; i++, it++)
393 {
394 m_SNR = RxPowerToSNR(GetReceivedPower(it->second.gwList));
395
396 NS_LOG_DEBUG("Received power: " << GetReceivedPower(it->second.gwList));
397 NS_LOG_DEBUG("m_SNR = " << m_SNR);
398
399 if (m_SNR > max)
400 {
401 max = m_SNR;
402 }
403 }
404
405 NS_LOG_DEBUG("SNR (max) = " << max);
406
407 return max;
408}
409
410double
412{
413 double sum = 0;
414 double m_SNR;
415
416 // Take elements from the list starting at the end
417 auto it = packetList.rbegin();
418 for (int i = 0; i < historyRange; i++, it++)
419 {
420 m_SNR = RxPowerToSNR(GetReceivedPower(it->second.gwList));
421
422 NS_LOG_DEBUG("Received power: " << GetReceivedPower(it->second.gwList));
423 NS_LOG_DEBUG("m_SNR = " << m_SNR);
424
425 sum += m_SNR;
426 }
427
428 double average = sum / historyRange;
429
430 NS_LOG_DEBUG("SNR (average) = " << average);
431
432 return average;
433}
434
435uint8_t
437{
438 NS_ASSERT_MSG(txPower >= 0 && txPower <= 14, "TxPower dBm value out of supported range");
439 NS_ASSERT_MSG(fmod(txPower, 2) == 0, "Invalid TxPower value");
440 return 7 - txPower / 2;
441}
442
443} // namespace lorawan
444} // namespace ns3
Hold variables of type enum.
Definition enum.h:52
Hold a signed integer type.
Definition integer.h:34
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:70
a unique identifier for an interface.
Definition type-id.h:50
TypeId AddConstructor()
Record in this TypeId the fact that the default constructor is accessible.
Definition type-id.h:719
TypeId SetGroupName(std::string groupName)
Set the group name.
Definition type-id.cc:1011
LinkAdrRequest commands management.
double GetAverageSNR(EndDeviceStatus::ReceivedPacketList packetList, int historyRange)
Get the average Signal to Noise Ratio (SNR) of the received packet history.
enum CombiningMethod historyAveraging
Received SNR history policy.
double GetMinSNR(EndDeviceStatus::ReceivedPacketList packetList, int historyRange)
Get the min Signal to Noise Ratio (SNR) of the receive packet history.
void OnReceivedPacket(Ptr< const Packet > packet, Ptr< EndDeviceStatus > status, Ptr< NetworkStatus > networkStatus) override
Function called as a new uplink packet is received by the NetworkServer application.
double threshold[6]
Vector containing the required SNR for the 6 allowed spreading factor levels ranging from 7 to 12 (th...
void OnFailedReply(Ptr< EndDeviceStatus > status, Ptr< NetworkStatus > networkStatus) override
Method that is called when a packet cannot be sent in the downlink.
AdrComponent()
Default constructor.
void AdrImplementation(uint8_t *newDataRate, double *newTxPower, Ptr< EndDeviceStatus > status)
Implementation of the default Adaptive Data Rate (ADR) procedure.
void BeforeSendingReply(Ptr< EndDeviceStatus > status, Ptr< NetworkStatus > networkStatus) override
Function called as a downlink reply is about to leave the NetworkServer application.
const int NF
Noise Figure (dB).
uint8_t GetTxPowerIndex(double txPower)
Get the LoRaWAN protocol TxPower parameter from the Equivalent Radiated Power (ERP) in dBm.
double GetMinTxFromGateways(EndDeviceStatus::GatewayList gwList)
Get the min RSSI (dBm) among gateways receiving the same transmission.
int historyRange
Number of previous packets to consider.
const int min_spreadingFactor
Spreading factor lower limit.
double GetMaxTxFromGateways(EndDeviceStatus::GatewayList gwList)
Get the max RSSI (dBm) among gateways receiving the same transmission.
enum CombiningMethod tpAveraging
TX power from gateways policy.
bool m_toggleTxPower
Whether to control transmission power of end devices or not.
double GetReceivedPower(EndDeviceStatus::GatewayList gwList)
Get RSSI metric for a transmission according to chosen gateway aggregation policy.
~AdrComponent() override
Destructor.
static TypeId GetTypeId()
Register this type.
const int B
Bandwidth (Hz).
double GetMaxSNR(EndDeviceStatus::ReceivedPacketList packetList, int historyRange)
Get the max Signal to Noise Ratio (SNR) of the receive packet history.
double RxPowerToSNR(double transmissionPower) const
Convert reception power values [dBm] to Signal to Noise Ratio (SNR) values [dB].
double GetAverageTxFromGateways(EndDeviceStatus::GatewayList gwList)
Get the average RSSI (dBm) of gateways receiving the same transmission.
const int min_transmissionPower
Minimum transmission power (dBm) (Europe).
uint8_t SfToDr(uint8_t sf)
Convert spreading factor values [7:12] to respective data rate values [0:5].
const int max_transmissionPower
Maximum transmission power (dBm) (Europe).
std::list< std::pair< Ptr< const Packet >, ReceivedPacketInfo > > ReceivedPacketList
typedef of a list of packets paired to their reception info.
std::map< Address, PacketInfoPerGw > GatewayList
typedef of a list of gateways with relative reception information.
This class represents the Frame header (FHDR) used in a LoraWAN network.
bool GetAdr() const
Get the value of the ADR bit field.
void SetAsUplink()
State that this is an uplink message.
This class represents the Mac header of a LoRaWAN packet.
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
Definition assert.h:76
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
Definition log.h:253
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:201
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:267
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition object-base.h:35
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< const AttributeChecker > MakeBooleanChecker()
Definition boolean.cc:113
Ptr< const AttributeChecker > MakeIntegerChecker()
Definition integer.h:99
Ptr< const AttributeAccessor > MakeIntegerAccessor(T1 a1)
Definition integer.h:35
Ptr< const AttributeChecker > MakeEnumChecker(T v, std::string n, Ts... args)
Make an EnumChecker pre-configured with a set of allowed values by name.
Definition enum.h:181
Ptr< const AttributeAccessor > MakeBooleanAccessor(T1 a1)
Definition boolean.h:70
Ptr< const AttributeAccessor > MakeEnumAccessor(T1 a1)
Definition enum.h:223