MQTT client for IBM Bluemix

Dependencies:   HTS221 LIS3MDL LPS22HB LSM303AGR LSM6DSL MQTT VL53L0X

Getting started with IBM Bluemix

This is the MQTT Client example for mbed OS. It demonstrates how to connect a device with IBM Bluemix, how to get values from sensors, and how to see them on the IBM quickstart website. If you are unfamiliar with IBM Bluemix, we recommend that you read the introduction starting here.

Demo workflow:

  • Connection to the local network with 6LoWPAN ND connection.
  • Connection to the Quickstart Bluemix.
  • Read data sensors.
  • Sends data sensors to the Quickstart Bluemix

You can compile this project in three ways:

1. Using the Online compiler. Just clicking here:

/media/uploads/rspelta/import-mqtt.jpg

Information

Learn how to use the Online compiler reading https://docs.mbed.com/docs/mbed-os-handbook/en/latest/dev_tools/online_comp/ page.

2. Using the compiler on your PC:

Information

Learn how to use the mbed-cli reading https://docs.mbed.com/docs/mbed-os-handbook/en/latest/dev_tools/cli/ page.
The name of the machine is SILICA_SENSOR_NODE.

3. Exporting to 3rd party tools (IDE) like eclipse, IAR, uvision 5 and more others

Information

Learn how to use the mbed-cli reading https://docs.mbed.com/docs/mbed-os-handbook/en/latest/dev_tools/third_party/ page.

Warning

This example requires a Border Router board. For more details please read the Border Router paragraph from this page.

Please read carefully the next pages:

  • What to do before to compile the project: read here. This step is indipendent from the way you compile the project.

Files at this revision

API Documentation at this revision

Comitter:
rspelta
Date:
Thu Nov 02 11:01:13 2017 +0100
Commit message:
release

Changed in this revision

HTS221.lib Show annotated file Show diff for this revision Revisions of this file
LIS3MDL.lib Show annotated file Show diff for this revision Revisions of this file
LPS22HB.lib Show annotated file Show diff for this revision Revisions of this file
LSM303AGR.lib Show annotated file Show diff for this revision Revisions of this file
LSM6DSL.lib Show annotated file Show diff for this revision Revisions of this file
MQTT.lib Show annotated file Show diff for this revision Revisions of this file
MQTTNetwork.h Show annotated file Show diff for this revision Revisions of this file
VL53L0X.lib Show annotated file Show diff for this revision Revisions of this file
easy-connect.lib Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed-os.lib Show annotated file Show diff for this revision Revisions of this file
mbed_app.json Show annotated file Show diff for this revision Revisions of this file
mbedtls_mbed_client_config.h Show annotated file Show diff for this revision Revisions of this file
diff -r 000000000000 -r e673387d5add HTS221.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTS221.lib	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,1 @@
+https://developer.mbed.org/teams/ST/code/HTS221/#312ee2694a77
diff -r 000000000000 -r e673387d5add LIS3MDL.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LIS3MDL.lib	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,1 @@
+https://developer.mbed.org/teams/ST/code/LIS3MDL/#308889c4d074
diff -r 000000000000 -r e673387d5add LPS22HB.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LPS22HB.lib	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,1 @@
+https://developer.mbed.org/teams/ST/code/LPS22HB/#f7b403c70f6b
diff -r 000000000000 -r e673387d5add LSM303AGR.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LSM303AGR.lib	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,1 @@
+https://developer.mbed.org/teams/ST/code/LSM303AGR/#652f8f67d991
diff -r 000000000000 -r e673387d5add LSM6DSL.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/LSM6DSL.lib	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,1 @@
+https://developer.mbed.org/teams/ST/code/LSM6DSL/#20ccff7dd652
diff -r 000000000000 -r e673387d5add MQTT.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MQTT.lib	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,1 @@
+https://mbed.org/teams/mqtt/code/MQTT/#ff9e5c4b52d0
diff -r 000000000000 -r e673387d5add MQTTNetwork.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MQTTNetwork.h	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,38 @@
+#ifndef _MQTTNETWORK_H_
+#define _MQTTNETWORK_H_
+
+#include "NetworkInterface.h"
+
+class MQTTNetwork {
+public:
+    MQTTNetwork(NetworkInterface* aNetwork) : network(aNetwork) {
+        socket = new TCPSocket();
+    }
+
+    ~MQTTNetwork() {
+        delete socket;
+    }
+
+    int read(unsigned char* buffer, int len, int timeout) {
+        return socket->recv(buffer, len);
+    }
+
+    int write(unsigned char* buffer, int len, int timeout) {
+        return socket->send(buffer, len);
+    }
+
+    int connect(const char* hostname, int port) {
+        socket->open(network);
+        return socket->connect(hostname, port);
+    }
+
+    int disconnect() {
+        return socket->close();
+    }
+
+private:
+    NetworkInterface* network;
+    TCPSocket* socket;
+};
+
+#endif // _MQTTNETWORK_H_
diff -r 000000000000 -r e673387d5add VL53L0X.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/VL53L0X.lib	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,1 @@
+https://os.mbed.com/teams/ST/code/VL53L0X/#e9269ff624ed
diff -r 000000000000 -r e673387d5add easy-connect.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/easy-connect.lib	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,1 @@
+https://github.com/Avnet-Silica-team/easy-connect/#da83992554368d70bea97bd430df4f3665927d1a
\ No newline at end of file
diff -r 000000000000 -r e673387d5add main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,183 @@
+/**
+ ******************************************************************************
+ * @file    main.cpp
+ * @version V1.0.0
+ * @date    27-October-2017
+ * @brief   Simple Example application for using SILICA_SENSOR_NODE with IBM Bluemix
+ *          project ported from X_NUCLEO_IKS01A2 ST project
+ *          
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
+ *
+ * Redistribution and use in source and binary forms, with or without modification,
+ * are permitted provided that the following conditions are met:
+ *   1. Redistributions of source code must retain the above copyright notice,
+ *      this list of conditions and the following disclaimer.
+ *   2. Redistributions in binary form must reproduce the above copyright notice,
+ *      this list of conditions and the following disclaimer in the documentation
+ *      and/or other materials provided with the distribution.
+ *   3. Neither the name of STMicroelectronics nor the names of its contributors
+ *      may be used to endorse or promote products derived from this software
+ *      without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ *  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ ******************************************************************************
+*/ 
+
+/* Includes */
+#include "mbed.h"
+#include "mbed-trace/mbed_trace.h"
+
+#include "HTS221Sensor.h"
+#include "LPS22HBSensor.h"
+#include "LSM6DSLSensor.h"
+
+#include "easy-connect/easy-connect.h"
+
+#include "MQTTNetwork.h"
+#include "MQTT/MQTTmbed.h"
+#include "MQTT/MQTTClient.h"
+
+#define MAX_MQTT_PACKET_SIZE 250
+
+#define logMessage printf
+
+#include "LSM303AGRMagSensor.h"
+#include "LSM303AGRAccSensor.h"
+
+/* Retrieve the composing elements of the expansion board */
+
+/* Interface definition */
+#define SPI_TYPE_LPS22HB   LPS22HBSensor::SPI3W
+#define SPI_TYPE_LSM6DSL   LSM6DSLSensor::SPI3W
+SPI devSPI(PB_15, NC, PB_13);  // 3-wires SPI on SensorTile  
+static Serial ser(PC_12,PD_2); // Serial with SensorTile Cradle Exp. Board + Nucleo   
+#define printf(...) ser.printf(__VA_ARGS__)     
+
+/* Environmental sensors */
+static LPS22HBSensor press_temp(&devSPI, PA_3, NC, SPI_TYPE_LPS22HB); 
+
+/* Motion sensors */
+static LSM6DSLSensor acc_gyro(&devSPI,PB_12, NC, PA_2, SPI_TYPE_LSM6DSL); 
+static LSM303AGRMagSensor magnetometer(&devSPI, PB_1);
+static LSM303AGRAccSensor accelerometer(&devSPI, PC_4);
+
+
+/* Simple main function */
+int main( void )
+{
+  char buf[500];
+  char* topic = MQTT_TOPIC;
+  unsigned int index = 0;
+  uint8_t id;
+  float temp, press;
+  int32_t axes[3];
+  const char* hostname = MQTT_URL_BROKER;
+  int port = 1883;
+
+
+  MQTT::Message message;
+  
+  mbed_trace_init();
+
+  printf("Avnet-Silica Sensor Node\n\rmbed-os-mqtt-client demo\r\n");
+
+  NetworkInterface* network = easy_connect(true);
+  if(network == NULL) {
+    tr_err("\nConnection to Network Failed - exiting application...\n");
+    return -1;
+  }
+
+  MQTTNetwork mqttNetwork(network);
+  MQTT::Client<MQTTNetwork, Countdown, MAX_MQTT_PACKET_SIZE> client(mqttNetwork);
+  printf("Connecting to %s:%d\r\n", hostname, port);
+  int rc = mqttNetwork.connect(hostname, port);
+  if (rc != 0) {
+    tr_err("rc from TCP connect is %d\r\n", rc);
+    return -1;
+  }
+  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
+  data.MQTTVersion = 3;
+  data.clientID.cstring = MQTT_CLIENT_ID;
+  data.username.cstring = MQTT_USERNAME;
+  data.password.cstring = MQTT_PASSWORD;
+  tr_debug( "Connecting with Client Id:  %s\r\n", MQTT_CLIENT_ID );
+  if ((rc = client.connect(data)) != 0) {
+    tr_err("rc from MQTT connect is %d\r\n", rc);
+	return -1;
+  }
+
+  tr_debug("Sending [QoS0], topic: %s\n\r", topic );
+
+	
+  /* Init all sensors with default params */
+  press_temp.init(NULL);
+  magnetometer.init(NULL);
+  acc_gyro.init(NULL);
+  accelerometer.init(NULL);
+  
+  /* Enable all sensors */
+  press_temp.enable();
+  magnetometer.enable();
+  accelerometer.enable();
+  acc_gyro.enable_x();
+  acc_gyro.enable_g();
+
+  press_temp.read_id(&id);
+  tr_debug("LPS22HB pressure & temperature    = 0x%X\r\n", id);
+  magnetometer.read_id(&id);
+  tr_debug("LSM303AGR magnetometer            = 0x%X\r\n", id);
+  accelerometer.read_id(&id);
+  tr_debug("LSM303AGR accelerometer           = 0x%X\r\n", id);
+  acc_gyro.read_id(&id);
+  tr_debug("LSM6DSL accelerometer & gyroscope = 0x%X\r\n", id);
+ 
+  while( rc == 0 ) {    
+    press_temp.get_temperature(&temp);
+    press_temp.get_pressure(&press);
+    tr_debug("LPS22HB: [temp] %.2f C, [press] %.2f mbar\r\n", temp, press);
+    accelerometer.get_x_axes(axes);
+	tr_debug("LSM303AGR [acc/mg]:      %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);        
+#if 0
+    magnetometer.get_m_axes(axes);
+    tr_debug("LSM303AGR [acc/mg]:      %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);        
+    acc_gyro.get_x_axes(axes);
+    tr_debug("LSM6DSL [acc/mg]:        %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
+    acc_gyro.get_g_axes(axes);
+    tr_debug("LSM6DSL [gyro/mdps]:     %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
+#endif
+
+	printf("Sending payload #%d\n\r", index);
+	sprintf(buf,  "{\"%s\": {\"temp\":%.0f,\"humidity\":0,\"pressure\":%.0f,\"ambient\":0,\"uv\":0,\"accel_X\":0,\"accel_Y\":0,\"accel_Z\":0}}", MQTT_SENSOR_ID, temp, press );
+	message.qos = MQTT::QOS0;
+	message.retained = false;
+	message.dup = false;
+	message.payload = (void*)buf;
+	message.payloadlen = strlen(buf);
+	if( (message.payloadlen + strlen(topic)+1) >= MAX_MQTT_PACKET_SIZE )
+		logMessage("message too long!\r\n");
+	rc = client.publish(topic, message);
+	printf( "Sent: %d, rc: %d, payload: %s\r\n", index, rc, buf );
+	index++;
+
+    wait(10);
+  }
+  
+  tr_warning("Server connection closed. (rc = %d)\n", rc);
+  client.disconnect();
+  mqttNetwork.disconnect();	
+  tr_info("Demo ended\r\n");
+  return -1;
+}
diff -r 000000000000 -r e673387d5add mbed-os.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-os.lib	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,1 @@
+https://github.com/Avnet-Silica-team/mbed-os/#acaf97f37387c767a1fecd0eab51ae967f5cfefd
diff -r 000000000000 -r e673387d5add mbed_app.json
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed_app.json	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,49 @@
+{
+    "config": {
+        "network-interface":{
+            "help": "Options are ETHERNET, WIFI_ESP8266, WIFI_ODIN, MESH_LOWPAN_ND, MESH_THREAD",
+            "value": "MESH_LOWPAN_ND"
+        },
+        "mesh_radio_type": {
+        	"help": "options are ATMEL, MCR20, SPIRIT1, EFR32, SENSOR_NODE_SPIRIT1",
+        	"value": "SENSOR_NODE_SPIRIT1"
+        }
+    },
+    "macros": ["MBEDTLS_USER_CONFIG_FILE=\"mbedtls_mbed_client_config.h\"",
+			   "SPIRIT1_SPI_MOSI=PG_11",
+				"SPIRIT1_SPI_MISO=PG_10",
+				"SPIRIT1_SPI_SCLK=PG_9",
+				"SPIRIT1_DEV_IRQ=PC_2",
+				"SPIRIT1_DEV_CS=PG_12",
+				"SPIRIT1_DEV_SDN=NC",
+				"MQTT_URL_BROKER=\"fdff::9f08:a9d4\"",
+				"MQTT_CLIENT_ID=\"g:pvko17:<your DEVICE_ID_TYPE>:<your DEVICE_ID>\"",
+				"MQTT_USERNAME=\"use-token-auth\"",
+				"MQTT_PASSWORD=\"<your DEVICE_ID>\"",
+				"MQTT_TOPIC=\"iot-2/type/<your DEVICE_ID_TYPE>/id/<your DEVICE_ID>/evt/status/fmt/json\"",
+				"MQTT_SENSOR_ID=\"<mmddyyyy>\""],
+    "target_overrides": {
+        "*": {
+        	"target.features_add": ["NANOSTACK", "NANOSTACK_FULL", "COMMON_PAL"],
+            "platform.stdio-baud-rate": 9600,
+            "platform.stdio-convert-newlines": true,
+            "mbed-mesh-api.6lowpan-nd-channel-page": 2,
+            "mbed-mesh-api.6lowpan-nd-channel": 1,
+			"mbed-mesh-api.heap-size": 32300,
+            "mbed-trace.enable": 0,
+            "mbed-mesh-api.6lowpan-nd-security-mode": "PSK",
+            "spirit1.mac-address": "{0x01, 002, 0x03, 0x04, 0x05, <MONTH>, <DAY>, <YEAR>}"
+        },
+        "NUCLEO_F401RE": {
+            "wifi-tx": "PA_11",
+            "wifi-rx": "PA_12"
+        },
+        "NUCLEO_F411RE": {
+            "wifi-tx": "PA_11",
+            "wifi-rx": "PA_12"
+        },
+        "UBLOX_EVK_ODIN_W2": {
+        "target.device_has_remove": ["EMAC"]
+        }
+    }
+}
diff -r 000000000000 -r e673387d5add mbedtls_mbed_client_config.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbedtls_mbed_client_config.h	Thu Nov 02 11:01:13 2017 +0100
@@ -0,0 +1,111 @@
+/**
+ *  Minimal configuration for using mbedtls as part of mbed-client
+ *
+ *  NOTE! This is an optimized, minimal configuration for mbed Client.
+ *  We know it works with mbed Client but if you want to add more
+ *  services/communications to the application yourself - please ensure
+ *  you update this configuration accordingly. The default configuration
+ *  can be found from mbedTLS Github:
+ *
+ *  https://github.com/ARMmbed/mbedtls/blob/development/include/mbedtls/config.h
+ *
+ *
+ *  Copyright (C) 2006-2016, ARM Limited, All Rights Reserved
+ *  SPDX-License-Identifier: Apache-2.0
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License"); you may
+ *  not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ *
+ *  This file is part of mbed TLS (https://tls.mbed.org)
+ */
+
+
+#ifndef MBEDTLS_CUSTOM_CONFIG_H
+#define MBEDTLS_CUSTOM_CONFIG_H
+
+/* System support */
+#define MBEDTLS_HAVE_ASM
+
+/* mbed TLS feature support */
+#define MBEDTLS_ECP_DP_SECP256R1_ENABLED
+#define MBEDTLS_ECP_NIST_OPTIM
+#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
+#define MBEDTLS_SSL_PROTO_TLS1_2
+#define MBEDTLS_SSL_PROTO_DTLS
+#define MBEDTLS_SSL_DTLS_ANTI_REPLAY
+#define MBEDTLS_SSL_DTLS_HELLO_VERIFY
+#define MBEDTLS_SSL_EXPORT_KEYS
+
+/* mbed TLS modules */
+#define MBEDTLS_AES_C
+#define MBEDTLS_ASN1_PARSE_C
+#define MBEDTLS_ASN1_WRITE_C
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_CIPHER_C
+#define MBEDTLS_CTR_DRBG_C
+#define MBEDTLS_ECP_C
+#define MBEDTLS_ENTROPY_C
+#define MBEDTLS_MD_C
+#define MBEDTLS_OID_C
+#define MBEDTLS_PK_C
+#define MBEDTLS_PK_PARSE_C
+#define MBEDTLS_SHA256_C
+#define MBEDTLS_SSL_COOKIE_C
+#define MBEDTLS_SSL_CLI_C
+#define MBEDTLS_SSL_SRV_C
+#define MBEDTLS_SSL_TLS_C
+
+// XXX mbedclient needs these: mbedtls_x509_crt_free, mbedtls_x509_crt_init, mbedtls_x509_crt_parse
+#define MBEDTLS_X509_USE_C
+#define MBEDTLS_X509_CRT_PARSE_C
+
+// XXX: clean these up!!
+#define MBEDTLS_SHA512_C
+#define MBEDTLS_ECDH_C
+#define MBEDTLS_GCM_C
+
+#define MBEDTLS_ECDH_C
+#define MBEDTLS_ECDSA_C
+#define MBEDTLS_X509_CRT_PARSE_C
+
+// Remove RSA, save 20KB at total
+#undef MBEDTLS_RSA_C
+#undef MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
+
+// Remove error messages, save 10KB of ROM
+#undef MBEDTLS_ERROR_C
+
+// Remove selftesting and save 11KB of ROM
+#undef MBEDTLS_SELF_TEST
+
+// Reduces ROM size by 30 kB
+#undef MBEDTLS_ERROR_STRERROR_DUMMY
+#undef MBEDTLS_VERSION_FEATURES
+#undef MBEDTLS_DEBUG_C
+
+// needed for parsing the certificates
+#define MBEDTLS_PEM_PARSE_C
+// dep of the previous
+#define MBEDTLS_BASE64_C
+
+// Reduce IO buffer to save RAM, default is 16KB
+#define MBEDTLS_SSL_MAX_CONTENT_LEN 2048
+
+// define to save 8KB RAM at the expense of ROM
+#undef MBEDTLS_AES_ROM_TABLES
+
+// Save ROM and a few bytes of RAM by specifying our own ciphersuite list
+#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
+
+#include "mbedtls/check_config.h"
+
+#endif /* MBEDTLS_CUSTOM_CONFIG_H */