0 Replies Latest reply on Jul 8, 2015 5:50 PM by PranavSanghadia

    MQTT Client : Using Intel Edison with Temperature, Humidity and Barometric Pressure Sensors, RTC, WiFi

    PranavSanghadia

      Hardware

      1) Temperature and Humidity Sensor : HTU21D

      2) Barometric Pressure Sensor : BMP180

      3) Intel Edison Arduino Board

       

      Connection and Setup:

      - Connection: Connect HGU21D and BMP180 to Edison board on I2C Bus

      - Update Edison with latest image

      - Login to Edison using serial port : Execute following command to syncup time

      > rdate "server"

      -  you can find server name from this link (NIST Internet Time Service )

       

      Software

       

      /*****************************************************************************

      * This program reads Temperature, Humidity and Barometric Pressure data

      * from HTU21D and BMP180 sensors and

      *  publishes it JSON format using MQTT

      *

      *  1) Read Sensor Data (HTU21D and BMP180)

      *  2) Connect to WiFi HotSpot

      *  3) Build JSON format

      *  4) Publish data in MQTT format

      Credits: I took MQTT Pub code ported on Edison by tuan.h.bui@intel.com  and modified by sebastian.salomon@intel.com

      Last Modified by: Pranav.K.Sanghadia@intel.com

      ******************************************************************************/

       

      #include <Wire.h>

      #include <WiFi.h>

      #include <MQTTClient.h>

      #include <math.h>

      #include<stdlib.h>

      #include <HTU21D.h>

      #include <time.h>

      #define ALTITUDE 1237    // in feet, Chandler, AZ

       

       

      char ssid[] = "SSID";     //  your network SSID (name)

      char pass[] = "password";    // your network password

      int status = WL_IDLE_STATUS;     // the Wifi radio's status

       

       

      //Create an instance of the object

      MQTTClient mqttClient;

      HTU21D myHumidity;

       

       

      // Sampling Period and MQTT Publish period

      const unsigned long SAMPLING_PERIOD = 1000; // Sample Sensor Data : Every Second

      const unsigned long PUBLISH_INTERVAL = 10000; // Publish MQTT Message : Every 10 Seconds

       

       

      int vectorIndex = 0;

      int openDore;

      double humidity[PUBLISH_INTERVAL / SAMPLING_PERIOD];

      double temperature[PUBLISH_INTERVAL / SAMPLING_PERIOD];

      double pressure[PUBLISH_INTERVAL / SAMPLING_PERIOD];

      double vibration[PUBLISH_INTERVAL / SAMPLING_PERIOD];

       

       

      double a_humidity = 0;

      double a_temperature = 0;

      double a_vibration = 0;

      double a_pressure = 0;

       

       

      char bufT[1000];

      char bufH[1000];

      char bufP[1000];

      char bufO[1000];

      char bufG[1000];

      char bufV[1000];

      char pubBufT[1000];

      char pubBufH[1000];

      char pubBufP[1000];

      unsigned long smplingTime;

      unsigned long publishTime;

      String macStr;

       

       

      byte mac[6];

       

       

      // Following is used to build MQTT message using buildMsg() function, need to fix it...

      String gatewayID = "Gateway007";

      String temperatureSensorId = "111";

      String temperatureSensorName = "TemperatureSensor";

      String temperatureSensorType = "Maker";

      String temperatureSensorDataType = "Float";

      String temperatureSensorDataUnit = "F";

       

       

      String baroPressureSensorId = "222";

      String baroPressureSensorName = "BaroPressureSensor";

      String baroPressureSensorType = "Maker";

      String baroPressureSensorDataType = "Float";

      String baroPressureSensorDataUnit = "mBar";

       

       

      String humiditySensorId = "333";

      String humiditySensorName = "HumiditySensor";

      String humiditySensorType = "Maker";

      String humiditySensorDataType = "Float";

      String humiditySensorDataUnit = "%";

       

       

      String buildingName = "CH7";

      String floorNo = "2";

       

       

      String myMsg;

       

       

       

       

      ///////////////////////////////////////////////////////////

      // TBD: Build JSON Message

      // Note: This function needs some work

      ///////////////////////////////////////////////////////////

      void buildMsg(String sensorId, String sensorName, String sensorType, String dataType, String dataUnit, String dataValue) {

       

        // Read Time

        time_t t = time(NULL);

        struct tm tm = *gmtime(&t); //*localtime(&t);

        char timeBuf[100];

        int milSecondsToday = 1000 * (tm.tm_hour * 3600 + tm.tm_min * 60 + tm.tm_sec);

        sprintf(timeBuf, "%02d-%02d-%04d", tm.tm_mon + 1, tm.tm_mday, tm.tm_year + 1900);

       

       

        myMsg = "{\\\"Sensor\\\":";

        myMsg += "{\\\"Name\\\":\\\"";

        myMsg += sensorName;

        myMsg += "\\\",\\\"Type\\\":\\\"";

        myMsg += sensorType;

        myMsg += "\\\",\\\"SensorID\\\":\\\"";

        myMsg += sensorId;

        myMsg += "\\\",\\\"GatewayID\\\":\\\"";

        myMsg += gatewayID;

        myMsg += "\\\"},";

       

       

        myMsg += "\\\"Location\\\":";

        myMsg += "{\\\"Description\\\":";

        myMsg += "{\\\"BuildingName\\\":\\\"";

        myMsg += buildingName;

        myMsg += "\\\",\\\"FloorNo\\\":\\\"";

        myMsg += floorNo;

        myMsg += "\\\"},";

       

       

        String latitudeUnit = "Deg";

        String latitudeValue = "-111.932870";

        myMsg += "\\\"Latitude\\\":";

        myMsg += "{\\\"Unit\\\":\\\"";

        myMsg += latitudeUnit;

        myMsg += "\\\",\\\"Value\\\":\\\"";

        myMsg += latitudeValue;

        myMsg += "\\\"},";

       

       

        String longitudeUnit = "Deg";

        String longitudeValue = "33.310345";

        myMsg += "\\\"Longitude\\\":";

        myMsg += "{\\\"Unit\\\":\\\"";

        myMsg += longitudeUnit;

        myMsg += "\\\",\\\"Value\\\":\\\"";

        myMsg += longitudeValue;

        myMsg += "\\\"},";

       

       

        String altitudeUnit = "Meter";

        String altitudeValue = "370";

        myMsg += "\\\"Altitude\\\":";

        myMsg += "{\\\"Unit\\\":\\\"";

        myMsg += altitudeUnit;

        myMsg += "\\\",\\\"Value\\\":\\\"";

        myMsg += altitudeValue;

        myMsg += "\\\"}";

        myMsg += "},";

       

       

        String timeFormat = "mm-dd-yyyy:elapsedTimeInMilliSecond";

        String timeZone = "UTC";

        String currentTime(timeBuf);

        currentTime += ":";

        currentTime += String(milSecondsToday);

       

       

        myMsg += "\\\"Data\\\":";

        myMsg += "{\\\"Type\\\":\\\"";

        myMsg += dataType;

        myMsg += "\\\",\\\"Unit\\\":\\\"";

        myMsg += dataUnit;

        myMsg += "\\\",\\\"Value\\\":\\\"";

        myMsg += dataValue;

        myMsg += "\\\",";

       

       

        myMsg += "\\\"TimeStamp\\\":";

        myMsg += "{\\\"Format\\\":\\\"";

        myMsg += timeFormat;

        myMsg += "\\\",\\\"TimeZone\\\":\\\"";

        myMsg += timeZone;

        //  myMsg+= "\",";

       

       

        myMsg += "\\\",\\\"Value\\\":\\\"";

        myMsg += currentTime;

        myMsg += "\\\"}";

       

       

        myMsg += "}";

        myMsg += "}";

      }

       

       

       

       

      void setup() {

       

        Serial.begin(9600);

       

        myHumidity.begin();

        status = WiFi.begin(ssid, pass);

       

        if ( status != WL_CONNECTED) {

          Serial.println("Couldn't get a wifi connection");

          while (true);

        }

        // if you are connected, print out info about the connection:

        else {

          Serial.println("Connected to network");

          WiFi.macAddress(mac);

          Serial.print("MAC: ");

       

          macStr = String(mac[5], HEX);

          macStr += String(mac[4], HEX);

          macStr += String(mac[3], HEX);

          macStr += String(mac[2], HEX);

          macStr += String(mac[1], HEX);

          macStr += String(mac[0], HEX);

          Serial.println(macStr);

        }

       

        mqttClient.begin("Your Moasuitto Broker", 1883, OPEN, NULL, NULL, NULL);                // You can use a public MQTT Broker

       

        smplingTime = millis() + SAMPLING_PERIOD;

        publishTime = millis() + PUBLISH_INTERVAL;

      }

       

       

       

      ///////////////////////////////////////////////////////////////////

      //

      //

      ///////////////////////////////////////////////////////////////////

      void loop() {

       

        char status;

        double T, P, valBaroPressure, a;

       

        // 1. Sample at every SAMPLING_PERIOD

        if (smplingTime < millis()) {

       

          float valHumidity = myHumidity.readHumidity();

          double T = myHumidity.readTemperature();

       

          float valTemperature = 1.8 * T + 32;

          Serial.print("Humidity: "); Serial.print(valHumidity);

          Serial.print(" Temperature-F: "); Serial.println(valTemperature);

       

          // Store values in respective arrays

          humidity[vectorIndex] = valHumidity;

          temperature[vectorIndex] = valTemperature;

          vibration[vectorIndex] = 1;

       

          vectorIndex++;

          smplingTime = millis() + SAMPLING_PERIOD;    // update sampling time

        }

       

        // 2. Publish at every PUBLISH_INTERVAL

        if (publishTime < millis()) {

       

          publishTime = millis() + PUBLISH_INTERVAL;

          for (int j = 0; j <= vectorIndex; j++) {

            a_humidity += humidity[j];

            a_temperature += temperature[j];

            a_vibration += vibration[j];

          }

       

          // Tane an average of sensor data

          snprintf (bufT, sizeof(bufT), "%f", a_temperature / vectorIndex);

          snprintf (bufH, sizeof(bufH), "%f", a_humidity / vectorIndex);

       

          time_t t = time(NULL);

          struct tm tm = *gmtime(&t); //*localtime(&t);

          char timeBuf[200];

          int milSecondsToday = 1000 * (tm.tm_hour * 3600 + tm.tm_min * 60 + tm.tm_sec);

          sprintf(timeBuf, "%02d-%02d-%04d:%d", tm.tm_mon + 1, tm.tm_mday, tm.tm_year + 1900, milSecondsToday);

          Serial.println(timeBuf);

       

          // Publish Temperature

          snprintf (pubBufT, sizeof(pubBufT), "{\\\"Sensor\\\": {\\\"Name\\\": \\\"SensorName\\\",\\\"Type\\\": \\\"Temperature\\\",\\\"SensorId\\\":\\\"111\\\",\\\"GateWayId\\\":\\\"TCW-GW1\\\"},\\\"Location\\\":{\\\"Description\\\": {\\\"BuildingName\\\": \\\"CH7\\\",\\\"FloorNo\\\": \\\"2\\\"},\\\"Latitude\\\":{\\\"Unit\\\" : \\\"Deg\\\",\\\"Value\\\":\\\"45.550695\\\"},\\\"Longitude\\\":{\\\"Unit\\\":\\\"Deg\\\",\\\"Value\\\":\\\"-122.850550\\\"},\\\"Altitude\\\":{\\\"Unit\\\":\\\"meter\\\",\\\"Value\\\":\\\"60\\\"}},\\\"Data\\\":{\\\"Type\\\":\\\"Float\\\",\\\"Unit\\\":\\\"F\\\",\\\"Value\\\":\\\"%s\\\",\\\"TimeStamp\\\":\\\"%s\\\"}}", bufT, timeBuf);

          Serial.println(pubBufT);

          mqttClient.publish("IOT/ARP/TCS", pubBufT);

       

          snprintf (pubBufH, sizeof(pubBufH), "{\\\"Sensor\\\": {\\\"Name\\\": \\\"SensorName\\\",\\\"Type\\\": \\\"Humidity\\\",\\\"SensorId\\\":\\\"222\\\",\\\"GateWayId\\\":\\\"TCW-GW1\\\"},\\\"Location\\\":{\\\"Description\\\": {\\\"BuildingName\\\": \\\"CH7\\\",\\\"FloorNo\\\": \\\"2\\\"},\\\"Latitude\\\":{\\\"Unit\\\" : \\\"Deg\\\",\\\"Value\\\":\\\"45.550695\\\"},\\\"Longitude\\\":{\\\"Unit\\\":\\\"Deg\\\",\\\"Value\\\":\\\"-122.850550\\\"},\\\"Altitude\\\":{\\\"Unit\\\":\\\"meter\\\",\\\"Value\\\":\\\"60\\\"}},\\\"Data\\\":{\\\"Type\\\":\\\"Float\\\",\\\"Unit\\\":\\\"F\\\",\\\"Value\\\":\\\"%s\\\",\\\"TimeStamp\\\":\\\"%s\\\"}}", bufH, timeBuf);

          mqttClient.publish("IOT/ARP/TCS", pubBufH);     // MQTT Publish

          Serial.println(pubBufH);

       

          // TBD: Fix buildMsg() function

       

          //    buildMsg(temperatureSensorId, temperatureSensorName, temperatureSensorType, temperatureSensorDataType, temperatureSensorDataUnit, bufT);

          //    myMsg.toCharArray(pubBufT, sizeof(pubBufT));    // Convert String to Array

          //    mqttClient.publish("IOT/ARP/TCS", pubBufT);     // MQTT Publish

          //    Serial.println(pubBufT);

          /*

              buildMsg(humiditySensorId, humiditySensorName, humiditySensorType, humiditySensorDataType, humiditySensorDataUnit, bufH);

              myMsg.toCharArray(pubBufH, sizeof(pubBufH));

              mqttClient.publish("IOT/ARP/TCS", pubBufH);

              Serial.println(pubBufH);                                                 // Publish

       

              buildMsg(baroPressureSensorId, baroPressureSensorName, baroPressureSensorType, baroPressureSensorDataType, baroPressureSensorDataUnit, bufP);

              myMsg.toCharArray(pubBufP, sizeof(pubBufP));

              mqttClient.publish("IOT/ARP/TCS", pubBufP);               // Publish

              Serial.println(pubBufP);

          */

          // Initialze

          openDore = 0;

          for (int j = 0; j <= vectorIndex; j++) {

            humidity[j] = NULL;

            temperature[j] = NULL;

            vibration[j] = NULL;

          }

       

       

          a_humidity = 0;

          a_temperature = 0;

          a_vibration = 0;

          vectorIndex = 0;

        }

      }