17#include "ns3/energy-source-container.h"
19#include "ns3/simulator.h"
36 TypeId(
"ns3::EndDeviceLorawanMac")
38 .SetGroupName(
"lorawan")
39 .AddTraceSource(
"RequiredTransmissions",
40 "Total number of transmissions required to deliver this packet",
42 "ns3::TracedValueCallback::uint8_t")
43 .AddAttribute(
"DataRate",
44 "Data rate currently employed by this end device",
48 .AddTraceSource(
"DataRate",
49 "Data rate currently employed by this end device",
51 "ns3::TracedValueCallback::uint8_t")
54 "Ensure to the network server that this device will accept data rate, transmission "
55 "power and number of retransmissions configurations received via LinkADRReq.",
59 .AddTraceSource(
"TxPower",
60 "Transmission ERP [dBm] currently employed by this end device",
62 "ns3::TracedValueCallback::Double")
63 .AddTraceSource(
"LastKnownLinkMargin",
64 "Last known demodulation margin in "
65 "communications between this end device "
68 "ns3::TracedValueCallback::uint8_t")
69 .AddTraceSource(
"LastKnownGatewayCount",
70 "Last known number of gateways able to "
71 "listen to this end device",
73 "ns3::TracedValueCallback::uint8_t")
74 .AddTraceSource(
"AggregatedDutyCycle",
75 "Aggregate duty cycle, in fraction form, "
76 "this end device must respect",
78 "ns3::TracedValueCallback::Double")
79 .AddAttribute(
"MaxTransmissions",
80 "Maximum number of transmissions for a packet (NbTrans)",
84 .AddAttribute(
"EnableEDDataRateAdaptation",
85 "Whether the end device should up its data rate "
86 "in case it doesn't get a reply from the network server.",
90 .AddAttribute(
"MType",
91 "Specify type of message will be sent by this end device.",
102 : m_enableDRAdapt(false),
108 m_headerDisabled(false),
112 m_receiveWindowDurationInSymbols(8),
116 m_lastKnownLinkMarginDb(0),
117 m_lastKnownGatewayCount(0),
118 m_aggregatedDutyCycle(1),
172 NS_LOG_INFO(
"Max number of transmission achieved: packet not transmitted.");
181 " The selected power is too high to be supported by this channel.");
193 NS_LOG_WARN(
"Attempting to send, but the aggregate duty cycle won't allow it. Scheduling a tx "
206 "Received a new packet from application. Resetting retransmission parameters.");
213 packet->AddHeader(frameHdr);
216 NS_LOG_INFO(
"Added frame header of size " << fhdrSize <<
" bytes.");
221 NS_LOG_WARN(
"Attempting to send a packet larger than the maximum allowed"
222 <<
" size at this Data Rate (DR" <<
unsigned(
m_dataRate)
223 <<
"). Transmission canceled.");
230 packet->AddHeader(macHdr);
240 NS_LOG_DEBUG(
" Received new packet from the application layer: stopping retransmission "
242 <<
unsigned(txs) <<
" transmissions out of a maximum of "
261 NS_LOG_DEBUG(
"It is a confirmed packet. Setting retransmission parameters and "
262 "decreasing the number of transmissions left.");
265 NS_LOG_INFO(
"Added MAC header of size " << mhdrSize <<
" bytes.");
289 packet->RemoveHeader(macHdr);
290 packet->RemoveHeader(frameHdr);
295 packet->AddHeader(frameHdr);
298 NS_LOG_INFO(
"Added frame header of size " << fhdrSize <<
" bytes.");
303 packet->AddHeader(macHdr);
342 NS_LOG_INFO(
"The message is an ACK, not waiting for it anymore.");
344 NS_LOG_DEBUG(
"Reset retransmission variables to default values and cancel "
345 "retransmission if already scheduled.");
350 <<
unsigned(txs) <<
" transmissions: stopping retransmission procedure. ");
358 "Received downlink message not containing an ACK while we were waiting for it!");
371 OnLinkCheckAns(linkCheckAns->GetMargin(), linkCheckAns->GetGwCnt());
378 linkAdrReq->GetTxPower(),
379 linkAdrReq->GetChMask(),
380 linkAdrReq->GetChMaskCntl(),
381 linkAdrReq->GetNbTrans());
394 rxParamSetupReq->GetRx2DataRate(),
395 rxParamSetupReq->GetFrequency());
408 newChannelReq->GetFrequency(),
409 newChannelReq->GetMinDataRate(),
410 newChannelReq->GetMaxDataRate());
491 if (channel && channel->IsEnabledForUplink())
498 NS_LOG_DEBUG(
"frequency=" << channel->GetFrequency() <<
"Hz,"
499 <<
" waitTime=" << waitTime.As(
Time::S));
510 std::vector<Ptr<LogicalLoraChannel>> candidates;
513 if (channel && channel->IsEnabledForUplink())
515 uint8_t minDr = channel->GetMinimumDataRate();
516 uint8_t maxDr = channel->GetMaximumDataRate();
519 << channel->GetFrequency() <<
" Hz, minDr=" <<
unsigned(minDr)
520 <<
", maxDr=" <<
unsigned(maxDr) <<
", waitTime=" << waitTime.
As(
Time::S));
523 candidates.emplace_back(channel);
527 if (candidates.empty())
532 uint8_t i =
m_uniformRV->GetInteger(0, candidates.size() - 1);
533 auto channel = candidates.at(i);
534 NS_LOG_DEBUG(
"Selected channel with frequency=" << channel->GetFrequency() <<
" Hz");
645 NS_LOG_FUNCTION(
this <<
unsigned(dataRate) <<
unsigned(txPower) << std::bitset<16>(chMask)
646 <<
unsigned(chMaskCntl) <<
unsigned(nbTrans));
651 NS_ASSERT_MSG(!(dataRate & 0xF0),
"dataRate field > 4 bits");
653 NS_ASSERT_MSG(!(chMaskCntl & 0xF8),
"chMaskCntl field > 3 bits");
658 bool channelMaskAck =
true;
659 bool dataRateAck =
true;
660 bool powerAck =
true;
662 NS_LOG_DEBUG(
"Channel mask = " << std::bitset<16>(chMask)
663 <<
", ChMaskCtrl = " <<
unsigned(chMaskCntl));
671 for (
size_t i = 0; i < channels.size(); ++i)
673 if ((chMask & 0b1 << i) && !channels.at(i))
676 channelMaskAck =
false;
684 for (
size_t i = 0; i < channels.size(); ++i)
694 channelMaskAck =
false;
702 channelMaskAck =
false;
711 bool compatible =
false;
713 for (
size_t i = 0; i < channels.size(); ++i)
715 if ((chMask & 0b1 << i) &&
m_dataRate >= channels.at(i)->GetMinimumDataRate() &&
716 m_dataRate <= channels.at(i)->GetMaximumDataRate())
724 NS_LOG_WARN(
"Invalid channel mask for current device data rate (ADR off)");
725 channelMaskAck = dataRateAck = powerAck =
false;
729 for (
size_t i = 0; i < channels.size(); ++i)
731 if (
auto c = channels.at(i); c)
733 (chMask & 0b1 << i) ? c->EnableForUplink() : c->DisableForUplink();
736 dataRateAck = powerAck =
false;
742 dataRateAck = powerAck =
false;
749 bool compatible =
false;
751 for (
size_t i = 0; i < channels.size(); ++i)
753 if (chMask & 0b1 << i)
755 if (
const auto& c = channels.at(i); c)
757 if (dataRate >= c->GetMinimumDataRate() &&
758 dataRate <= c->GetMaximumDataRate())
793 if (channelMaskAck && dataRateAck && powerAck)
795 for (
size_t i = 0; i < channels.size(); ++i)
797 if (
auto c = channels.at(i); c)
799 (chMask & 0b1 << i) ? c->EnableForUplink() : c->DisableForUplink();
806 m_nbTrans = (nbTrans == 0) ? 1 : nbTrans;
825 NS_ASSERT_MSG(!(maxDutyCycle & 0xF0),
"maxDutyCycle > 4 bits");
836 uint8_t battery = 255;
840 sc && sc->GetN() == 1)
842 battery = sc->Get(0)->GetEnergyFraction() * 253 + 1.5;
853 snr = snr < -32 ? -32 : snr > 31 ? 31 : snr;
855 uint8_t margin = std::bitset<6>(snr).to_ulong();
867 NS_LOG_FUNCTION(
this <<
unsigned(chIndex) << frequencyHz <<
unsigned(minDataRate)
868 <<
unsigned(maxDataRate));
870 NS_ASSERT_MSG(!(minDataRate & 0xF0),
"minDataRate field > 4 bits");
871 NS_ASSERT_MSG(!(maxDataRate & 0xF0),
"maxDataRate field > 4 bits");
876 bool dataRateRangeOk =
true;
877 bool channelFrequencyOk =
true;
880 if (chIndex < 3 || chIndex >
m_channelHelper->GetRawChannelArray().size() - 1)
883 dataRateRangeOk = channelFrequencyOk =
false;
887 if (frequencyHz != 0 && !
m_channelHelper->IsFrequencyValid(frequencyHz))
890 channelFrequencyOk =
false;
897 dataRateRangeOk =
false;
903 dataRateRangeOk =
false;
906 if (maxDataRate < minDataRate)
909 dataRateRangeOk =
false;
912 if (dataRateRangeOk && channelFrequencyOk)
915 (frequencyHz == 0) ? channel->DisableForUplink() : channel->EnableForUplink();
917 NS_LOG_DEBUG(
"MacTxFrequency[" <<
unsigned(chIndex) <<
"]=" << frequencyHz
918 <<
", DrMin=" <<
unsigned(minDataRate)
919 <<
", DrMax=" <<
unsigned(maxDataRate));
Hold variables of type enum.
An identifier for simulation events.
void Cancel()
This method is syntactic sugar for the ns3::Simulator::Cancel method.
Hold a signed integer type.
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.
static void Cancel(const EventId &id)
Set the cancel bit on this event: the event's associated function will not be invoked when it expires...
Simulation virtual time values and global simulation resolution.
TimeWithUnit As(const Unit unit=Time::AUTO) const
Attach a unit to a Time, to facilitate output in a specific unit.
bool IsStrictlyPositive() const
Exactly equivalent to t > 0.
static Time Max()
Maximum representable Time Not to be confused with Max(Time,Time).
bool IsZero() const
Exactly equivalent to t == 0.
a unique identifier for an interface.
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Hold an unsigned integer type.
Holds a vector of ns3::EnergySource pointers.
LorawanMacHeader::MType m_mType
The message type to apply to packets sent with the Send method.
void FailedReception(Ptr< const Packet > packet) override
Function called by lower layers to inform this layer that reception of a packet we were locked on fai...
void OnLinkAdrReq(uint8_t dataRate, uint8_t txPower, uint16_t chMask, uint8_t chMaskCntl, uint8_t nbTrans)
Perform the actions that need to be taken when receiving a LinkAdrReq command.
void OnDutyCycleReq(uint8_t maxDutyCycle)
Perform the actions that need to be taken when receiving a DutyCycleReq command.
TracedValue< double > m_txPowerDbm
The transmission ERP [dBm] this device is currently using.
~EndDeviceLorawanMac() override
Destructor.
virtual void postponeTransmission(Time nextTxDelay, Ptr< Packet > packet)
Postpone transmission to the specified time and delete previously scheduled transmissions if present.
virtual void SendToPhy(Ptr< Packet > packet)
Add headers and send a packet with the sending function of the physical layer.
Ptr< LogicalLoraChannel > GetChannelForTx()
Find a suitable channel for transmission.
double GetTransmissionPowerDbm()
Get the transmission power this end device is set to use.
bool m_adr
Uplink ADR bit contained in the FCtrl field of the LoRaWAN FHDR.
bool m_enableDRAdapt
Enable data rate adaptation (ADR) during the retransmission procedure.
void TxFinished(Ptr< const Packet > packet) override
Perform actions after sending a packet.
void SetUplinkAdrBit(bool adr)
Signals to the network server that this device will or may not comply with LinkADRReq settings (data ...
Ptr< UniformRandomVariable > m_uniformRV
An uniform random variable, used to randomly pick from the channel list.
static TypeId GetTypeId()
Register this type.
uint8_t GetLastKnownLinkMarginDb() const
Get the last known link margin from the demodulation floor.
TracedValue< double > m_aggregatedDutyCycle
The aggregated duty cycle this device needs to respect across all sub-bands.
double GetAggregatedDutyCycle()
Get the aggregated duty cycle.
void Receive(Ptr< const Packet > packet) override
Receive a packet from the lower layer.
void SetMType(LorawanMacHeader::MType mType)
Set the message type to send when the Send method is called.
virtual void resetRetransmissionParameters()
Reset retransmission parameters contained in the structure LoraRetxParams.
void ParseCommands(LoraFrameHeader frameHeader)
Parse and take action on the commands contained on this FrameHeader.
virtual void OnRxParamSetupReq(uint8_t rx1DrOffset, uint8_t rx2DataRate, double frequencyHz)=0
Perform the actions that need to be taken when receiving a RxParamSetupReq command based on the Devic...
void OnNewChannelReq(uint8_t chIndex, uint32_t frequencyHz, uint8_t minDataRate, uint8_t maxDataRate)
Perform the actions that need to be taken when receiving a NewChannelReq command.
void ApplyNecessaryOptions(LoraFrameHeader &frameHeader)
Add the necessary options and MAC commands to the LoraFrameHeader.
TracedCallback< uint8_t, bool, Time, Ptr< Packet > > m_requiredTxCallback
The trace source fired when the transmission procedure is finished.
uint8_t GetMaxNumberOfTransmissions()
Get the max number of unacknowledged redundant transmissions of each packet.
void OnLinkCheckAns(uint8_t margin, uint8_t gwCnt)
Perform the actions that need to be taken when receiving a LinkCheckAns command.
EventId m_nextTx
The event of retransmitting a packet in a consecutive moment if an ACK is not received.
void SetMaxNumberOfTransmissions(uint8_t nbTrans)
Set the max number of unacknowledged redundant transmissions of each packet.
std::list< Ptr< MacCommand > > m_macCommandList
List of the MAC commands that need to be applied to the next UL packet.
TracedValue< uint8_t > m_dataRate
The data rate this device is using to transmit.
LoraDeviceAddress m_address
The address of this device.
bool GetUplinkAdrBit() const
Get the current value of the device's uplink ADR bit of the LoRaWAN FHDR.
void Send(Ptr< Packet > packet) override
Send a packet.
uint16_t m_currentFCnt
current value of the device frame counter.
EndDeviceLorawanMac()
Default constructor.
uint8_t GetLastKnownGatewayCount() const
Get the last known number of gateways concurrently receiving transmissions from the device.
void AddMacCommand(Ptr< MacCommand > macCommand)
Add a MAC command to the list of those that will be sent out in the next packet.
Time GetNextTransmissionDelay()
Find the base minimum wait time before the next possible transmission.
LorawanMacHeader::MType GetMType()
Get the message type to send when the Send method is called.
virtual void DoSend(Ptr< Packet > packet)
Checking if we are performing the transmission of a new packet or a retransmission,...
void OnDevStatusReq()
Perform the actions that need to be taken when receiving a DevStatusReq command.
LoraDeviceAddress GetDeviceAddress()
Get the network address of this device.
double m_lastRxSnr
Used to record the last reception SNR measurement to be included in the DevStatusAns.
TracedValue< uint8_t > m_lastKnownGatewayCount
The last known gateway count (i.e., gateways that are in communication range with this end device).
uint8_t m_nbTrans
Default number of unacknowledged redundant transmissions of each packet.
void SetDataRate(uint8_t dataRate)
Set the data rate this end device will use when transmitting.
TracedValue< uint8_t > m_lastKnownLinkMarginDb
The last known link margin in dB from the demodulation floor.
void SetTransmissionPowerDbm(double txPowerDbm)
Set the transmission power of this end device.
uint8_t GetDataRate()
Get the data rate this end device is set to use.
virtual Time GetNextClassTransmissionDelay(Time waitTime)
Find the minimum wait time before the next possible transmission based on end device's Class Type.
void SetDeviceAddress(LoraDeviceAddress address)
Set the network address of this device.
struct LoraRetxParameters m_retxParams
Structure containing the retransmission parameters for this device.
This class represents the device address of a LoraWAN end device.
Class representing the LoRaWAN MAC layer.
TracedCallback< Ptr< const Packet > > m_cannotSendBecauseDutyCycle
The trace source that is fired when a packet cannot be sent because of duty cycle limitations.
std::vector< uint32_t > m_maxAppPayloadForDataRate
A vector holding the maximum app payload size that corresponds to a certain data rate.
double GetDbmForTxPower(uint8_t txPower)
Get the transmission power in dBm that corresponds, in this region, to the encoded 8-bit txPower.
uint8_t GetSfFromDataRate(uint8_t dataRate)
Get the spreading factor corresponding to a data rate, based on this MAC's region.
double GetBandwidthFromDataRate(uint8_t dataRate)
Get the bandwidth corresponding to a data rate, based on this MAC's region.
Ptr< LogicalLoraChannelHelper > m_channelHelper
The LogicalLoraChannelHelper instance that is assigned to this MAC.
TracedCallback< Ptr< const Packet > > m_sentNewPacket
Trace source that is fired when a new APP layer packet arrives at the MAC layer.
Ptr< NetDevice > m_device
The device this MAC layer is installed on.
static uint8_t GetCIDFromMacCommand(enum MacCommandType commandType)
Get the CID that corresponds to a type of MAC command.
#define NS_ASSERT_MSG(condition, message)
At runtime, in debugging builds, if this condition is not true, the program prints the message to out...
#define NS_LOG_ERROR(msg)
Use NS_LOG to output a message of level LOG_ERROR.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
#define NS_LOG_FUNCTION_NOARGS()
Output the name of the function.
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_WARN(msg)
Use NS_LOG to output a message of level LOG_WARN.
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Time Now()
create an ns3::Time instance which contains the current simulation time.
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
MacCommandType
Enum for every possible command type.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< const AttributeChecker > MakeBooleanChecker()
Ptr< const AttributeChecker > MakeIntegerChecker()
Ptr< const AttributeAccessor > MakeIntegerAccessor(T1 a1)
Ptr< const AttributeChecker > MakeUintegerChecker()
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Ptr< const AttributeChecker > MakeEnumChecker(T v, std::string n, Ts... args)
Make an EnumChecker pre-configured with a set of allowed values by name.
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Ptr< const AttributeAccessor > MakeBooleanAccessor(T1 a1)
Ptr< const AttributeAccessor > MakeEnumAccessor(T1 a1)
Structure representing the parameters that will be used in the retransmission procedure.
bool waitingAck
Whether the packet requires explicit acknowledgment.
uint8_t retxLeft
Number of retransmission attempts left.
Time firstAttempt
Timestamp of the first transmission of the packet.
Ptr< Packet > packet
A pointer to the packet being retransmitted.