18#include "ns3/simulator.h"
35 TypeId(
"ns3::EndDeviceLorawanMac")
37 .SetGroupName(
"lorawan")
38 .AddTraceSource(
"RequiredTransmissions",
39 "Total number of transmissions required to deliver this packet",
41 "ns3::TracedValueCallback::uint8_t")
42 .AddAttribute(
"DataRate",
43 "Data rate currently employed by this end device",
47 .AddTraceSource(
"DataRate",
48 "Data rate currently employed by this end device",
50 "ns3::TracedValueCallback::uint8_t")
53 "Whether to request the network server to control this device's data rate",
57 .AddTraceSource(
"TxPower",
58 "Transmission power currently employed by this end device",
60 "ns3::TracedValueCallback::Double")
61 .AddTraceSource(
"LastKnownLinkMargin",
62 "Last known demodulation margin in "
63 "communications between this end device "
66 "ns3::TracedValueCallback::Double")
67 .AddTraceSource(
"LastKnownGatewayCount",
68 "Last known number of gateways able to "
69 "listen to this end device",
71 "ns3::TracedValueCallback::Int")
72 .AddTraceSource(
"AggregatedDutyCycle",
73 "Aggregate duty cycle, in fraction form, "
74 "this end device must respect",
76 "ns3::TracedValueCallback::Double")
77 .AddAttribute(
"MaxTransmissions",
78 "Maximum number of transmissions for a packet",
82 .AddAttribute(
"EnableEDDataRateAdaptation",
83 "Whether the end device should up its data rate "
84 "in case it doesn't get a reply from the network server.",
88 .AddAttribute(
"MType",
89 "Specify type of message will be sent by this end device.",
96 .AddConstructor<EndDeviceLorawanMac>();
101 : m_enableDRAdapt(false),
107 m_headerDisabled(false),
111 m_receiveWindowDurationInSymbols(8),
113 m_controlDataRate(false),
114 m_lastKnownLinkMargin(0),
115 m_lastKnownGatewayCount(0),
116 m_aggregatedDutyCycle(1),
170 NS_LOG_INFO(
"Max number of transmission achieved: packet not transmitted.");
179 " The selected power is too high to be supported by this channel.");
191 NS_LOG_WARN(
"Attempting to send, but the aggregate duty cycle won't allow it. Scheduling a tx "
204 "Received a new packet from application. Resetting retransmission parameters.");
211 packet->AddHeader(frameHdr);
218 NS_LOG_WARN(
"Attempting to send a packet larger than the maximum allowed"
219 <<
" size at this Data Rate (DR" <<
unsigned(
m_dataRate)
220 <<
"). Transmission canceled.");
227 packet->AddHeader(macHdr);
237 NS_LOG_DEBUG(
" Received new packet from the application layer: stopping retransmission "
239 <<
unsigned(txs) <<
" transmissions out of a maximum of "
258 NS_LOG_DEBUG(
"It is a confirmed packet. Setting retransmission parameters and "
259 "decreasing the number of transmissions left.");
285 packet->RemoveHeader(macHdr);
286 packet->RemoveHeader(frameHdr);
291 packet->AddHeader(frameHdr);
298 packet->AddHeader(macHdr);
337 NS_LOG_INFO(
"The message is an ACK, not waiting for it anymore.");
339 NS_LOG_DEBUG(
"Reset retransmission variables to default values and cancel "
340 "retransmission if already scheduled.");
345 <<
unsigned(txs) <<
" transmissions: stopping retransmission procedure. ");
353 "Received downlink message not containing an ACK while we were waiting for it!");
357 std::list<Ptr<MacCommand>> commands = frameHeader.
GetCommands();
358 std::list<Ptr<MacCommand>>::iterator it;
359 for (it = commands.begin(); it != commands.end(); it++)
372 OnLinkCheckAns(linkCheckAns->GetMargin(), linkCheckAns->GetGwCnt());
384 linkAdrReq->GetTxPower(),
385 linkAdrReq->GetEnabledChannelsList(),
386 linkAdrReq->GetRepetitions());
431 newChannelReq->GetFrequency(),
432 newChannelReq->GetMinDataRate(),
433 newChannelReq->GetMaxDataRate());
514 std::vector<Ptr<LogicalLoraChannel>> logicalChannels;
522 std::vector<Ptr<LogicalLoraChannel>>::iterator it;
523 for (it = logicalChannels.begin(); it != logicalChannels.end(); ++it)
527 double frequency = logicalChannel->GetFrequency();
529 waitingTime = std::min(waitingTime,
m_channelHelper->GetWaitingTime(logicalChannel));
531 NS_LOG_DEBUG(
"Waiting time before the next transmission in channel with frequency "
532 << frequency <<
" is = " << waitingTime.
GetSeconds() <<
".");
546 std::vector<Ptr<LogicalLoraChannel>> logicalChannels;
549 logicalChannels =
Shuffle(logicalChannels);
552 std::vector<Ptr<LogicalLoraChannel>>::iterator it;
553 for (it = logicalChannels.begin(); it != logicalChannels.end(); ++it)
557 double frequency = logicalChannel->GetFrequency();
559 NS_LOG_DEBUG(
"Frequency of the current channel: " << frequency);
573 NS_LOG_DEBUG(
"Packet cannot be immediately transmitted on "
574 <<
"the current channel because of duty cycle limitations.");
580std::vector<Ptr<LogicalLoraChannel>>
585 int size = vector.size();
587 for (
int i = 0; i < size; ++i)
589 uint16_t random = std::floor(
m_uniformRV->GetValue(0, size));
591 vector.at(random) = vector.at(i);
686 std::list<int> enabledChannels,
689 NS_LOG_FUNCTION(
this <<
unsigned(dataRate) <<
unsigned(txPower) << repetitions);
692 bool channelMaskOk =
true;
693 bool dataRateOk =
true;
694 bool txPowerOk =
true;
700 int channelListSize = channelList.size();
702 for (
auto it = enabledChannels.begin(); it != enabledChannels.end(); it++)
704 if ((*it) > channelListSize)
706 channelMaskOk =
false;
720 if (sf == 0 || bw == 0)
729 if (dataRateOk && channelMaskOk)
731 bool foundAvailableChannel =
false;
732 for (
auto it = enabledChannels.begin(); it != enabledChannels.end(); it++)
734 NS_LOG_DEBUG(
"MinDR: " <<
unsigned(channelList.at(*it)->GetMinimumDataRate()));
735 NS_LOG_DEBUG(
"MaxDR: " <<
unsigned(channelList.at(*it)->GetMaximumDataRate()));
736 if (channelList.at(*it)->GetMinimumDataRate() <= dataRate &&
737 channelList.at(*it)->GetMaximumDataRate() >= dataRate)
739 foundAvailableChannel =
true;
744 if (!foundAvailableChannel)
759 NS_LOG_DEBUG(
"Finished checking. ChannelMaskOk: " << channelMaskOk <<
", "
760 <<
"DataRateOk: " << dataRateOk <<
", "
761 <<
"txPowerOk: " << txPowerOk);
765 if (channelMaskOk && dataRateOk && txPowerOk)
770 if (std::find(enabledChannels.begin(), enabledChannels.end(), i) !=
771 enabledChannels.end())
801 NS_ASSERT(0 <= dutyCycle && dutyCycle < 1);
830 uint8_t battery = 10;
846 bool dataRateRangeOk =
true;
847 bool channelFrequencyOk =
true;
880 NS_LOG_FUNCTION(
this <<
unsigned(chIndex) << frequency <<
unsigned(minDataRate)
881 <<
unsigned(maxDataRate));
892 double maxTxPowerDbm)
896 m_channelHelper->AddSubBand(startFrequency, endFrequency, dutyCycle, maxTxPowerDbm);
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...
static Time Now()
Return the current simulation virtual time.
Simulation virtual time values and global simulation resolution.
double GetSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
static Time Max()
Maximum representable Time Not to be confused with Max(Time,Time).
a unique identifier for an interface.
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Hold an unsigned integer type.
LorawanMacHeader::MType m_mType
The message type to apply to packets sent with the Send method.
uint8_t m_maxNumbTx
Default number of unacknowledged redundant transmissions of each packet.
TracedValue< int > m_lastKnownGatewayCount
The last known gateway count (i.e., gateways that are in communication range with this end device).
bool GetDataRateAdaptation() const
Get if data rate adaptation is enabled or not.
void SetLogicalChannel(uint8_t chIndex, double frequency, uint8_t minDataRate, uint8_t maxDataRate)
Set a new logical channel in the helper.
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...
virtual void OnRxClassParamSetupReq(Ptr< RxParamSetupReq > rxParamSetupReq)
Perform the actions that need to be taken when receiving a RxParamSetupReq command based on the Devic...
void AddSubBand(double startFrequency, double endFrequency, double dutyCycle, double maxTxPowerDbm)
Add a subband to the logical channel helper.
bool m_controlDataRate
Whether this device's data rate should be controlled by the network server.
~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.
void OnDutyCycleReq(double dutyCycle)
Perform the actions that need to be taken when receiving a DutyCycleReq command.
TracedValue< double > m_txPower
The transmission power this device is using to transmit.
bool m_enableDRAdapt
Enable data rate adaptation (ADR) during the retransmission procedure.
void TxFinished(Ptr< const Packet > packet) override
Perform the actions that are required after a packet send.
Ptr< UniformRandomVariable > m_uniformRV
An uniform random variable, used by the Shuffle method to randomly reorder the channel list.
void OnRxParamSetupReq(Ptr< RxParamSetupReq > rxParamSetupReq)
Perform the actions that need to be taken when receiving a RxParamSetupReq command.
static TypeId GetTypeId()
Register this type.
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.
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.
virtual Time GetNextClassTransmissionDelay(Time waitingTime)
Find the minimum waiting time before the next possible transmission based on end device's Class Type.
void ParseCommands(LoraFrameHeader frameHeader)
Parse and take action on the commands contained on this FrameHeader.
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.
virtual uint8_t GetTransmissionPower()
Get the transmission power this end device is set to use.
uint8_t GetMaxNumberOfTransmissions()
Get the max number of unacknowledged redundant transmissions of each packet.
void SetDataRateAdaptation(bool adapt)
Enable data rate adaptation in the retransmitting procedure.
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 OnLinkAdrReq(uint8_t dataRate, uint8_t txPower, std::list< int > enabledChannels, int repetitions)
Perform the actions that need to be taken when receiving a LinkAdrReq command.
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.
void Send(Ptr< Packet > packet) override
Send a packet.
uint16_t m_currentFCnt
current value of the device frame counter.
EndDeviceLorawanMac()
Default constructor.
void AddMacCommand(Ptr< MacCommand > macCommand)
Add a MAC command to the list of those that will be sent out in the next packet.
void SetMaxNumberOfTransmissions(uint8_t maxNumbTx)
Set the max number of unacknowledged redundant transmissions of each packet.
TracedValue< double > m_lastKnownLinkMargin
The last known link margin.
void AddLogicalChannel(double frequency)
Add a logical channel to the helper.
Time GetNextTransmissionDelay()
Find the base minimum waiting time before the next possible transmission.
std::vector< Ptr< LogicalLoraChannel > > Shuffle(std::vector< Ptr< LogicalLoraChannel > > vector)
Randomly shuffle a Ptr<LogicalLoraChannel> vector.
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.
void OnNewChannelReq(uint8_t chIndex, double frequency, uint8_t minDataRate, uint8_t maxDataRate)
Perform the actions that need to be taken when receiving a NewChannelReq command.
void SetDataRate(uint8_t dataRate)
Set the data rate this end device will use when transmitting.
uint8_t GetDataRate()
Get the data rate this end device is set to use.
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.
static uint8_t GetCIDFromMacCommand(enum MacCommandType commandType)
Get the CID that corresponds to a type of MAC command.
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
#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.
Time Seconds(double value)
Construct a Time in the indicated unit.
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.