LoRaWAN end device MAC layer for SX1272 and SX1276. Supports LoRaWAN-1.0 and LoRaWAN-1.1

Dependencies:   sx12xx_hal

Dependents:   LoRaWAN-SanJose_Bootcamp LoRaWAN-grove-cayenne LoRaWAN-classC-demo LoRaWAN-grove-cayenne ... more

radio chip selection

Radio chip driver is not included, because two options are available.
If you're using SX1272 or SX1276, then import sx127x driver into your program.
if you're using SX1261 or SX1262, then import sx126x driver into your program.
If you're using NAmote72 or Murata discovery, then you must import only sx127x driver.

application project requirements

This library requires mbed TLS to be enabled.
The file mbed_app.json must be present in the project using this library:

{
    "macros": [ "MBEDTLS_CMAC_C" ]
}

regional PHY selection

All end device configuration is done in Commissioning.h, define desired radio frequency band of operation in this header file.
Commissioning.h is located in the application using this library.

end device provisioning

End device is provisioned by editing Commissioning.h in the application which is using this library
To use LoRaWAN-1.0 OTA: make sure LORAWAN_ROOT_APPKEY is undefined.
To use LoRaWAN-1.1 OTA, define LORAWAN_ROOT_APPKEY.
To select OTA operation, define LORAWAN_JOIN_EUI, then LORAWAN_DEVICE_EUI must be defined, along with root key(s).
To select ABP operation, undefine LORAWAN_JOIN_EUI: then define session keys

LoRaWAN 1.0 nameLoRaWAN 1.1 nameComissioning.h defnedescription
OTADevEUIDevEUILORAWAN_DEVICE_EUIuniquely identifies end device
OTAAppEUIJoinEUILORAWAN_JOIN_EUI
OTAAppKeyNwkKeyLORAWAN_ROOT_NWKKEYroot key for network server
OTA(note 1)AppKeyLORAWAN_ROOT_APPKEYroot key for application server
ABPNwkSKey(note 3)LORAWAN_FNwkSIntKeynetwork session key
ABP(note 2)SNwkSIntKeyLORAWAN_SNwkSIntKeymac layer network integrity key
ABP(note 2)NwkSEncKeyLORAWAN_NwkSEncKeynetwork session encryption key
ABP(note 2)FNwkSIntKeyLORAWAN_FNwkSIntKeyforwarding network session integrity key
ABPAppSKeyAppSKeyLORAWAN_APPSKEYapplication session encryption key

(note 1): LoRaWAN-1.0 OTA uses a single root key for both network server and application server.

In LoRaWAN-1.0 OTA: the single root AppKey is used to generate NwkSkey and AppSKey.
(note 2): In LoRaWAN-1.0 (both OTA and ABP) SNwkSIntKey, NwkSEncKey. FNwkSIntKey are of same value and are collectively known as NwkSKey.
(note 3): LoRaWAN-1.0 uses single network session key, LoRaWAN-1.1 uses 3 network session keys. Both use a unique application session key.


In LoRaWAN-1.1 OTA: the root NwkKey is used to generate SNwkSIntKey, NwkSEncKey, FNwkSIntKey
In LoRaWAN-1.1 OTA: the root AppKey is used to generate AppSKey


in ABP mode, the DevAddr, and session keys are fixed (never change), and frame counters never reset to zero.
ABP operation has no concept of: root keys, or DevEUI or JoinEUI/AppEUI.
in OTA mode, the DevAddr and session keys are assigned at join procedure, and frame counters reset at join.

eeprom

This library includes eeprom driver to support non-volatile storage required by LoRaWAN specification.
Currently eeprom is implemented for STM32L1 family and STM32L0 family.
Writing of values are wear-leveled to increase endurance; each write operation circulates across several memory locations. A read operation returns the highest value found. This simple method is used for sequence numbers which only increase.

value nameused in
DevNonceOTAfor Join request (note 1)
RJcount1OTAfor ReJoin Type 1 request
FCntUpABPuplink frame counter
NFCntDownABPdownlink frame counter
AFCntDownABPdownlink frame counter

AFCntDown is only used in LoRaWAN-1.1 when application payload is present in downlink and FPort > 0.
NFCntDown is used in LoRaWAN-1.1 when FPort is zero in downlink or application payload not present.
NFCntDown is the only downlink frame counter used in LoRaWAN-1.0
(note 1) OTA DevNonce is random number in LoRaWAN-1.0, therefore not stored in eeprom. DevNonce in LoRaWAN-1.1 is forever increasing (non-volatile) number upon each join request,.
RJcount0 is only stored in RAM because the value resets upon new session from JoinAccept, therefore not stored in eeprom.
Frame counters in OTA mode reset upon new session in join request, therefore are stored in RAM instead of eeprom for OTA.

radio driver support

When SX127x driver is used, both SX1272 and SX1276 are supported without defining at compile time. The chip is detected at start-up.
Supported radio platforms:


Alternately, when SX126x driver is imported, the SX126xDVK1xAS board is used.

low-speed clock oscillator selection

LoRaWAN uses 32768Hz crystal to permit low-power operation.
However, some mbed targets might revert to low-speed internal oscillator, which is not accurate enough for LoRaWAN operation.
An oscillator check is performed at initialization; program will not start if internal oscillator is used.
To force LSE watch crystal, add to mbed_app.json

{
    "macros": [ "MBEDTLS_CMAC_C" ],
    "target_overrides": {
        "<your-target>": {
            "target.lse_available": true
        }
    }
}
Revision:
0:6b3ac9c5a042
Child:
3:eb174e10afbb
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mac/region_arib8ch.cpp	Wed Feb 28 10:48:11 2018 -0800
@@ -0,0 +1,367 @@
+//#include "Commissioning.h"
+#include "board.h"
+#if defined(USE_BAND_ARIB_8CH)
+#include <stdint.h>
+#include "LoRaMacPrivate.h"
+
+const uint8_t MaxPayloadOfDatarate[] = { 51, 51, 51, 115, 242, 242, 242, 242 };
+const uint8_t Datarates[]  = { 12, 11, 10,  9,  8,  7,  7, 50 };
+const int8_t TxPowers[]    = { 20, 14, 11,  8,  5,  2 };
+
+ChannelParams_t Channels[LORA_MAX_NB_CHANNELS] =
+{
+    LC1,
+    LC2
+    /* other channels given by mac command */
+};
+
+uint32_t region_GetRxBandwidth( int8_t datarate )
+{
+    if( datarate == DR_6 )
+    {// LoRa 250 kHz
+        return 1;
+    }
+    return 0; // LoRa 125 kHz
+}
+
+uint16_t region_GetRxSymbolTimeout( int8_t datarate )
+{
+    if( ( datarate == DR_3 ) || ( datarate == DR_4 ) )
+    { // DR_4, DR_3
+        return 8;
+    }
+    else if( datarate == DR_5 )
+    {
+        return 10;
+    }
+    else if( datarate == DR_6 )
+    {
+        return 14;
+    }
+    return 5; // DR_2, DR_1, DR_0
+}
+
+void region_rx1_setup(uint8_t chan)
+{
+    int8_t datarate = LoRaMacParams.ChannelsDatarate - LoRaMacParams.Rx1DrOffset;
+    if( datarate < 0 )
+    {
+        datarate = DR_0;
+    }
+
+    RxWindowSetup(
+        Channels[chan].FreqHz,
+        datarate,
+        region_GetRxBandwidth(datarate),
+        region_GetRxSymbolTimeout(datarate)
+    );
+}
+
+void
+region_adr_next_dr(int8_t* dr, bool update)
+{
+    if( *dr > LORAMAC_TX_MIN_DATARATE )
+    {
+        (*dr)--;
+    }
+    if( *dr == LORAMAC_TX_MIN_DATARATE )
+    {
+        if( update == true )
+        {
+            // Re-enable default channels, boot channels
+            LoRaMacParams.ChannelsMask[0] = LoRaMacParamsDefaults.ChannelsMask[0];
+            MAC_PRINTF("adr: reset channel mask\r\n");
+        }
+    }
+}
+
+static bool SetNextChannel(LoRaMacStatus_t* status)
+{
+    uint8_t nbEnabledChannels = 0;
+    uint8_t enabledChannels[LORA_MAX_NB_CHANNELS];
+
+    memset( enabledChannels, 0, LORA_MAX_NB_CHANNELS );
+
+    *status = LORAMAC_STATUS_SERVICE_UNKNOWN;
+    if( CountBits( LoRaMacParams.ChannelsMask[0], 16 ) == 0 )
+    {
+        // Re-enable default channels, if no channel is enabled
+        LoRaMacParams.ChannelsMask[0] = LoRaMacParams.ChannelsMask[0] | ( LC( 1 ) + LC( 2 ) + LC( 3 ) );
+    }
+
+    // Search how many channels are enabled
+    for( uint8_t i = 0, k = 0; i < LORA_MAX_NB_CHANNELS; i += 16, k++ )
+    {
+        for( uint8_t j = 0; j < 16; j++ )
+        {
+            if( ( LoRaMacParams.ChannelsMask[k] & ( 1 << j ) ) != 0 )
+            {
+                if( Channels[i + j].FreqHz == 0 )
+                { // Check if the channel is enabled
+                    continue;
+                }
+#ifdef OVER_THE_AIR_ACTIVATION
+                if (!flags.IsLoRaMacNetworkJoined)
+                {
+                    if( ( JOIN_CHANNELS & ( 1 << j ) ) == 0 )
+                    {
+                        continue;
+                    }
+                }
+#endif /* OVER_THE_AIR_ACTIVATION  */
+                if( ( ( Channels[i + j].DrRange.Fields.Min <= LoRaMacParams.ChannelsDatarate ) &&
+                      ( LoRaMacParams.ChannelsDatarate <= Channels[i + j].DrRange.Fields.Max ) ) == false )
+                { // Check if the current channel selection supports the given datarate
+                    *status = LORAMAC_STATUS_DATARATE_INVALID;
+                    continue;
+                }
+                enabledChannels[nbEnabledChannels++] = i + j;
+            }
+        }
+    }
+
+    if( nbEnabledChannels > 0 )
+    {
+        Channel = enabledChannels[random_at_most(nbEnabledChannels - 1)];
+        *status = LORAMAC_STATUS_OK;
+        return true;
+    }
+    else
+    {
+        // Datarate not supported by any channel
+        return false;
+    }
+}
+
+
+static us_timestamp_t defer_uplink_us;
+
+void region_ScheduleTx( )
+{
+    LoRaMacStatus_t ret;
+
+    if (defer_uplink_us > 0) {
+        TxDelayedEvent.attach_us(OnTxDelayedTimerEvent, defer_uplink_us);
+        defer_uplink_us = 0;
+        return;
+    }
+
+    // Select channel
+    if (!SetNextChannel(&ret))
+    {
+        // Set the default datarate
+        LoRaMacParams.ChannelsDatarate = LoRaMacParamsDefaults.ChannelsDatarate;
+        // re-enable default channels
+        LoRaMacParams.ChannelsMask[0] = LoRaMacParamsDefaults.ChannelsMask[0];
+        if (!SetNextChannel(&ret))
+            return;
+    }
+
+    // Schedule transmission of frame
+    // Try to send now
+    SendFrameOnChannel( Channel );
+}
+
+void region_mac_init()
+{
+    /* only boot channels enabled */
+    LoRaMacParamsDefaults.ChannelsMask[0] = (LC(1)+LC(2));
+}
+
+void region_adr_request(adr_t* adr)
+{
+    uint8_t i;
+
+    if( ( adr->chMaskCntl == 0 ) && ( adr->chMask == 0 ) )
+    {
+        adr->status &= 0xFE; // Channel mask KO
+    }
+    else if( ( ( adr->chMaskCntl >= 1 ) && ( adr->chMaskCntl <= 5 )) ||
+             ( adr->chMaskCntl >= 7 ) )
+    {
+        // RFU
+        adr->status &= 0xFE; // Channel mask KO
+    }
+    else
+    {
+        for( i = 0; i < LORA_MAX_NB_CHANNELS; i++ )
+        {
+            if( adr->chMaskCntl == 6 )
+            {
+                if( Channels[i].FreqHz != 0 )
+                {
+                    adr->chMask |= 1 << i;
+                }
+            }
+            else
+            {
+                if( ( ( adr->chMask & ( 1 << i ) ) != 0 ) &&
+                    ( Channels[i].FreqHz == 0 ) )
+                {// Trying to enable an undefined channel
+                    adr->status &= 0xFE; // Channel mask KO
+                }
+            }
+        }
+        adr->channelsMask[0] = adr->chMask;
+        MAC_PRINTF("arib set channelsMask:%04x ", adr->channelsMask[0]);
+    }
+}
+
+void region_tx_setup(int8_t txPower, uint8_t pktLen)
+{
+    int8_t datarate = Datarates[LoRaMacParams.ChannelsDatarate];
+
+    if( LoRaMacParams.ChannelsDatarate == DR_7 )
+    { // High Speed FSK channel
+        Radio::SetTxConfig( MODEM_FSK, txPower, 25e3, 0, datarate * 1e3, 0, 5, false, true, false);
+        //TxTimeOnAir_us = Radio.TimeOnAir_us( MODEM_FSK, LoRaMacBufferPktLen );
+
+    }
+    else if( LoRaMacParams.ChannelsDatarate == DR_6 )
+    { // High speed LoRa channel
+        Radio::SetTxConfig( MODEM_LORA, txPower, 0, 1, datarate, 1, 8, false, true, false);
+        //TxTimeOnAir_us = Radio.TimeOnAir_us( MODEM_LORA, LoRaMacBufferPktLen );
+    }
+    else
+    { // Normal LoRa channel
+        Radio::SetTxConfig( MODEM_LORA, txPower, 0, 0, datarate, 1, 8, false, true, false);
+        //TxTimeOnAir_us = Radio.TimeOnAir_us( MODEM_LORA, LoRaMacBufferPktLen );
+    }
+}
+
+static bool DisableChannelInMask( uint8_t id, uint16_t* mask )
+{
+    uint8_t index = 0;
+    index = id / 16;
+
+    if( ( index > 4 ) || ( id >= LORA_MAX_NB_CHANNELS ) )
+    {
+        return false;
+    }
+
+    // Deactivate channel
+    mask[index] &= ~( 1 << ( id % 16 ) );
+
+    return true;
+}
+
+LoRaMacStatus_t LoRaMacChannelRemove( uint8_t id )
+{
+    /*if( ( LoRaMacState & LORAMAC_TX_RUNNING ) == LORAMAC_TX_RUNNING )
+    {
+        if( ( LoRaMacState & LORAMAC_TX_CONFIG ) != LORAMAC_TX_CONFIG )
+        {
+            return LORAMAC_STATUS_BUSY;
+        }
+    }*/
+
+    if( ( id < 3 ) || ( id >= LORA_MAX_NB_CHANNELS ) )
+    {
+        return LORAMAC_STATUS_PARAMETER_INVALID;
+    }
+    else
+    {
+        // Remove the channel from the list of channels
+        Channels[id] = ( ChannelParams_t ){ 0, { 0 }, 0 };
+
+        // Disable the channel as it doesn't exist anymore
+        if( DisableChannelInMask( id, LoRaMacParams.ChannelsMask ) == false )
+        {
+            return LORAMAC_STATUS_PARAMETER_INVALID;
+        }
+    }
+    return LORAMAC_STATUS_OK;
+}
+
+static bool ValidateDrRange( DrRange_t drRange, int8_t min, int8_t max )
+{
+    int8_t drMin = drRange.Fields.Min & 0x0F;
+    int8_t drMax = drRange.Fields.Max & 0x0F;
+
+    if( drMin > drMax )
+    {
+        return false;
+    }
+    if( ValueInRange( drMin, min, max ) == false )
+    {
+        return false;
+    }
+    if( ValueInRange( drMax, min, max ) == false )
+    {
+        return false;
+    }
+    return true;
+}
+
+LoRaMacStatus_t LoRaMacChannelAdd( uint8_t id, ChannelParams_t params )
+{
+    bool datarateInvalid = false;
+    bool frequencyInvalid = false;
+    uint8_t band = 0;
+
+    //MAC_PRINTF("channelAdd(%u,%u)\r\n", id, params.Frequency);
+    // The id must not exceed LORA_MAX_NB_CHANNELS
+    if( id >= LORA_MAX_NB_CHANNELS )
+    {
+        return LORAMAC_STATUS_PARAMETER_INVALID;
+    }
+
+    // Validate the datarate
+    if( ValidateDrRange( params.DrRange, LORAMAC_TX_MIN_DATARATE, LORAMAC_TX_MAX_DATARATE ) == false )
+    {
+        datarateInvalid = true;
+    }
+
+    // Validate the frequency
+    if( ( Radio::CheckRfFrequency( params.FreqHz ) == true ) && ( params.FreqHz > 0 ) && ( frequencyInvalid == false ) )
+    {
+        frequencyInvalid = false;
+    }
+    else
+    {
+        frequencyInvalid = true;
+    }
+
+    if( ( datarateInvalid == true ) && ( frequencyInvalid == true ) )
+    {
+        return LORAMAC_STATUS_FREQ_AND_DR_INVALID;
+    }
+    if( datarateInvalid == true )
+    {
+        return LORAMAC_STATUS_DATARATE_INVALID;
+    }
+    if( frequencyInvalid == true )
+    {
+        return LORAMAC_STATUS_FREQUENCY_INVALID;
+    }
+
+    // Every parameter is valid, activate the channel
+    Channels[id] = params;
+    Channels[id].Band = band;
+    LoRaMacParams.ChannelsMask[0] |= ( 1 << id );
+
+    return LORAMAC_STATUS_OK;
+}
+
+void
+region_session_start(LoRaMacEventInfoStatus_t status)
+{
+    McpsReq_t mcpsReq;
+        
+    if (LoRaMacParams.ChannelsMask[0] == 0x003c) {
+        return;
+    }
+    /* send mac commands until desired channel mask */
+
+    mcpsReq.Type = MCPS_UNCONFIRMED;
+    mcpsReq.Req.fPort = 1;
+    mcpsReq.Req.fBuffer = NULL;
+    mcpsReq.Req.fBufferSize = 0;
+    mcpsReq.Req.Datarate = DR_3;
+
+    defer_uplink_us = 2000000 + random_at_most(2000000);
+    LoRaMacMcpsRequest( &mcpsReq );
+}
+
+#endif /* USE_BAND_ARIB_8CH */
+