The Internet of Things on AWS – Official Blog

Connect your devices to AWS IoT using LoRaWAN

4/15/21 AWS IoT Editorial Team Update: 

Since the time of this blog post, we have announced AWS IoT Core for LoRaWAN. AWS IoT Core for LoRaWAN is a fully-managed feature that allows you to connect and manage wireless devices that use LoRaWAN connectivity with the AWS Cloud. Using AWS IoT Core for LoRaWAN, enterprises can setup a private LoRaWAN network by connecting their LoRaWAN devices and gateways to the AWS Cloud – without developing or operating a Network Server (NS) for LoRaWAN themselves.

Learn more about AWS IoT for LoRaWAN, visit the feature page. To get started, see this workshop for step-by-step instructions for how to start using AWS IoT Core for LoRaWAN:  https://iotwireless.workshop.aws/.

__

For many IoT use-cases, sensors only ever need to transmit infrequent and low bit-rate data. These sensors may communicate over large distances and have battery lives spanning in years, which means they are replaced infrequently. A couple of common use-cases would be in Smart Cities (eg. Parking or Waste sensors) and Agriculture (eg. Soil Monitoring sensors). LoRaWAN networks are a good fit for these use-cases and a great way of collecting sensor data.

This post looks at the characteristics of LoRaWAN devices and networks and how customers can integrate these with AWS. We’ll provide an overview of LoRaWAN technology and demonstrate how to build a demonstration kit that integrates directly with AWS IoT Core.

To build this demo you’ll need the following:

  • a LoPy4 development board with Espressif chipset. You can set the LED color on this board as an example of changing state using the AWS IoT shadow service. This board runs MicroPython.
  • a LoPy4 LoRa antenna kit.
  • a Pysense sensor shield to provide sample telemetry data.
  • The Things Network (TTN) – A world-wide community based LoRaWAN network. They have detailed documentation on how to configure AWS IoT integration with their platform. You’ll need to set up an account with The Things network.

Quick LoRaWAN overview

LoRaWAN is a low-power wide-area network (LPWAN) technology. Other LPWAN technologies include Narrowband IoT & Sigfox. LPWAN technologies support long range communication, low power requirements and low bit rates.

LoRaWAN is a protocol specification built on top of the LoRa technology developed by the LoRa Alliance. It uses unlicensed sub-1GHz Industrial, Scientific and Medical (ISM) bands. End-devices communicate with LoRaWAN gateways over a single hop and these gateways provide a TCP/IP uplink to the LoRaWAN Network server, which is responsible then for routing messages between devices and the LoRaWAN “Application”. End-devices can connect to multiple gateways for redundancy and the Network server manages duplicate packets etc. This is shown in the diagram below:

All communications are encrypted twice within the LoRaWAN network, once with a Network Session Key between the end device and the Network Server and secondly with an Application Session Key used to encrypt data between an end-device and an Application. These keys can be generated per session or at time of manufacture.

How do you get LoRaWAN data into AWS so you can build great solutions?

End-devices have a LoRa interface which communicates directly with gateway(s) using RF. Secure access to the network and identification is therefore managed by the LoRaWAN network and not AWS IoT; LoRaWAN devices therefore do not have the AWS IoT SDK installed. To get device data flowing from a LoRaWAN network into AWS IoT the Network Server is integrated with the AWS IoT service. Many LoRaWAN providers are now building AWS IoT integration into their products.

AWS IoT LoRaWAN integration must perform several functions (shown below in the diagram):

 

  • Synchronize device information and attributes between the AWS IoT Device Management service and the LoRaWAN Network Server. If an attribute is changed in one it should propagate to the other.
  • Support bidirectional communication so you can ingest sensor data, and also send back control data. LoRaWAN supports bidirectional communications over several classes of communication.
  • Be able to abstract the AWS IoT Shadow Service so you can at all times get and set the state of things from AWS IoT over the LoRaWAN network to the LoRa-enabled device.
  • Be able to convert between LoRaWAN data, which is typically composed of bytes (to minimize overhead), to a JSON document expected of the AWS IoT service.
  • Be reliable, scalable and fit for purpose. That is, make sure you test and validate your LoRaWAN network is suitable for your use-case.

All of these components can run in a single customer AWS account but it is more common to see the Network Server (and sometimes also the AWS IoT Integration tier) running in the LoRaWAN network provider’s AWS account and the AWS IoT and end-user application components running in a customer’s AWS account.

Demonstrating LoRaWAN AWS Integration using The Things Network

To demonstrate how this integration works I’ve built a small demo project using a LoPy4 device and The Things Network (TTN). Pycom provide extensive documentation on how to set up and manage a LoPy4 device. I set up and run this demo using the Pymakr plugin with Atom (you can also use VS Code).

The high-level steps to configure this demo are:

1. Follow the Pycom documentation for hardware setup of the LoPy4, antenna and Pysense and then update the firmware and configure the development environment for the board.

2. Configuring the LoRaWAN Application & Device in the TTN console.

3. Creating JavaScript code in the TTN console to decode bytes into JSON and encode JSON back into bytes and JSON for temperature data and shadow changes.

The decoder and encoder functions used are shown below:

function Decoder(bytes, port) {
  // Decode an uplink message from a buffer
  // (array) of bytes to an object of fields.
  var decoded = {};
  var colors = ["off", "red", "green", "blue"];
  var color = colors[bytes[2]];
  var temperature = (bytes[0] * 256 + bytes [1])/100;

  return {
    temperature: temperature,
    state: {
      color: color
    }
  }
}

function Encoder(object, port) {
  var colors = ["off", "red", "green", "blue"];
  var bytes = [];
  if (object.state && object.state.color) {
    bytes.push(colors.indexOf(object.state.color));
  }
  return bytes;
}

4. Install & test the TTN AWS IoT integration in an AWS account. This is provided as a CloudFormation script that installs an Elastic Beanstalk (EB) application that performs the integration. This EB application, which runs by default on a t2.micro EC2 instance, authenticates itself with the TTN Network Server and Application using the Application Access Key generated by TTN. By default, this will synchronize the TTN Application details with the AWS IoT Device Management service every 10 minutes (this is configurable).

5. Install, configure and test the Micropython code on the LoPy device. You must be in range of The Things Network. Configure the correct LoRaWAN region for your geography (in Australia both AU915 and AS923 band plans are supported) and the correct credentials for your LoRaWAN Application.

import binascii
import pycom
import socket
import time
from network import LoRa
from pysense import Pysense
from MPL3115A2 import MPL3115A2


# Colors
off = 0x000000
red = 0xff0000
green = 0x00ff00
blue = 0x0000ff
colors = [off, red, green, blue]

# Turn off heartbeat LED
pycom.heartbeat(False)

# Initialize LoRaWAN radio
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.AU915, adr=False, tx_retries=0, device_class=LoRa.CLASS_A)

# Set network keys
app_eui = binascii.unhexlify('xxxxxxxxxxxxxxxx')
app_key = binascii.unhexlify('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')

# remove some channels (in Australia)
for i in range(16, 65):
  lora.remove_channel(i)
for i in range(66, 72):
  lora.remove_channel(i)

# Join the network
lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
pycom.rgbled(red)

# init the libraries
py = Pysense()
temp = MPL3115A2()

# Loop until joined
while not lora.has_joined():
  print('Not joined yet...')
  pycom.rgbled(off)
  time.sleep(0.1)
  pycom.rgbled(red)
  time.sleep(2)

print('Joined')
pycom.rgbled(blue)

s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
s.setblocking(False)
colorindex = 3

while True:
  # Read data from the libraries and place into string
  data = temp.temperature()
  print("Sending %.5s" % data)
  data = int (data * 100);
  # send the data over LPWAN network
  s.send(bytes([int(data / 256), data % 256, colorindex   ]))
  s.settimeout(3.0) # configure a timeout value of 3 seconds
  try:
    rx_pkt = s.recv(64)   # get the packet received (if any)
    print(rx_pkt)
    colorindex = int.from_bytes(rx_pkt, "big")
  except socket.timeout:
    print('No packet received')

  pycom.rgbled(green)
  time.sleep(0.1)
  pycom.rgbled(colors[colorindex])
  time.sleep(29.9)

6. The code runs an infinite loop converting temperature readings and the LED color from the Pysense to bytes and sending these bytes to the TTN Application, which then forwards the data to AWS IoT. Each time a packet is sent it checks to see if there is a return packet based on a Shadow state change (LoRaWAN has three classes for supporting directional communications) and if so it receives that packet and changes the LED color to the new desired state.

Testing the TTN AWS IoT integration

There are several ways of testing the integration.

1. Confirm that the LoPy device is present in both the AWS IoT and TTN consoles.

2. Confirm that your LoPy4 device is being activated and is sending uplink messages in the TTN console.

3. Confirm that uplink messages are being converted from bytes to JSON and being sent to the AWS IoT Core service by using the MQTT Test client

4. Create an AWS IoT Action and send data to DynamoDB.

5. Update the AWS IoT device shadow state in the console, observe the downlink message in the TTN console and if all goes well watch the LED on your device change color!

6. You can also simulate uplink and downlink messages from the TTN console if you need to troubleshoot.

In summary

LoRaWAN technology offers customers a great way to build IoT networks that support low bit-rates, low energy use and long device lifespan over large geographical areas. And now with AWS IoT integration customers can leverage the best of both worlds by bringing the power of the cloud to their IoT data! If you’d like to learn more about AWS and our IoT network partners, follow these links: