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:
7:4b6f960dcca2
Parent:
5:4e9d41359897
Child:
8:5a5ea7cc946f
diff -r babd601c6392 -r 4b6f960dcca2 mac/LoRaMac1v1.cpp
--- a/mac/LoRaMac1v1.cpp	Fri Apr 06 23:41:55 2018 +0000
+++ b/mac/LoRaMac1v1.cpp	Fri May 04 11:00:06 2018 -0700
@@ -101,6 +101,8 @@
 
 static void PrepareRxDoneAbort(LoRaMacEventInfoStatus_t);
 
+void OnRadioRxTimeout(void);
+
 LoRaMacStatus_t
 AddMacCommand( uint8_t cmd, uint8_t p1, uint8_t p2 )
 {
@@ -208,6 +210,14 @@
             }
             break;
 #endif /* !LORAWAN_JOIN_EUI  */
+        case MOTE_MAC_MODE_IND:
+            if( MacCommandsBufferIndex < bufLen-1 )
+            {
+                MacCommandsBuffer[MacCommandsBufferIndex++] = cmd;
+                MacCommandsBuffer[MacCommandsBufferIndex++] = p1;
+                status = LORAMAC_STATUS_OK;
+            }
+            break;
         default:
             MAC_PRINTF("unknown-addCmd %02x\r\n", cmd);
             return LORAMAC_STATUS_SERVICE_UNKNOWN;
@@ -293,6 +303,8 @@
     memcpy( ( uint8_t* ) ChannelsMaskRemaining, ( uint8_t* ) LoRaMacParamsDefaults.ChannelsMask, sizeof( LoRaMacParams.ChannelsMask ) );
 #endif
 
+    LoRaMacParams.MaxListenTime = LoRaMacParamsDefaults.MaxListenTime;
+
 
     flags.SrvAckRequested = false;
     flags.MacCommandsInNextTx = false;
@@ -355,6 +367,7 @@
                 i += 2;
                 break;
             }
+            case MOTE_MAC_MODE_IND:
             case MOTE_MAC_LINK_ADR_ANS:
             case MOTE_MAC_NEW_CHANNEL_ANS:
             { // 1 byte payload
@@ -373,7 +386,7 @@
     }
 
     return cmdCount;
-}
+} // ..ParseMacCommandsToRepeat()
 
 LoRaMacStatus_t PrepareFrame( LoRaMacHeader_t *macHdr, LoRaMacFrameCtrl_t *fCtrl, uint8_t fPort, void *fBuffer, uint16_t fBufferSize )
 {
@@ -864,6 +877,9 @@
             mibGet->Param.ChannelsMask = LoRaMacParams.ChannelsMask;
             LoRaMacParams.NbEnabledChannels = region_CountNbEnabledChannels();
             break;
+        case MIB_MAX_LISTEN_TIME:
+            mibGet->Param.MaxListenTime = LoRaMacParams.MaxListenTime;
+            break;
 #ifdef LORAWAN_JOIN_EUI
         case MIB_NETWORK_JOINED:
             mibGet->Param.IsNetworkJoined = flags.IsLoRaMacNetworkJoined;
@@ -928,7 +944,7 @@
         return LORAMAC_STATUS_PARAMETER_INVALID;
     }
     if (flags.uplink_in_progress > 0) {
-        MAC_PRINTF("LoRaMacMcpsRequest() in_progress BUSY\r\n");
+        MAC_PRINTF("LoRaMacMcpsRequest() in_progress BUSY%u\r\n", flags.uplink_in_progress);
         return waitingFor;
     }
     if (ConfFCntUp > 0) {
@@ -1010,7 +1026,6 @@
 {
     uint8_t downlinkDatarate = Datarates[datarate];
     RadioModems_t modem;
-    //RadioState_t rs = Radio::GetStatus();
 
     MAC_PRINTF(" rxwin-dr%u-sf%u ", datarate, downlinkDatarate);
     Radio::SetChannel( freq );
@@ -1037,6 +1052,9 @@
     Radio::SetRxMaxPayloadLength( modem, MaxPayloadOfDatarate[datarate] + LORA_MAC_FRMPAYLOAD_OVERHEAD );
 } //..RxWindowSetup()
 
+LowPowerTimeout RxWindowEvent1;
+LowPowerTimeout RxWindowEvent2;
+
 static void RxWindow2Start( void )
 {
     /* TODO: join accept rx2 channel unique */
@@ -1129,8 +1147,9 @@
 finish_uplink(LoRaMacEventInfoStatus_t status)
 {
     if ((flags.uplink_in_progress > 0 && McpsIndication.RxSlot == 2) || status == LORAMAC_EVENT_INFO_STATUS_OK) {
-        if ((uplinkMHDR->Bits.MType == FRAME_TYPE_DATA_CONFIRMED_UP && status == LORAMAC_EVENT_INFO_STATUS_OK) || uplinkMHDR->Bits.MType != FRAME_TYPE_DATA_CONFIRMED_UP)
+        if ((uplinkMHDR->Bits.MType == FRAME_TYPE_DATA_CONFIRMED_UP && status == LORAMAC_EVENT_INFO_STATUS_OK) || uplinkMHDR->Bits.MType != FRAME_TYPE_DATA_CONFIRMED_UP) {
             flags.uplink_in_progress--;
+        }
 
         if (flags.uplink_in_progress > 0) {
             McpsIndication.Status = status;
@@ -1160,8 +1179,6 @@
     }
 #endif /* LORAWAN_JOIN_EUI  */
 
-    McpsIndication.RxSlot = 0;
-
     waitingFor = LORAMAC_STATUS_OK;
 
     if (function_pending != NULL) {
@@ -1273,6 +1290,9 @@
                 LoRaMacDeviceClass = deviceClass;
                 RxWindow2Setup();
                 RxWindow2Start(); // continuous rx2 reception
+                if (flags.OptNeg) {
+                    AddMacCommand(MOTE_MAC_MODE_IND, LoRaMacDeviceClass, 0);
+                }
 
                 status = LORAMAC_STATUS_OK;
             }
@@ -1296,6 +1316,9 @@
             {
                 MAC_PRINTF("->A ");
                 LoRaMacDeviceClass = deviceClass;
+                if (flags.OptNeg) {
+                    AddMacCommand(MOTE_MAC_MODE_IND, LoRaMacDeviceClass, 0);
+                }
 
                 // Set the radio into sleep to setup a defined state
                 Radio::Sleep( );
@@ -1389,6 +1412,9 @@
             flags.PublicNetwork = mibSet->Param.EnablePublicNetwork;
             Radio::SetPublicNetwork( flags.PublicNetwork );
             break;
+        case MIB_MAX_LISTEN_TIME:
+            LoRaMacParams.MaxListenTime = mibSet->Param.MaxListenTime;
+            break;
 #ifndef LORAWAN_JOIN_EUI
         case MIB_SNwkSIntKey:
             flags.have_SNwkSIntKey = 1;
@@ -1434,15 +1460,15 @@
     return LORAMAC_STATUS_OK;
 }
 
-LowPowerTimeout RxWindowEvent1;
-LowPowerTimeout RxWindowEvent2;
 
 static void RxWindow1Start( void )
 {      
-    if (LoRaMacDeviceClass == CLASS_C)
-        Radio::Rx( 0 ); // Continuous mode
-    else
-        Radio::Rx( LoRaMacParams.MaxRxWindow_us );
+    if (LoRaMacDeviceClass == CLASS_C) {
+        Radio::Standby();
+        region_rx1_setup(Channel);
+    }
+
+    Radio::Rx( LoRaMacParams.MaxRxWindow_us );
 
     McpsIndication.RxSlot = 1;
 }
@@ -1457,20 +1483,16 @@
         PrepareRxDoneAbort(LORAMAC_EVENT_INFO_BAD_RX_DELAY);
         return;
     }
-
-    waitingFor = LORAMAC_STATUS_WAITING_FOR_RX1;
     // Setup timers
     RxWindowEvent1.attach_us(RxWindow1Start, RxWindow1Delay_us);
-    if( LoRaMacDeviceClass != CLASS_C )
-    {
-        RxWindowEvent2.attach_us(RxWindow2Start, RxWindow2Delay_us);
-    }
+    waitingFor = LORAMAC_STATUS_WAITING_FOR_RX1;
     McpsIndication.RxSlot = 0;
 
     tx_done_at = at_us;
 
-    if( LoRaMacDeviceClass != CLASS_C )
+    if (LoRaMacDeviceClass != CLASS_C)
     {
+        RxWindowEvent2.attach_us(RxWindow2Start, RxWindow2Delay_us);
         region_rx1_setup(Channel);
         Radio::Sleep( );
     }
@@ -1478,6 +1500,8 @@
     {
         RxWindow2Setup();
         RxWindow2Start();
+        // simulate timeout to complete uplink
+        RxWindowEvent2.attach_us(OnRadioRxTimeout, RxWindow2Delay_us + 256000);
     }
 
     // Store last tx channel
@@ -1623,6 +1647,8 @@
                 MlmeConfirm.fields.link.DemodMargin = buf[0];
                 MlmeConfirm.fields.link.NbGateways = buf[1];
                 break;
+            case SRV_MAC_MODE_CONF:
+                break;
             case SRV_MAC_LINK_ADR_REQ:
                 MACC_PRINTF("LINK_ADR_REQ ");
                 {
@@ -2039,8 +2065,9 @@
     } else {
         /* downlink with good MIC means previous confirmed uplink was receied */
         ConfFCntUp = 0;
-        if (McpsIndication.RxSlot == 1)   // no need for RX2 with good mic on rx1
+        if (McpsIndication.RxSlot == 1) {   // no need for RX2 with good mic on rx1
             RxWindowEvent2.detach();
+        }
     }
 
     McpsIndication.Status = LORAMAC_EVENT_INFO_STATUS_OK;
@@ -2252,7 +2279,7 @@
         MlmeConfirm.Status = LORAMAC_EVENT_INFO_STATUS_OK;
     }
 
-    if( LoRaMacDeviceClass != CLASS_C )
+    if (LoRaMacDeviceClass != CLASS_C)
     {
         Radio::Sleep( );
     }
@@ -2328,8 +2355,9 @@
 
             if (micRx == mic)
             {
-                if (McpsIndication.RxSlot == 1)   // no need for RX2 with good mic on rx1
+                if (McpsIndication.RxSlot == 1) {  // no need for RX2 with good mic on rx1
                     RxWindowEvent2.detach();
+                }
 
 #ifdef LORAWAN_ROOT_APPKEY        
                 if (flags.OptNeg) {
@@ -2448,12 +2476,15 @@
         if (McpsIndication.RxSlot == 1) {
             RxWindow2Setup();
             RxWindow2Start();   // immiediately to continuous rx2 reception
-            McpsIndication.RxSlot = 2;
+        } else if (McpsIndication.RxSlot == 2) {
+            /* stop simulated rx timeout for classC rx2-continuous */
+            RxWindowEvent2.detach();
         }
     }
 
     {
-        finish_uplink(status);
+        if (flags.uplink_in_progress > 0)
+            finish_uplink(status);
 
         mcps_confirm(status);  // RxDone
         mlme_confirm(status);
@@ -2483,10 +2514,8 @@
     if (McpsIndication.RxSlot == 1)
         RxWindow2Setup();
 
-    if (LoRaMacDeviceClass == CLASS_C)
-        RxWindow2Start();
-    else
-        Radio::Sleep( );
+    if (LoRaMacDeviceClass != CLASS_C)
+        Radio::Sleep();
 
     if (McpsIndication.RxSlot == 2)
     {
@@ -2519,10 +2548,16 @@
 
         finish_uplink(LORAMAC_EVENT_INFO_STATUS_RX2_TIMEOUT);
     } // ..if (McpsIndication.RxSlot == 2)
+
+    if (LoRaMacDeviceClass == CLASS_C) {
+        if (McpsIndication.RxSlot != 2) {
+            RxWindow2Start();
+        }
+    } else
+        flags.rxing = false;
+
     MAC_PRINTF("\r\n");
 
-    flags.rxing = false;
-
 } // ..OnRadioRxTimeout()
 
 __attribute__((weak)) void 
@@ -2739,8 +2774,11 @@
     //MlmeConfirm.TxTimeOnAir = TxTimeOnAir_us;
 
     // Send now
+    if (Radio::Send(tx_len, LoRaMacParams.MaxListenTime, REGION_LBT_CHANNEL_FREE_TIME_us, REGION_LBT_RSSI_THRESHOLD_DBM) < 0) {
+        mcps_confirm(LORAMAC_EVENT_INFO_STATUS_CHANNEL_BUSY);  // SendFrame fail
+        return;
+    }
     waitingFor = LORAMAC_STATUS_WAITING_FOR_TXDONE;
-    Radio::Send(tx_len);
     MAC_PRINTF(" sfoc %u, %" PRIu32"hz\r\n", tx_len, Channels[ch_num].FreqHz);
 
     /* if this is unconfirmed up, and last NbTrans */
@@ -2771,7 +2809,17 @@
 
 void LoRaMacPrintStatus()
 {
-    MAC_PRINTF("uplink_in_progress:%u, ConfFCntUp%u\r\n", flags.uplink_in_progress, ConfFCntUp);
+#ifdef MAC_DEBUG
+    switch (waitingFor) {
+        case LORAMAC_STATUS_WAITING_FOR_TXSTART: MAC_PRINTF("wait-TXSTART "); break;
+        case LORAMAC_STATUS_WAITING_FOR_TXDONE:  MAC_PRINTF("wait-TXDONE "); break;
+        case LORAMAC_STATUS_WAITING_FOR_RX1:     MAC_PRINTF("wait-RX1 "); break;
+        case LORAMAC_STATUS_WAITING_FOR_RX2:     MAC_PRINTF("wait-RX2 "); break;
+        default: break;
+    }
+    if (flags.uplink_in_progress > 0)
+        MAC_PRINTF("uplink_in_progress:%u ", flags.uplink_in_progress);
+    MAC_PRINTF("ConfFCntUp%u\r\n", ConfFCntUp);
     MAC_PRINTF("function_pending:%p\r\n", function_pending);
     MAC_PRINTF("rx delays:%u, %u, %u, %u\r\n",
         RxWindow1Delay_us,
@@ -2783,7 +2831,16 @@
         MAC_PRINTF("since txDone:%u\r\n", Radio::lpt.read_us() - tx_done_at);
     }
 
+    MAC_PRINTF("class-");
+    switch (LoRaMacDeviceClass) {
+        case CLASS_A:   MAC_PRINTF("A "); break;
+        case CLASS_B:   MAC_PRINTF("B "); break;
+        case CLASS_C:   MAC_PRINTF("C "); break;
+    }
+    MAC_PRINTF("\r\n");
+
     Radio::PrintStatus();
+#endif /* MAC_DEBUG */
 }
 
 us_timestamp_t LoRaMacReadTimer()