Objective
This tutorial describes how to create communication between AirVantage and STM32Nucleo-based system using AirPrime HL wireless module.
The following use cases are covered:
- Sending custom data such as sensor values or application data from STM32/Nucleo board to AirVantage
- Sending commands or configuration from AirVantage to STM32/Nucleo board
To implement this solution, MQTT protocol will be used.
Let’s develop a simple Alarm system to better showcase the solution in 4 main steps:
- Setup Hardware
- Setup STM32/Nucleo board Software Development Environment
- Define STM32/Nucleo board-AirVantage Interface
- Develop a simple Alarm system
Prerequisite
- HL Shield + Antenna + Power adaptor + USB cable MiniB-A
- AirPrime HL series Module
- SIM card with data call plan
- STM32 Nucleo-L053R8 + USB cable type B-A
- USB Hub (3 ports or more) + TTL to Serial USB cable (E.g. TTL-232R)
- LED + PIR Motion detection sensor
- Female to female wiring cable
- Have an account on AirVantage server : eu.airvantage.net
Part references used in this tutorial
Any issues ?
If you encounter any issue to set up your device, don’t hesitate to use the developer forum to benefit from the developer community experience.
Preparing the HL Shield
- Place the HL Module into the shield’s module socket. To ensure the correct orientation of the HL Module, use the dot mark, printed on the top right corner, as reference. It should be aligned with the dot mark visible within the shield socket. Then place the shielding cover on the module.
- Ensure that jumpers are correctly placed according to the photo (red marks in ellipses)
- Connect the antenna to the “2G/3G/4G RF MAIN” connector.
- Insert a SIM card into the “SIM1” slot, located in the bottom side of the Shield.
- Connect the “MAIN UART” USB port (green ellipse) to USB Hub which is connected to your PC/Mac
- If USB driver is missing, VCP driver can be downloaded here
- By default, Nucleo boards are configured to have shared UART on pins D0 and D1 with STLink.
We need to use these D0 and D1 pins independently so the Nucleo can be stacked under the HL Shield, to achieve this:
- Remove Solder Bridges SB13 and SB14, located in the red area in the photo
- Set Solder Bridges SB62 and SB63 to ON, green area in the photo. (Zero resistors removed from SB13 & SB14 can placed in SB62 & SB63)
Important: without this hardware configuration, D0 and D1 cannot be used as serial port to drive the HL Shield.
In this case, flying wires should be used (no stacking) to connect Nucleo CN3's RX & TX pins to HL Shield's counterpart Arduino TX & RX pins. IOREF and GND pins must also be wired.
Stacking HL Shield over Nucleo-L053R8
- Refer to the photo for stacking reference.
- Once stacked, Nucleo’s I/O pins are exposed to the top of the HL Shield through staking headers, highlighted in blue rectangles of the previous photo.
- Note that there is no stacking header for pin D0 to D7, thus not accessible once stacked. Nucleo’s RX and TX pins (D0 and D1) are connected to module’s UART.
Connecting the Debug cable
- Connect the TTL to Serial Debug cable to Nucleo pin D8 and GND as shown in the previous photo
- Pins D2 and D8 of Nucleo board will be configured programmatically as an serial port for debug output purpose
- Refer to the datasheet of your TTL cable, to perform the following connection:
- the TX wire cannot be connected to Nucleo’s pin D2 (RX) as it is not accessible. Not an issue as Debug output does not make use of RX.
- the RX wire must be connected to Nucleo’s pin D8 (TX)
- the Ground wire must be connected to Nucleo’s GND pin
- Connect the TTL cable to USB Hub which is connected to your PC/Mac
- If USB driver is missing, VCP driver for FTDI-based TTL cables can be downloaded here
In Step 1, we’ve covered how to:
- Configure HL Shield and stack it over the Nucleo board
- Connect HL Module’s UART to your host USB port
- Connect a debug cable (additional serial port configured on Nucleo pins D2 & D8) to your host USB port
- Reference to USB driver has also been provided
Embedded System Overview
- mbed platform will be used to develop the application. Source code is compiled online using web browser, Nucleo binary code is downloaded then uploaded locally to Nucleo.
- Sierra Wireless MQTT Client library (SWIR_MQTTClient) will be leveraged in order to easily establish communication between AirVantage and Nucleo. This library provides 3 functionalities:
- Module management: setting SIM pin code, setting APN, making data call, etc…
- MQTT Client: managing MQTT session with AirVantage, sending/receiving MQTT packets over AT commands.
MQTT packets are generated and handled by Paho MQTTClient library which implements MQTT protocol.
- Log output facility: SWI_TRACE macro enables Nucleo app to output debug traces to a virtual serial port. This latter function is emulated on Nucleo pins D2 & D8 (by default) and trace logs are visible with a serial monitor application bound to the TTL to serial USB port.
- HL Shield wires Nucleo’s default Serial port (pins D0 & D1) to HL module UART. Therefore, Nucleo’s Serial object instance is used by SWIR_MQTTClient library to send AT commands to HL module, and shall not be used to output program trace log. For the latter purpose, use SWI_TRACE macro instead.
- HL module’s AT interface trace can be visualized with a serial monitor application bound to the HL Shield Main UART USB port.
Setup Embedded Software Development Components
- Get started with mbed compiler:
- use your favorite web browser and navigate to mbed, then go to Developer Site
- login or signup
- Click on Platforms then select NUCLEO-L053R8 device
- On the Nucleo-L053R8 page, click on Add to your mbed Compiler button
- Click on Open mbed Compiler to launch the development IDE
- Create a new program with provided Program Name (e.g. Nucleo_AVHL) using Empty Program template
- Select your new program then click on Import to open Import Wizard
- In the Libraries tab, drag mbed library (the official mbed C/C++ SDK for building mbed applications) and drop it onto your project
- In the Upload tab, click on browse button:
- Import Paho MQTTClient library: select the prebuilt Arduino port of Paho MQTTClient zip file available here
- Import SWIR_MQTTClient library V0.92: select the MQTTClient library for Sierra Wireless HL serie modules zip file available here
- Import these 2 libraries with a provided Import Name (e.g. Lib)
Setup Debug output
- Unplug all USB plugs on the HUB Hub, while maintaining this latter plugged to your host computer. The intent here is to disconnect the host from all Nucleo/HL Shield USB cables. All virtual COM ports are thus released on the host.
- Debug trace log for Nucleo app
- Launch your favorite Serial monitor software or use the provided TestCom.exe
- Plug the TTL to Serial USB cable to the USB Hub, a virtual COM port shall be mounted accordingly
- Select this virtual COM port and choose 115200 baudrate to open this port in the Serial monitor application
- Output log for HL Module
- Launch a second instance of your favorite Serial monitor software or use the provided TestCom.exe
- Connect the HL Shield Main UART USB port to the USB Hub, a virtual COM port shall be mounted accordingly
- Select this virtual COM port and choose 115200 baudrate to open this port in the Serial monitor application
TestCom.exe tip: When plugging/unplugging a USB device, the associated virtual COM port is displayed in TestCom. Identifying the virtual COM to be openned is then made easy in the 2 above steps.
In Step 2, we’ve covered the following:
- Overview of the HL module-based Nucleo system
- Software Setup :
- mbed development environment
- Import MQTTClient adapter Library for Sierra Wireless HL Serie Modules
- Import Paho MQTTClient Library
- Setup output tracing to view:
- Nucleo application debug trace log
- HL Module’s AT interface trace log
Alarm System Use Case
- On AirVantage portal, the user can turn ON or OFF the Nucleo-based Alarm system
- If the Alarm is be turned ON, Nucleo board shall arm the alarm and switch on the LED
- Then Nucleo shall, on a regular basis, read motion event from PIR sensor, and publish it to AirVantage
- If the Alarm is to be turned OFF, Nucleo shall disarm the alarm system and switch off the LED
- Nucleo shall not post any data to AirVantage
- The data flow and type are therefore defined as follow:
- TurnOn Action command from AirVantage to Device of type boolean. Value true for Turn ON, false for Turn OFF
- Motion event from Device to AirVantage of type integer. Value 1 for Motion detected, 0 for No Motion detected
Alarm System Application Model
- An embedded application on device-side (e.g. Nucleo) is interfacing with a server-side application on AirVantage in order to exchange predefined data over a predefined communication protocol and authentication scheme:
- Server-side application is defined by an Application Model (a XML file)
- AirVantage uses this XML file to figure out how to deal with the device about Communication Protocol, Authentication and Data Exchange (e.g. variable, settings, commands)
Based on the use case as described in the previous section, the application model for our Alarm System is defined here:
- The communication protocol is MQTT, and the authentication is based on the device’s IMEI
<communication>
<protocol comm-id="IMEI" type="MQTT" />
</communication>
- The downstream TurnOn action command and the upstream motion event are defined in an asset labeled My Home, exchanged over MQTT protocol:
<data>
<encoding type="MQTT">
<asset default-label="My Home" id="home">
<setting default-label="Motion Detected" path="motion" type="int"/>
<command path="TurnOn" default-label="Turn on">
<parameter id="Alarm" default-label="Alarm" type="boolean" />
</command>
</asset>
</encoding>
</data>
The Application Model for our Alarm System is now defined. Let’s create it on AirVantage with the 2 following procedures:
Create Application Package
- Save the the Alarm Application Model to file with app file extension (e.g. appmodel.app)
- Zip the app file (e.g. appmodel.zip)
The filename of this zip file is only used for uploading process. AirVantage does not keep track of this zip filename. Only the XML content will be tracked by AirVantage.
Release Application
- Select your zip file (e.g. appmodel.zip)
- Open Advanced settings and select I want to publish my application after releasing it
- Finally, click on Start
Making the First MQTT Connection
- Before developing the Alarm System application, let’s first try to make a MQTT connection between Nucleo and AirVantage
- SWIR_MQTTClient Library provides a Quick Start sample that is intended to be used as a starting point to easily build AirVantage-MQTT-ready application.
- This starting point application can publish data to and receive data from AirVantage… without typing a single line of code.
However this sample app has been configured by default for Arduino platform, do the following to adjust it for Nucleo platform:
- Go to the mbed IDE (web browser)
- Select swir_platform_def.h file, disable TARGET_ARDUINO (//#define TARGET_ARDUINO) and enable TARGET_MBED (#define TARGET_MBED)
- Right-click and Rename the provided sample arduino sketch HL-AV_QuickStart.ino (SWIR_MQTTClient/examples/HL_AV_QuickStart) to HL-AV_QuickStart.cpp
- Right-click then Copy HL-AV_QuickStart.cpp file which is still greyed out due to precedent invalid ino file extension
- Right-click on the top level program folder (e.g. Nucleo-AVHL) then select Paste, now the sample cpp file becomes valid.
- Right-click on the greyed out HL-AV_QuickStart.cpp (in SWIR_MQTTClient/examples/HL_AV_QuickStart) then delete it
- Open the Quick Start sample program (just select HL-AV_QuickStart.cpp)
Adjust the SIM PIN code and APN for your SIM card, change the following definitions in the sketch if necessary:
#define APN "yourAPN"
#define APN_LOGIN "" //your APN login
#define APN_PASSWORD "" //your APN password
#define SIM_PIN_CODE 0 //default is 0000, it's an integer!
Click the Compile button in mbed IDE, this will compile the sample sketch and download the resulting binary
Make sure that the HL Shield is powered off (unplug power adapter)
Connect Nucleo board to USB Hub (connected to Host)
Drag the downloaded mbed compiled binary file and drop it onto the Nucleo mapped drive
Nucleo sample app will automatically run upon program upload completion
Nucleo app logs should be visible in the first serial monitor
Start the HL Module: power on the HL shield then press and hold the red button for 1 second
Nucleo will attempt to establish MQTT session with AirVantage once data call is ready (module registered to network, CGREG = x,1 or x,5)
HL Module AT logs should be visible in the second serial monitor
Verifying MQTT Connection
The MQTT connection outcome (fail and success cases) are described hereafter.
MQTT Connection Failed
- ”— Fail MQTT connect —” log (in serial monitor) indicates an unsuccessful MQTT connection, refer to top-right picture.
- This is the first connection, your HL Module has not been registered in AirVantage, let’s do the following:
- Log into AirVantage portal
- Release and Publish the Application Model as described in the previous sections Create Application Package and Release Application
- Register your system with below information, go to Register activity (refer to bottom-right picture)
- Select the Type of module (as displayed in the serial monitor)
- Copy the Serial Number displayed in serial monitor and pasted it into the Serial Number field
- Copy the IMEI 15-digits displayed in serial monitor and pasted it into the IMEI/ESN field
- Assign a Name
- Click on Register button
- Assign the Alarm Application Model to your device, go to Monitor activity then Systems
- Select your system, as registered in the above steps
- Click on Edit in the More menu
- In the Applications field, type in the name of the application (i.e. arduino-alarm) and select it
- Click on the Credentials icon
- Enter a password, it shall match the one in the sketch (#define MODULE_AV_PASSWORD), by default it is sierra
- Click on Save button
- From this point, the Nucleo should be able to establish a MQTT session, continue the verification with the next sub-section MQTT Connected
- If you have already registered your HL Module on AirVantage portal, then make sure that:
- The Alarm Application Model with MQTT-binding has been created and assigned to your device, refer to case 2 above
- The password assigned in AirVantage to your System/AppModel is matching the one in the sketch (#define MODULE_AV_PASSWORD), it is sierra by default
MQTT Connected
- Connected to AirVantage
- ”— MQTT connected —” log (in serial monitor) indicates a successful MQTT session
- Sending data to AirVantage
- This sample application posts ellapsed milliseconds (since Jan 1st 1970) to AirVantage. The data key name is MilliSec
- To view the data being sent to AirVantage, log into AirVantage portal
- Go to your system monitor page (i.e. Monitor activity, go to Systems, then select Your System)
- Published data is visible in the Last Communication widget
- Receiving data from AirVantage
- This quick start sketch can also receive incoming data sent by AirVantage
- Log into AirVantage portal
- Go to your system monitor page (i.e. Monitor activity, go to Systems, then select Your System)
- Click on
dropdown box then select Custom Command
- In the Application field, select the alarm application (i.e. arduino-alarm)
- Choose a Command and define Parameters then click on Send Command
- This data should be received by your Nucleo, it is displayed in the serial monitor
- Upon receiving command from AirVantage, the device should return an acknowlegment message back to AirVantage.
This ack message is automatically published (by the SWIR_MQTTClient library) to the /acks/json topic, as shown below
In Step 3, we’ve covered how to:
- Define the use case for the Alarm System which helps to figure out the data flow and type
- Create the Alarm Application Model that defines the interface between Nucleo and AirVantage
- Make a first MQTT connection with AirVantage without coding
- Register device in AirVantage and then Assign Alarm Application Model to it
- Verify that Nucleo can publish data to AirVantage
- Verify that Nucleo can receive data from AirVantage
Hardware Setup
- Let’s wire the LED to Nucleo’s digital pin D9 exposed to the top of the shield through stacking header, as shown in the picture
- The short leg pin of the LED shall be wired to the GND
- Wire the PIR’s Output to Nucleo’s digital pin D10 exposed to the top of the shield through stacking header, as shown in the picture
- PIR’s GND and VCC pins shall wired to respectively Nucleo’s GND and 5V pins
Application Development Guideline
- The QuickStart sample, provided by the SWIR_MQTTClient library, should be used as a starting point to develop a new application.
It is structured as follow:
- Configuration
- #define keyword is used to declare configurations which can adjusted by altering default values
- e.g. APN, SIM PIN code, Baudrate, MQTT quality of service level, delays, etc
- This is the right spot to declare additional data key names defined in your application model
- Global variables
- SWIR_MQTTClient object instance is needed as it is the interface with the Library
- A variable to keep track of the SIM status (ready or need SIM pin code)
- You may declare more variables to fulfill your needs
- QuickStart sketch provides a boilerplate code to facilitate the integration with AirVantage
- Check SIM pin, wait for readiness of data call, make MQTT connection, retry mechanism, perform regular task are handled in a proper sequence
- You can customize the application as follow:
- Add your one-time setup code in doCustomSetup() function
- Add your code to be executed on a regular basis when MQTT session is established in doCustomLoopTask(), called by main’s loop()
Usually, this is the placeholder to read sensor data and publish them to AirVantage
- Add your code to execute incoming Commands from AirVantage in messageArrived() function
- Helper functions are provided for your convenience:
- PostData(keyName, value) to publish data (key/value) to AirVantage
- SWI_TRACE macro to print debug trace to serial monitor
Coding the Alarm System
Let’s code this application using the QuickStart sketch as a starting point, following the above guideline
Note the Alarm scenario specific code below can be be activated by enabling the flag ALARM_SCENARIO (#define ALARM_SCENARIO)
In mbed IDE, select HL_AV_QuickStart.cpp file
Configuration:
- Add these new definitions for LED and PIR pins
#define ALARM_STATUS_LED_PIN D9 //the LED is wired to Nucleo's digital pin D9
#define PIR_PIN D10 //the PIR is wired to Nucleo's digital pin D10
- Change data key name to match the ones defined in the Alarm Application Model (defined in Step 3)
- Data key names are prefixed with the asset id (i.e. home).
#define PUBLISH_DATA_NAME "home.motion"
#define INCOMING_DATA_NAME "home.TurnOn.Alarm"
Global variables:
- Declare this new global variable to track the Alarm status (on/off), default is off. Place this line before the setup() function.
int _isAlarmOn = 0;
Declare global variables for the LED and PIR pins
DigitalOut _ledAlarmOnOff(ALARM_STATUS_LED_PIN); //variable binding to this output pin
DigitalIn _pirState(PIR_PIN); //variable binding to this input pin
Publish the motion detection status to AirVantage in the doCustomLoopTask() function
void doCustomLoopTask()
{
if (_isAlarmOn)
{
//At this point, the MQTT session has been established and the Alarm system has been armed
if (_pirState)
{
postData(PUBLISH_DATA_NAME, 1); //Motion detected, let's post this event to AV
}
else
{
postData(PUBLISH_DATA_NAME, 0); //No Motion detected, let's post this event to AV anyway
}
}
}
Handle AirVantage-originated Commands in the messageArrived() function
void messageArrived(const char* szKey, const char* szValue, const char* szTimestamp)
{
SWIR_TRACE(F("\r\n>>> Message from AirVantage: %s = %s @ %s\r\n"), szKey, szValue, szTimestamp);
//based on szKey and szValue let's turn on/off the alarm on/off LED
String sKey = String(szKey);
String sValue = String(szValue);
if (sKey == INCOMING_DATA_NAME)
{
if (sValue == ON_VALUE)
{
_ledAlarmOnOff = true; //Switch ON LED
_isAlarmOn = 1; //Arm the Alarm System
}
else
{
_ledAlarmOnOff = false; /Switch OFF LED
_isAlarmOn = 0; //Disarm the Alarm System
postData(PUBLISH_DATA_NAME, 0); //Publish message : "home.motion = 0", for consistency
}
return 0; //to indicate that the command has been handled
}
return 1; //to indicate unknown command,
//this information will be returned to AirVantage within the ACK message
}
Upload the Alarm app to Nucleo
- Compile the modified application to retrieved the resulting binary via download
- Make sure that the HL Shield is powered off (unplug power adapter)
- Connect Nucleo to USB Hub (to Host)
- Drag the downloaded mbed compiled binary file and drop it onto the Nucleo mapped drive
- Nucleo sample app will automatically run upon program upload completion
- Nucleo app logs should be visible in the first serial monitor
- Start the HL Module: power on the HL shield then press and hold the red button for 1 second
- Nucleo will attempt to establish MQTT session with AirVantage once data call is ready (module registered to network, CGREG = x,1 or x,5)
- HL Module AT logs should be visible in the second serial monitor
Testing the Alarm System
- Refer to Verifying MQTT Connection section in Step 3 to :
- Check the MQTT connection with AirVantage
- Remotely activate the Alarm system by sending Custom Command TurnOn.Alarm on AirVantage
- View motion detection events posted to AirVantage
In Step 4, we’ve covered :
- Nucleo Hardware setup to fulfill the Alarm Use Case
- The guideline to easily develop an AirVantage-MQTT-ready application
- How to to develop the Alarm application using the QuickStart sketch as a starting point