Home

Awesome

MCCI Arduino LoRaWAN Library

User-friendly library for using the Arduino LMIC library with The Things Network and LoRaWAN® networks.

GitHub release GitHub commits Build Status

Contents:

<!-- This TOC uses the VS Code markdown TOC extension AlanWalk.markdown-toc. We strongly recommend updating using VS Code, the markdown-toc extension and the bierner.markdown-preview-github-styles extension. Note that if you are using VS Code 1.29 and Markdown TOC 1.5.6, https://github.com/AlanWalk/markdown-toc/issues/65 applies -- you must change your line-ending to some non-auto value in Settings> Text Editor>Files. `\n` works for me. --> <!-- markdownlint-capture --> <!-- markdownlint-disable --> <!-- TOC depthFrom:2 updateOnSave:true --> <!-- /TOC --> <!-- markdownlint-restore --> <!-- Due to a bug in Markdown TOC, the table is formatted incorrectly if tab indentation is set other than 4. Due to another bug, this comment must be *after* the TOC entry. -->

Overview

The arduino-lorawan library provides a structured way of using the arduino-lmic library to send sensor data over The Things Network or a similar LoRaWAN-based data network.

This version targets v4.0.0 or later of the arduino-lmic library.

It targets devices that are reasonably capable, consisting of:

  1. A 32-bit processor (ARM, XTENSA, etc.);
  2. An SX1276-based LoRa radio; and
  3. An Arduino run-time environment.

The reference target for SAMD21G deployments is Adafruit Feather M0 LoRa. In addition to the basic Feather M0 LoRa, other products are supported. The MCCI Catena 4450, Catena 4460, and Catena 4470 products are upward compatible with the Feather M0 LoRa and therefore also can be used with this library.

The reference target for STM32L0 deployments is the Murata CMWX1ZZABZ-078, as deployed in the MCCI Catena 4610, Catena 4612, Catena 4801, Catena 4617, Catena 4618, Catena 4630 etc., with the MCCI Arduino board support package.

arduino-lorawan attempts to solve three problems.

  1. It separates network maintenance code from your application.
  2. It separates the common logic of your sensor app from the details about each individual device, allowing you to have a common source base that's used for all sensors.
  3. It provides a simple framework for doing low-power programming.
  4. It includes a framework for managing non-volatile storage (particularly FRAM) in a stable and atomic way. (However, you have to provide the non-volatile storage handling).

The resulting programming environment is just a little more complicated than basic Arduino, but we intend that it will be almost as easy to use for prototyping, and not too tedious to use when moving to small pilot runs.

MCCI tends to use the this library wrapped by the Catena Arduino Platform library, but this library can be used stand-alone, as described below, and as shown in examples/simple_sensor_bme280/simple_sensor_bme280.ino.

Required libraries

LibraryRequired VersionRecommended VersionComments
arduino-lmic3.99.0-24.0.0Earlier versions will fail to compile but should give compile-time asserts.
Catena-mcciadk0.1.10.2.2Needed for miscellaneous definitions

Compile-time Configuration

Region Selection

This library uses the same configuration variables as the Arduino LMIC for selecting the target region.

Network selection

The following compile-time defines select the network that will be used. Exactly one should be defined. The value shall be 1.

SymbolNetworkRegions Supported
ARDUINO_LMIC_CFG_NETWORK_TTNThe Things NetworkEU868, US915 (subband 1), AU915 (subband 1), AS923, AS923 Japan, KR920, IN866
ARDUINO_LMIC_CFG_NETWORK_ACTILITYActilityEU868, US915, AU915, AS923, AS923 Japan, KR920, IN866
ARDUINO_LMIC_CFG_NETWORK_HELIUMHeliumUS915 (subband 1)
ARDUINO_LMIC_CFG_NETWORK_MACHINEQmachineQUS915
ARDUINO_LMIC_CFG_NETWORK_SENETSenetUS915
ARDUINO_LMIC_CFG_NETWORK_SENRASenraIN866
ARDUINO_LMIC_CFG_NETWORK_SWISSCOMSwisscomEU868
ARDUINO_LMIC_CFG_NETWORK_CHIRPSTACKChirpStack.ioEU868, US915, AU915, AS923, AS923 Japan, KR920, IN866
ARDUINO_LMIC_CFG_NETWORK_GENERICGenericEU868, US915, AU915, AS923, AS923 Japan, KR920, IN866

Join Subband Selection

Three regional plans (US915, AU915 and CN470) have fixed channel frequencies, and many more channels than are supported by most gateways. In these regions, it's common to reduce the OTAA join channels to a subset of the available channels -- networks often configure gateways to support a maximum of 8 channels. The exact choice of 8 channels is called the subband.

The symbol ARDUINO_LMIC_CFG_SUBBAND, if defined, configures the subband to be used. If set to -1, no subband choice is made; all channels are used for joining. Otherwise, the value is multiplied by 8 and used as the base channel for joining. Channels ARDUINO_LMIC_CFG_SUBBAND through ARDUINO_LMIC_CFG_SUBBAND + 7 are used for the join process. In the US915 and AU915 regions ARDUINO_LMIC_CFG_SUBBAND can be any value between 0 and 7, inclusive. In the CN470 region, ARDUINO_LMIC_CFG_SUBBAND can be any value between 0 and 11, inclusive.

Some networks (The Things Network, Helium) pre-define the subband to be used; in that case, ARDUINO_LMIC_CFG_SUBBAND is not used.

In most cases, ARDUINO_LMIC_CFG_SUBBAND can be set to -1. The network either sends the desired channel mask as part of the JoinAccept message, or (in the case of TTN V2) sends channel-mapping information in response to the first successful uplink. However, if you're impatient, setting the subband to match your network will speed up joins appreciably, and (on TTN V2) will make your device start sending good data more quickly. Setting ARDUINO_LMIC_CFG_SUBBAND to a non-negative value that doesn't match your network will effectively prevent communication.

Writing Code With This Library

The classes in this library are normally intended to be used inside a class that overrides one or more of the virtual methods.

Using the LMIC's pre-configured pin-maps

The stand-alone use pattern is as follows, targeting The Things Network V3 (also works with V2). This code can be found in the example/simple_feather/simple.ino sketch. Note that this isn't complete, as you have to add code in the indicated places.

#include <Arduino_LoRaWAN_ttn.h>

class cMyLoRaWAN : public Arduino_LoRaWAN_ttn {
public:
    cMyLoRaWAN() {};

protected:
    // you'll need to provide implementations for this.
    virtual bool GetOtaaProvisioningInfo(Arduino_LoRaWAN::OtaaProvisioningInfo*) override;
    // if you have persistent storage, you can provide implementations for these:
    virtual void NetSaveSessionInfo(const SessionInfo &Info, const uint8_t *pExtraInfo, size_t nExtraInfo) override;
    virtual void NetSaveSessionState(const SessionState &State) override;
    virtual bool NetGetSessionState(SessionState &State) override;
};

// set up the data structures.
cMyLoRaWAN myLoRaWAN {};

void setup() {
    myLoRaWAN.begin();
}

void loop() {
    myLoRaWAN.loop();
}

// this method is called when the LMIC needs OTAA info.
// return false to indicate "no provisioning", otherwise
// fill in the data and return true.
bool
cMyLoRaWAN::GetOtaaProvisioningInfo(
    OtaaProvisioningInfo *pInfo
    ) {
    return false;
}

void
cMyLoRaWAN::NetSaveSessionInfo(
    const SessionInfo &Info,
    const uint8_t *pExtraInfo,
    size_t nExtraInfo
    ) {
    // save Info somewhere.
}

void
cMyLoRaWAN::NetSaveSessionState(const SessionState &State) {
    // save State somwwhere. Note that it's often the same;
    // often only the frame counters change.
}

bool
cMyLoRaWAN::NetGetSessionState(SessionState &State) {
    // either fetch SessionState from somewhere and return true or...
    return false;
}

Supplying a pin-map

If the LMIC library doesn't have a pin-map for your board, and you don't want to add one to the library, you can supply your own. Simply prepare a pin-map, and pass it to the begin() method.

A full example can be found in the example/simple_feather/simple_feather.ino sketch, but here are the relevant differences.

// The pin map. This form is convenient if the LMIC library
// doesn't support your board and you don't want to add the
// configuration to the library (perhaps you're just testing).
// This pinmap matches the FeatherM0 LoRa. See the arduino-lmic
// docs for more info on how to set this up.
const cMyLoRaWAN::lmic_pinmap myPinMap = {
     .nss = 8,
     .rxtx = cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN,
     .rst = 4,
     .dio = { 3, 6, cMyLoRaWAN::lmic_pinmap::LMIC_UNUSED_PIN },
     .rxtx_rx_active = 0,
     .rssi_cal = 0,
     .spi_freq = 8000000,
};

void setup() {
    // simply pass the pinmap to the begin() method.
    myLoRaWAN.begin(myPinMap);
}

Details on use

  1. Define a class to define your concrete LoRaWAN instance. This is how you'll provide the out-calls, by defining virtual method functions. We'll call this cMyLoRaWAN, beginning with c to indicate that this is a class name.

  2. Create an instance of your class. We'll call this myLoRaWAN.

  3. Determine whether you need a pin-map, or whether your arduino-lmic library already directly supports your board. If directly supported, you can call myLoRaWAN.begin() without any arguments, and the LMIC default pin-map for your board will be used. Otherwise, you can allocate a pin-map. If you name it myPinmap, you can call myLoRaWAN.begin(myPinmap);, as in the example.

  4. Implement the required methods.

APIs

Starting operation

The begin() APIs are used to start the LMIC engine. There are three forms. See "Details on use," above.

Poll and update the LMIC

void Arduino_LoRaWAN::loop(void);

This method must be called periodically in order to keep the LMIC operating. For class-A devices, this need only be called while actively pushing an uplink, or while a task is pending in the LMIC's time-driven queue.

Reset the LMIC

void Arduino_LoRaWAN::reset(void);

Cancel any pending operations and reinitialize all internal state.

Shut down the LMIC

void Arduino_LoRaWAN::Shutdown(void);

Shut down the LMIC. Any attempt to transmit while shut down will fail.

Register an event listener

typedef void ARDUINO_LORAWAN_EVENT_FN(
                        void *pUserData,
                        uint32_t eventCode
                        );

bool Arduino_LoRaWAN::RegisterListener(
    ARDUINO_LORAWAN_EVENT_FN *pEvent,
    void *pUserData
    );

Clients may register event functions using RegisterListener. The event function is called on each event from the LMIC. Up to four listeners may be registered. There's no way to cancel a registration.

Send an event to all listeners

void Arduino_LoRaWAN::DispatchEvent(uint32_t eventCode);

This routine causes each registered event listener to be called with the specified event code. This is mostly for internal use, and may become protected in future releases.

Manipulate the Debug Mask

To be documented. This feature is currently only in the header files and not used.

Output a formatted log message

To be documented. This feature is currently only used by the macro ARDUINO_LORAWAN_PRINTF, which in turn is only used in one place.

Get the configured LoRaWAN region, country code, and network name

const char *Arduino_LoRaWAN::GetRegionString(char *pBuf, size_t size) const;

Set the buffer at *pBuf to the configured network region. At most size-1 characters will be copied to the target buffer.

The result is guaranteed to be non-NULL, and is a pointer to a string. If pBuf is nullptr or size is zero, then the result is a constant string "<<null>>". Otherwise, the result is pBuf. Since the result might be an immutable string, the result is declared as const char *. The result is guaranteed to be a well-formed string. If the buffer is too small to contain the region string, the region string will be truncated to the right as needed.

Arduino_LoRaWAN::Region Arduino_LoRaWAN::GetRegion() const;

Return the region code. Arduino_LoRaWAN::Region contains the following values: unknown, eu868, us915, cn783, eu433, au915, cn490, as923, kr920, and in866.

Arduino_LoRaWAN::CountryCode Arduino_LoRaWAN::GetCountryCode() const;

Return the country code, which might be relevant to the region definition. The defined values are none (in case there are no relevant country-specific variations), and JP (which means we must follow Japan listen-before-talk rules).

enum class Arduino_LoRaWAN::NetworkID_t : std::uint32_t {
    TheThingsNetwork, Actility, Helium, machineQ, Senet, Senra, Swisscom,
    ChirpStack, Generic
};

Arduino_LoRaWAN::NetworkID_t Arduino_LoRaWAN::GetNetworkID() const;

Return the network ID, indicating the network for which the stack is currently configured.

const char *GetNetworkName() const;

Return the network name. Values are "The Things Network", "Actility", "Helium", "machineQ", "Senet", "Senra", "Swisscom", "ChirpStack", and "Generic".

Set link-check mode

bool Arduino_LoRaWAN::SetLinkCheckMode(
    bool fEnable
    );

Enable (or disable) link check mode, based on the value of fEnabled. If disabled, the device will not try to maintain a connection to the network. If enabled, the device watches for downlinks. If no downlink is seen for 64 messages, the device starts setting the network ADR request in uplinks. If there's no response after 32 messages, the device reduces the data rate and increases power, and continues this loop until there are no more data rates to try. At that point, the device will start inserting join attempts after every uplink without a downlink.

If disabled, the device doesn't try to reduce data rate automatically and won't ever automatically detect network loss or change.

Disabled was formerly the preferred mode of operation, but as of early 2019, it is clear that enabled is the preferred mode for The Things Network.

Send a buffer

typedef void Arduino_LoRaWAN::SendBufferCbFn(
    void *pClientData,
    bool fSuccess
    );

bool Arduino_LoRaWAN::SendBuffer(
    const uint8_t *pBuffer,
    size_t nBuffer,
    SendBufferCbFn *pDoneFn = nullptr,
    void *pClientData = nullptr,
    bool fConfirmed = false,
    uint8_t port = 1
    );

Send message from pBuffer; call pDoneFn(pClientData, status) when the message has either been transmitted or abandoned.

Register a Receive-Buffer Callback

typedef void
Arduino_LoRaWAN::ReceivePortBufferCbFn(
    void *pClientData,
    uint8_t uPort,
    const uint8_t *pBuffer,
    size_t nBuffer
    );

void Arduino_LoRaWAN::SetReceiveBufferCb(
    Arduino_LoRaWAN::ReceivePortBufferCbFn *pReceiveBufferFn,
    void *pUserData = nullptr
    );

The specified function is called whenever a downlink message is received. nBuffer might be zero, and uPort might be zero for MAC messages.

Get DevEUI, AppEUI, AppKey

bool Arduino_LoRaWAN::GetDevEUI(uint8_t *pBuf);
bool Arduino_LoRaWAN::GetAppEUI(uint8_t *pBuf);
bool Arduino_LoRaWAN::GetAppKey(uint8_t *pBuf);

These three routines fetch the provisioned DevEUI, AppEUI, and AppKey. pBuf points to an 8-byte (DevEUI and AppEUI) or 16-byte (AppKey) buffer. The values are returned in network byte order: DevEUI and AppEUI are returned in little-endian byte order, and AppKey is returned in big-endian byte order.

Test provisioning state

bool Arduino_LoRaWAN::IsProvisioned(void);

Return true if the LoRaWAN stack seems to be properly provisioned (provided with a valid Device EUI, Application EUI and Application Key for OTAA; or provided with valid Device Address, Application Session Key and Network Session Key for ABP). Returns false otherwise.

Examples

Although the examples directory has many sketches, most are for regression testing, and are not of much use in showing how library should be used.

However, examples/simple_sensor_bme280 is a complete working example of an OTAA device.

Note: the example uses the MCCI fork of the Adafruit BME280 library, found here. This won't trouble you unless you actually try to use the code, rather than replacing the sensor logic with your own logic.

Much more elaborate uses can be found in the MCCI Catena-Arduino-Platform library; but that library is so large that it's tough to figure out what's required for LoRaWAN, and what's used for supporting MCCI boards.

Release History

Notes