Pelion Device Management example over 15.4 Thread for Thunderboard Sense 2 board

Dependencies:   ICM20648 BMP280 Si1133 Si7210 AMS_CCS811_gas_sensor SI7021

DEPRECATED

This example application is not maintained and not recommended. It uses an old version of Mbed OS, Pelion DM, and Arm toolchain. It doesn't work with Mbed Studio.

Please use: https://os.mbed.com/teams/mbed-os-examples/code/mbed-os-example-pelion/

This example is known to work great on the following platforms:

Follow the Quick-Start instructions: https://cloud.mbed.com/quick-start

Thunderboard Sense 2

Example functionality

This example showcases the following device functionality:

  • Read onboard sensors, and report them as Pelion LWM2M resources:
    • Barometric Pressure and Temperature (BMP280)
    • Relative Humidity and Temperature (Si7021)
    • Air quality - CO2 and tVOC (CCS811)
    • Light intensity and UV level (Si1133)
    • Hall effect and Temperature (Si7210)
    • Accelerometer and Gyroscope (ICM20648)
  • It also exposes the RGB LEDs for triggering flashes in a specific color
  • On user button click, increment Pelion LWM2M button resource.

/media/uploads/screamer/pelion_st_humidity_reading.png?v=2

15.4 Thread setup

This example program requires that a Thread Border Router is available. A Border Router is a network gateway between a wireless 6LoWPAN mesh network and a backhaul network. It controls and relays traffic between the two networks. In a typical setup, a 6LoWPAN border router is connected to another router in the backhaul network (over Ethernet or a serial line) which in turn forwards traffic to/from the internet or a private company LAN, for instance.

https://raw.githubusercontent.com/ARMmbed/nanostack-border-router/f8bf21aac12c9926afba252187e2adf2525bf1eb/images/br_role.png

Instructions how to set up a Thread Border Router

Use this example with Mbed CLI

1. Import the application into your desktop:

mbed import https://os.mbed.com/teams/SiliconLabs/code/pelion-example-tbsense2

cd pelion-example-tbsense2

2. Install the CLOUD_SDK_API_KEY

mbed config -G CLOUD_SDK_API_KEY <PELION_DM_API_KEY>

For instructions on how to generate your API key, please see the documentation.

3. Initialize firmware credentials (done once per repository). You can use the following command:

mbed dm init -d "<your company name in Pelion DM>" --model-name "<product model identifier>" -q --force

If above command do not work for your Mbed CLI, please consider upgrading Mbed CLI to version 1.8.x or above.

4. Compile and program:

mbed compile -t <toolchain> -m TB_SENSE_2

(supported toolchains : GCC_ARM / ARM / IAR)

5. You can connect on a virtual terminal/COM port to the platform using:

mbed sterm -b 115200

This should give you an output similar to:

[BOOT] Mbed Bootloader
[BOOT] ARM: 00000000000000000000
[BOOT] OEM: 00000000000000000000
[BOOT] Layout: 0 90AC
[BOOT] Active firmware integrity check:
[BOOT] SHA256: 615A11A7F03B1F048573E2CB51D8C9A5DD4E6F17A7F8E79C4B64E3241FF78974
[BOOT] Version: 1553594998
[BOOT] Slot 0 is empty
[BOOT] Active firmware up-to-date
[BOOT] Application's start address: 0x10400
[BOOT] Application's jump address: 0x10FBD
[BOOT] Application's stack address: 0x20040000
[BOOT] Forwarding to application...


Starting Simple Pelion Device Management Client example
You can hold the user button during boot to format the storage and change the device identity.
Connecting to the network using 802.15.4...
Connected to the network successfully. IP address: 2001:****:****:****:****:****:****:73bc
Initializing Pelion Device Management Client...
Si7021 Electronic Serial Number:                0         15b5ffff, firmware rev 20
Registered to Pelion Device Management. Endpoint Name: 0169b91a********************01a0
                                                                 
BMP280 temp:     32.750 C,   pressure: 1030.750 [mbar]            
Si7021 temp:     27.529 C,   humidity:   24.842 %                 
Si7210 temp:     34.484 C,   field:      -0.076 [mT]              
Si1133 light:  1258.574 lux, UV level:    0.031                       
CCS811 CO2:           0 ppm, VoC:             0 ppb                   
ICM20648 acc:    -0.093 x,  -0.057 y,     0.969 z [mg]            
ICM20648 gyro:   -1.503 x,   0.122 y,    -0.771 z [mdps]          
    
Revision:
0:3853978178c0
Child:
1:cf0bd0446785
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Fri Mar 22 00:58:50 2019 +0000
@@ -0,0 +1,354 @@
+// Includes and declarations for Pelion DM Client to work
+#include "simple-mbed-cloud-client.h"
+#include "BlockDevice.h"
+#include "LittleFileSystem.h"
+#include "NetworkInterface.h"
+#include "mbed_trace.h"
+#include "Nanostack.h"
+#include "ns_file_system.h"
+
+#define TRACE_GROUP "APP"
+
+// Thunderboard Sense 2 connects over 802.15.4 by default. Since the mesh
+// stack is a bit iffy, we'll register a 'network down' handler to act as
+// a kind of watchdog for the Pelion DM Client.
+NetworkInterface *net = NetworkInterface::get_default_instance();
+
+// Thunderboard Sense 2 has a 1M external flash, which is being shared
+// between upgrade storage and LittleFS. LittleFS is instantiated at the
+// start of storage, until the start address for upgrade storage.
+// Currently, this split is at 256/768 for FS/upgrade.
+BlockDevice* bd = BlockDevice::get_default_instance();
+SlicingBlockDevice sd(bd, 0, MBED_CONF_UPDATE_CLIENT_STORAGE_ADDRESS);
+LittleFileSystem fs("fs", &sd);
+
+// An event queue is a very useful structure to debounce information between
+// contexts (e.g. ISR and normal threads)
+// This is great because things such as network operations are illegal in ISR,
+// so updating a resource in a button's fall() function is not allowed.
+EventQueue eventQueue;
+
+DigitalIn rst_btn(BTN0);
+
+//------------------------------------------------------------------------------
+// Includes and declarations for our sensor array
+#include "BMP280.h"
+#include "Si1133.h"
+#include "SI7021.h"
+#include "AMS_CCS811.h"
+
+// Define measurement intervals in seconds
+#define LIGHT_MEASURING_INTERVAL        (600)
+#define RHT_MEASURING_INTERVAL          (600)
+#define BAROMETER_MEASURING_INTERVAL    (600)
+#define AQ_AVERAGING_SAMPLES            (10)
+
+/* Turn on power supply to ENV sensor suite */
+DigitalOut env_en(PF9, 1);
+/* Turn on power to CCS811 sensor */
+DigitalOut ccs_en(PF14, 1);
+
+BMP280 barometer(PC4, PC5);
+Si1133 light_sensor(PC4, PC5);
+SI7021 rht_sensor(PC4, PC5, SI7021::SI7021_ADDRESS, 400000);
+
+InterruptIn ccs_int(PF13);
+I2C ccs_i2c(PB6, PB7);
+AMS_CCS811 aqs(&ccs_i2c, PF15);
+
+// When called, will trigger a light sensor measurement and update the resources
+void measure_lux(MbedCloudClientResource *light_var, MbedCloudClientResource *uv_var) {
+    float light_level, uv_index;
+    bool result = light_sensor.get_light_and_uv(&light_level, &uv_index);
+    if (result) {
+        if (light_var) light_var->set_value(light_level);
+        if (uv_var) uv_var->set_value(uv_index);
+    } else {
+        tr_warn("Could not take measurement from lux sensor");
+    }
+}
+
+// When called, will trigger an RHT measurement and update the resources
+void measure_rht(MbedCloudClientResource *temperature, MbedCloudClientResource *humidity) {
+    SI7021::SI7021_status_t result = rht_sensor.SI7021_TriggerHumidity( SI7021::SI7021_NO_HOLD_MASTER_MODE );
+    if (result == SI7021::SI7021_SUCCESS) {
+        wait_ms(30);
+        SI7021::SI7021_vector_data_t result_data;
+        result = rht_sensor.SI7021_ReadHumidity( &result_data );
+        if (result == SI7021::SI7021_SUCCESS) {
+            if (humidity) humidity->set_value(result_data.RelativeHumidity);
+        } else {
+            tr_warn("Could not get humidity from RHT sensor");
+        }
+        result = rht_sensor.SI7021_ReadTemperatureFromRH( &result_data );
+        if (result == SI7021::SI7021_SUCCESS) {
+            if (temperature) temperature->set_value(result_data.Temperature);
+        } else {
+            tr_warn("Could not get temperature from RHT sensor");
+        }
+
+        aqs.env_data(result_data.RelativeHumidity, result_data.Temperature);
+    } else {
+        tr_warn("Could not take measurement from RHT sensor");
+    }
+}
+
+// When called, will trigger a barometer measurement and update the resources
+void measure_baro(MbedCloudClientResource *pressure) {
+    float result = barometer.getPressure();
+    if (result > 0) {
+        if (pressure) pressure->set_value(result);
+    } else {
+        tr_warn("Could not take measurement from barometric sensor");
+    }
+}
+
+// When called, will read out the CCS811 measurement
+void measure_airquality(MbedCloudClientResource *eco2, MbedCloudClientResource *tvoc) {
+    static uint32_t co2_buf[AQ_AVERAGING_SAMPLES] = {0};
+    static uint32_t voc_buf[AQ_AVERAGING_SAMPLES] = {0};
+    static size_t num_samples = 0;
+    static bool started = false;
+
+    aqs.has_new_data();
+    co2_buf[num_samples] = aqs.co2_read();
+    voc_buf[num_samples] = aqs.tvoc_read();
+
+    if ((num_samples == 0) && started) {
+        int co2 = 0, voc = 0;
+        for (size_t i = 0; i < AQ_AVERAGING_SAMPLES; i++) {
+            co2 += co2_buf[i];
+            voc += voc_buf[i];
+        }
+
+        co2 = co2 / AQ_AVERAGING_SAMPLES;
+        voc = voc / AQ_AVERAGING_SAMPLES;
+
+        if (eco2) eco2->set_value(co2);
+        if (tvoc) tvoc->set_value(voc);
+    }
+
+    started = true;
+    num_samples = (num_samples + 1) % AQ_AVERAGING_SAMPLES;
+}
+
+void blink_callback(MbedCloudClientResource *resource, const uint8_t *buffer, uint16_t size) {
+    static int num_count = 0;
+    static int event = 0;
+
+    static DigitalOut led_ch_red(PD11, 1);
+    static DigitalOut led_ch_green(PD12, 1);
+    static DigitalOut led_ch_blue(PD13, 1);
+
+    static DigitalOut led_com_0(PI0, 0);
+    static DigitalOut led_com_1(PI1, 0);
+    static DigitalOut led_com_2(PI2, 0);
+    static DigitalOut led_com_3(PI3, 0);
+
+    static DigitalOut led_rgb_en(PJ14, 0);
+
+    if (buffer != NULL) {
+        tr_info("POST received. POST data: %s\n", buffer);
+
+        if (event > 0) {
+            tr_info("Not blinking since previous blink still in progress\n");
+            return;
+        }
+        num_count = 0;
+        for (size_t i = 0, num_arg = 0; i < 20 || buffer[i] == 0; i++) {
+            if (buffer[i] == ':') {
+                num_arg++;
+                continue;
+            }
+
+            if (buffer[i] >= '0' && buffer[i] <= '9') {
+                switch (num_arg) {
+                    case 0:
+                    if (buffer[i] == '1') {
+                        led_ch_red = 1;
+                    } else {
+                        led_ch_red = 0;
+                    }
+                    break;
+                    case 1:
+                    if (buffer[i] == '1') {
+                        led_ch_green = 1;
+                    } else {
+                        led_ch_green = 0;
+                    }
+                    break;
+                    case 2:
+                    if (buffer[i] == '1') {
+                        led_ch_blue = 1;
+                    } else {
+                        led_ch_blue = 0;
+                    }
+                    break;
+                    case 3:
+                    num_count = ((buffer[i] - 0x30) * 2) - 1;
+                    tr_info("blinking %d\n", num_count);
+                    break;
+                    default:
+                    break;
+                }
+            } else {
+                //garbage...
+                continue;
+            }
+            if (num_count > 0) {
+                break;
+            }
+        }
+
+        if (num_count > 0) {
+            led_rgb_en = 1;
+            led_com_0 = 1;
+            led_com_1 = 1;
+            event = eventQueue.call_in(1000, blink_callback, resource, (const uint8_t *)NULL, 0);
+            if (event == 0) {
+                led_rgb_en = 0;
+                num_count = 0;
+            }
+        }
+    } else {
+        tr_info("blink cb\n");
+        num_count--;
+        led_com_0 = (num_count & 1);
+        led_com_1 = (num_count & 1);
+
+        if (num_count == 0) {
+            led_rgb_en = 0;
+            event = 0;
+        } else {
+            event = eventQueue.call_in(1000, blink_callback, resource, (const uint8_t *)NULL, 0);
+            if (event == 0) {
+                led_rgb_en = 0;
+                num_count = 0;
+            }
+        }
+    }
+}
+
+int main() {
+    // If the User button is pressed ons start, then format storage.
+    if (rst_btn == 0) {
+        printf("User button is pushed on start. Formatting the storage...\n");
+        int storage_status = bd->erase(0, bd->size());
+        if (storage_status != 0) {
+            printf("ERROR: Failed to erase the storage (%d).\n", storage_status);
+        }
+        storage_status = StorageHelper::format(&fs, &sd);
+        if (storage_status != 0) {
+            printf("ERROR: Failed to reformat the storage (%d).\n", storage_status);
+        }
+    } else {
+        printf("You can hold the user button during boot to format the storage and change the device identity.\n");
+    }
+
+    Nanostack::get_instance(); // ensure Nanostack is initialised
+    ns_file_system_set_root_path("/fs/");
+
+    /* Initialize connectivity */
+    net->connect();
+
+    /* Initialize Simple Pelion DM Client */
+    SimpleMbedCloudClient client(net, &sd, &fs);
+    client.init();
+
+    /* Create resources */
+
+    /* Thunderboard Sense 2 has *A LOT* of sensors. This demo app will expose:
+     * * Temperature
+     * * Relative Humidity
+     * * CO2
+     * * tVOC
+     * * light intensity (lux)
+     * * barometric pressure
+     * It also exposes the RGB LEDs for triggering flashes in a specific color
+     */
+    MbedCloudClientResource *variable;
+    variable = client.create_resource("3201/0/5853", "LED blinking (R:G:B:cnt)");
+    variable->observable(false);
+    variable->set_value("0:0:0:0");
+    variable->attach_post_callback(blink_callback);
+    variable->methods(M2MMethod::POST);
+
+    MbedCloudClientResource *lux_res;
+    lux_res = client.create_resource("3301/0/5853", "LightIntensity (lux)");
+    lux_res->observable(true);
+    lux_res->methods(M2MMethod::GET);
+
+    MbedCloudClientResource *baro_res;
+    baro_res = client.create_resource("3323/0/5853", "Barometric pressure (hPa)");
+    baro_res->observable(true);
+    baro_res->methods(M2MMethod::GET);
+
+    MbedCloudClientResource *temperature_res;
+    temperature_res = client.create_resource("3303/0/5853", "Temperature (C)");
+    temperature_res->observable(true);
+    temperature_res->methods(M2MMethod::GET);
+
+    MbedCloudClientResource *humidity_res;
+    humidity_res = client.create_resource("3304/0/5853", "Humidity (%)");
+    humidity_res->observable(true);
+    humidity_res->methods(M2MMethod::GET);
+
+    MbedCloudClientResource *co2_res;
+    co2_res = client.create_resource("33255/0/5853", "CO2 (ppm)");
+    co2_res->observable(true);
+    co2_res->methods(M2MMethod::GET);
+
+    MbedCloudClientResource *voc_res;
+    voc_res = client.create_resource("33256/0/5853", "VOC (ppm)");
+    voc_res->observable(true);
+    voc_res->methods(M2MMethod::GET);
+
+    /* Register the device */
+    client.register_and_connect();
+
+    /* Set up measurements */
+    barometer.initialize();
+    eventQueue.call_every(BAROMETER_MEASURING_INTERVAL * 1000,
+                          measure_baro, baro_res);
+    measure_baro(baro_res);
+
+    if (light_sensor.open()) {
+        measure_lux(lux_res, (MbedCloudClientResource *)NULL);
+        eventQueue.call_every(LIGHT_MEASURING_INTERVAL * 1000,
+                              measure_lux, lux_res,
+                              (MbedCloudClientResource *)NULL);
+    } else {
+        tr_err("Disabling Si1133 because we can't find it on the bus");
+    }
+
+    SI7021::SI7021_status_t result = rht_sensor.SI7021_SoftReset();
+    if (result == SI7021::SI7021_SUCCESS) {
+        wait_ms ( 15 );
+        SI7021::SI7021_vector_data_t result_data;
+        result = rht_sensor.SI7021_Conf(SI7021::SI7021_RESOLUTION_RH_11_TEMP_11,
+                                        SI7021::SI7021_HTRE_DISABLED);
+        result = rht_sensor.SI7021_GetElectronicSerialNumber(&result_data);
+        result = rht_sensor.SI7021_GetFirmwareRevision(&result_data);
+        tr_info("Si7021 Electronic Serial Number: %16x %16x\n",
+                result_data.ElectronicSerialNumber_MSB,
+                result_data.ElectronicSerialNumber_LSB);
+        tr_info("Firmware Revision: %02x\r\n", result_data.FirmwareRevision);
+
+        measure_rht(temperature_res, humidity_res);
+        eventQueue.call_every(RHT_MEASURING_INTERVAL * 1000,
+                              measure_rht, temperature_res, humidity_res);
+    }
+
+    /* Initialize air quality sensor */
+    if(!aqs.init()) {
+        tr_err("Failed CCS811 init\r\n");
+    } else {
+        if(!aqs.mode(AMS_CCS811::SIXTY_SECOND)) {
+            tr_err("Failed to set CCS811 mode\r\n");
+        }
+        ccs_int.fall(eventQueue.event(measure_airquality, co2_res, voc_res));
+        aqs.enable_interupt(true);
+    }
+
+    eventQueue.dispatch_forever();
+}
\ No newline at end of file