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.

main.cpp

Committer:
rspelta
Date:
2017-11-02
Revision:
0:e673387d5add

File content as of revision 0:e673387d5add:

/**
 ******************************************************************************
 * @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;
}