MultiTech Dragonfly with ROHM Sensor board sending data to IBM BlueMix Quickstart

Dependencies:   mbed mtsas FXAS21002 FXOS8700 mbed-rtos

Fork of AvnetWorking_IBM_QuickStart by Paul Jaeger

Revision:
6:8f1ad9d2193e
Parent:
5:dbedb2422089
Child:
7:3d2a3fd4a523
--- a/main.cpp	Tue Aug 23 00:34:17 2016 +0000
+++ b/main.cpp	Tue Aug 23 02:17:54 2016 +0000
@@ -1,25 +1,4 @@
-/* Copyright (c) 2015 NXP Semiconductors. MIT License
-*
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
-* and associated documentation files (the "Software"), to deal in the Software without
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
-* Software is furnished to do so, subject to the following conditions:
-*
-* The above copyright notice and this permission notice shall be included in all copies or
-* substantial portions of the Software.
-*
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-* 8/12/2016  I will be making mistakes in this code.
-* 8/15/2016  I2C bus in the code is on D14/D15 Arduino Pinout.  FRDM-STBD-AGM01 board is jumpered
-*   to use the wrong pins vs the code.  Move the Jumpers from I2C-SCL1 to 0 and I2C-SDA1 to 0
-*/
-/** Combination of MultiTech HTTPS Example
+/** Combination of MultiTech HTTPS Example using json with ROHM Sennsor board and IBM Bluemix
  *
  * Configures the Sensor board for Ambient Light, cellular radio, brings up the cellular link,
  * and does HTTPS POST requests.
@@ -31,15 +10,22 @@
  *   - MultiTech UDK2 (4" square white PCB with Arduino headers, antenna
  *     connector, micro USB ports, and 40-pin connector for Dragonfly)
  *   - MultiTech Dragonfly (1"x2" green PCB with Telit radio)
- *   - NXP Freesclae FRDM-STBC-AGM01
- *     3-axis accelerometer + 3-axis magnetometer, 3-axis gyroscope,
+ *   - Rohm Electronics Sensor Board
+ *   - Expansion board (LSM6DS0
+ *     3-axis accelerometer + 3-axis gyroscope, LIS3MDL 3-axis
+ *     magnetometer, HTS221 humidity and temperature sensor and LPS25HB
+ *     pressure sensor)
  *
  * What this program does:
- *   - reads data from all sensors
+ *   - reads data from all sensors on board
  *   - prints all sensor data to debug port on a periodic basis
  *   - optionally send data to BlueMix
  *   - All data is sent to a specific location determined by the student login.
  *   - BlueMix cloud platform (user must create own account and configure a device
+ *       - you need to set the "VENDOR" and "MODEL"
+
+ *       - you need to set the "do_cloud_post" flag to true for this to
+ *         work
  *
  * Setup:
  *   - Correctly insert SIM card into Dragonfly
@@ -55,35 +41,45 @@
  *
  ************************************************************************/
 /*
- * Sample Program Description:
- *   This Program will enable to Multi-Tech Dragonfly platform to utilize NXP Freescale FRDM-STBC-AGM01 Shield Board.
- *   This program will initialize sensors on the shield and then read back the sensor data.
- *   Data will then be output to the UART Debug Terminal.
+Sample Program Description:
+   This Program will enable to Multi-Tech Dragonfly platform to utilize ROHM's Multi-sensor Shield Board.
+   This program will initialize all sensors on the shield and then read back the sensor data.
+   Data will then be output to the UART Debug Terminal every 1 second.
+
+Sample Program Author:
+   ROHM USDC
+
+Additional Resources:
+   ROHM Sensor Shield GitHub Repository: https://github.com/ROHMUSDC/ROHM_SensorPlatform_Multi-Sensor-Shield
+ * NOTE: This example changes the baud rate of the debug port to 115200 baud!
  */
 
 #include "mbed.h"
 #include "mtsas.h"
 #include "ssl_certificates.h"
 #include <string>   // added for string manipulation
-#include <vector>   // added for SMS example
-#include <iterator> // added for SMS example
-#include <sstream>  // added for HTTP 
-#include "FXAS21002.h"  // added for nxp (freescale) sensor board
-#include "FXOS8700.h"   // added for nxp (freescale) sensor board
+#include <sstream>
+#include "FXAS21002.h"
+#include "FXOS8700.h"
 
-//-------- Customise these values -----------
+// Initialize pins for I2C communication for sensors. Set jumpers J6,J7 in FRDM-STBC-AGM01 board accordingly.
+FXOS8700 accel(D14,D15);
+FXOS8700 mag(D14,D15);
+FXAS21002 gyro(D14,D15);
 
-#define ORG "quickstart" // your organization or "quickstart"
-#define DEVICE_TYPE "dragonflytype" // use this default for quickstart or customize to your registered device type
-#define DEVICE_ID "dragonfly01" // use this default for quickstart or customize to your registered device id
-#define TOKEN "token" // not used with "quickstart"
-#define EVENT "myEvent" // use this default or customize to your event type
-//-------- Customise the above values --------
+
+char streamAcc[] = "acc_rms"; // Stream you want to push to
+char streamMag[] = "mag_rms"; // Stream you want to push to
+char streamGyr[] = "gyr_rms"; // Stream you want to push to
 
 
 //*****************************************************************************************************************************************************
 DigitalOut Led1Out(LED1);
 
+
+// This line controls the regulator's battery charger.
+// BC_NCE = 0 enables the battery charger
+// BC_NCE = 1 disables the battery charger
 DigitalOut bc_nce(PB_2);
 
 bool init_mtsas();
@@ -99,70 +95,36 @@
 
 bool radio_ok = false;
 
-//Define Pins for I2C Interface
-I2C i2c(I2C_SDA, I2C_SCL);
-bool        RepStart = true;
-bool        NoRepStart = false;
-
+bool init_mtsas();
 char* httpResToStr(HTTPResult res);
 
-namespace patch  // this  may be something to delete *********************
-{
-template < typename T > std::string to_string( const T& n )
-{
-    std::ostringstream stm ;
-    stm << n ;
-    return stm.str() ;
-}
-}
-
-
-// Initialize Serial port
-Serial pc(USBTX, USBRX);
-int pc_baud = 115200;
-
-// Initialize pins for I2C communication for sensors. Set jumpers J6,J7 in FRDM-STBC-AGM01 board accordingly.
-FXOS8700 accel(D14,D15);
-FXOS8700 mag(D14,D15);
-FXAS21002 gyro(D14,D15);
-
-// Set Sensor Stream details
-char streamAcc[] = "acc_rms"; // Stream you want to push to
-char streamMag[] = "mag_rms"; // Stream you want to push to
-char streamGyr[] = "gyr_rms"; // Stream you want to push to
-
-
 /****************************************************************************************************
 // main
  ****************************************************************************************************/
 
 int main()
 {
-    // Disable the battery charger unless a battery is attached.
-    bc_nce = 1;
 
-    // Change the baud rate of the debug port from the default 9600 to 115200.
-//    Serial debug(USBTX, USBRX);
-//    debug.baud(115200);
-    pc.baud(pc_baud);
-
-    // Configure Accelerometer FXOS8700, Magnetometer FXOS8700 & Gyroscope FXAS21002
     accel.accel_config();
     mag.mag_config();
     gyro.gyro_config();
 
     float accel_data[3];
-    float accel_rms=0.0;
-    float mag_data[3];
-    float mag_rms=0.0;
-    float gyro_data[3];
-    float gyro_rms=0.0;
+    //float mag_data[3];
+    //float gyro_data[3];
 
-    logDebug("Begin Data Acquisition from FXOS8700 and FXAS21002....\r\n\r\n");
+    printf("Begin Data Acquisition from FXOS8700 and FXAS21002....\r\n\r\n");
+    wait(0.5);
 
-    static int post_interval_ms = 10000; //************* it was 30000, I don't want to wait 30 seconds ************************/
 
 
+    // Disable the battery charger unless a battery is attached.
+    bc_nce = 1;
+
+
+    // Change the baud rate of the debug port from the default 9600 to 115200.
+    Serial debug(USBTX, USBRX);
+    debug.baud(115200);
 
     //Sets the log level to INFO, higher log levels produce more log output.
     //Possible levels: NONE, FATAL, ERROR, WARNING, INFO, DEBUG, TRACE
@@ -181,97 +143,81 @@
         }
     }
 
-    Timer post_timer;
-    post_timer.start();
-    int timeStamp;
-    int countingLoop = 0;
-    Timer loop_timer;
-    loop_timer.start();
 
     logInfo("setting APN");
     if (radio->setApn(apn) != MTS_SUCCESS)
         logError("failed to set APN to \"%s\"", apn);
     logInfo("APN set successful");
 
-    logInfo("bringing up the link");                  //added to the program to create a connection outside of the while(1) loop.
-    if (! radio->connect()) {
-        logError("failed to bring up the link");
-        //return 0;
-    } else {
+    Timer post_timer;
+    post_timer.start();
+    static int post_interval_ms = 500; //************* I don't want to wait 30 seconds ************************/
+    int timeStamp;
+    int countingLoop = 0;
 
-        logInfo("Entering loop");
-        while (countingLoop < 5 ) {
-            if (post_timer.read_ms() > post_interval_ms  ) {            // can this be changed to seconds?
-                timeStamp = post_timer.read_ms();
-                logDebug("timer read %d", timeStamp);
-                logDebug("timer value %d",  post_interval_ms );
-                logDebug("loop count value %d",  countingLoop );
+    logInfo("Entering loop");
+    while (countingLoop < 5 ) {
+        if (post_timer.read_ms() > post_interval_ms ) {            // can this be changed to seconds?
+            timeStamp = post_timer.read_ms();
+            logDebug("timer read %d", timeStamp);
+            logDebug("timer value %d",  post_interval_ms );
+            logDebug("loop count value %d",  countingLoop );
 
-                accel.acquire_accel_data_g(accel_data);
-                accel_rms = sqrt(((accel_data[0]*accel_data[0])+(accel_data[1]*accel_data[1])+(accel_data[2]*accel_data[2]))/3);
-                logDebug("accel %4.2f,\t%4.2f,\t%4.2f,\t\n",accel_data[0],accel_data[1],accel_data[2]);
-                wait(0.01);
+            accel.acquire_accel_data_g(accel_data);
+            float dataX = accel_data[0];
+            float dataY = accel_data[1];
+            float dataZ = accel_data[2];
 
-                mag.acquire_mag_data_uT(mag_data);
-                logDebug("mag %4.2f,\t%4.2f,\t%4.2f,\t\n",mag_data[0],mag_data[1],mag_data[2]);
-                mag_rms = sqrt(((mag_data[0]*mag_data[0])+(mag_data[1]*mag_data[1])+(mag_data[2]*mag_data[2]))/3);
-                wait(0.01);
+            logDebug("\r\nPosting Accel Readings X: %f Y: %f  Z: %f \r\n",dataX,dataY,dataZ);
 
-                gyro.acquire_gyro_data_dps(gyro_data);
-                logDebug("gyro %4.2f,\t%4.2f,\t%4.2f\r\n",gyro_data[0],gyro_data[1],gyro_data[2]);
-                gyro_rms = sqrt(((gyro_data[0]*gyro_data[0])+(gyro_data[1]*gyro_data[1])+(gyro_data[2]*gyro_data[2]))/3);
-                wait(0.01);
+            logDebug("https://quickstart.internetofthings.ibmcloud.com");
+
+            //http_tx.clear();
 
-                logDebug("\r\nAccelerometer shock %f\r\n", accel_rms);
-                logDebug("Magnitometer max value vs 1.0 %f\r\n", mag_rms);
-                logDebug("Gyro RMS %f\r\n\n", gyro_rms);
-                wait(0.01);
-
-//                logDebug("https://quickstart.internetofthings.ibmcloud.com");
-//                logInfo("bringing up the link");
+            logInfo("bringing up the link");
+            if (! radio->connect()) {
+                logError("failed to bring up the link");
+                //return 0;
+            } else {
 
                 // HTTPClient object used for HTTP requests.
-//                HTTPClient http;
+                HTTPClient http;
 
                 // Enable strict certificate validation.
-//                http.setPeerVerification(VERIFY_PEER);
+                http.setPeerVerification(VERIFY_PEER);
 
                 // Load certificates defined in ssl_certificates.h.
                 // See comments in ssl_certificates.h for information on how to get and format root certificates.
-//                if (http.addRootCACertificate(ssl_certificates) != HTTP_OK)
-//                    logError("loading SSL certificates failed");
+                if (http.addRootCACertificate(ssl_certificates) != HTTP_OK)
+                    logError("loading SSL certificates failed");
 
-                // HTTP POST example - QUickstart
 
-//                char http_rx_buf[1024];
-//                char http_tx_buf[1024];
+                char http_rx_buf[1024];
+                char http_tx_buf[1024];
 
-//                logDebug("\r\nPosting Readings\r\n");
-//                memset(http_tx_buf, 0, sizeof(http_tx_buf));
-//                memset(http_rx_buf, 0, sizeof(http_rx_buf));
-//                snprintf(http_tx_buf, sizeof(http_tx_buf), "{ \"AccX\": \"%f\" , \"AccY\": \"%f\", \"Accz\": \"%f\" }", accel_data[0],accel_data[1],accel_data[2]);
-//                logDebug("%s",http_tx_buf);
-//                HTTPResult res;
+                memset(http_tx_buf, 0, sizeof(http_tx_buf));
+                memset(http_rx_buf, 0, sizeof(http_rx_buf));
+                snprintf(http_tx_buf, sizeof(http_tx_buf), "{ \"dataX\": \"%f\" , \"dataY\": \"%f\" ,\"dataZ\": \"%f\" }", dataX,dataY,dataZ);
+                logDebug("%s",http_tx_buf);
+                HTTPResult res;
 
                 // IHTTPDataIn object - will contain data received from server.
-//                HTTPText http_rx(http_rx_buf, sizeof(http_rx_buf));
+                HTTPText http_rx(http_rx_buf, sizeof(http_rx_buf));
 
                 // IHTTPDataOut object - contains data to be posted to server.
                 // HTTPJson automatically adds the JSON content-type header to the request.
-//                HTTPJson http_tx(http_tx_buf, strlen(http_tx_buf)+1);
+                HTTPJson http_tx(http_tx_buf, strlen(http_tx_buf)+1);
 
                 // Make a HTTP POST request to http://httpbin.org/
-//                res = http.post("http://quickstart.internetofthings.ibmcloud.com/api/v0002/device/types/dragonflytype/devices/dragonfly02/events/myEvent", http_tx, &http_rx);
-//                res = http.post("http://quickstart.internetofthings.ibmcloud.com/api/v0002/device/types/ TYPE VARIABLE /devices/ NAME VARIABLE /events/myEvent", http_tx, &http_rx);
-//              /*** there should be no spaces in the web site listed in above line ***/
-
-//                if (res != HTTP_OK)
-//                    logError("HTTPS POST to Bluemix failed [%d][%s]", res, httpResToStr(res));
-//                else
-//                    logInfo("HTTPS POST to Bluemix succeeded [%d]\r\n%s", http.getHTTPResponseCode(), http_rx_buf);
+                res = http.post("http://quickstart.internetofthings.ibmcloud.com/api/v0002/device/types/dragonflytype/devices/dragonfly22/events/myEvent", http_tx, &http_rx);
+//                res = http.post("http://quickstart.internetofthings.ibmcloud.com/api/v0002/device/types/dragonflytype/devices/ REPLACE WITH DEVICEID /events/myEvent", http_tx, &http_rx);
+                if (res != HTTP_OK)
+                    logError("HTTPS POST to Bluemix failed [%d][%s]", res, httpResToStr(res));
+                else
+                    logInfo("HTTPS POST to Bluemix succeeded [%d]\r\n%s", http.getHTTPResponseCode(), http_rx_buf);
 
                 //logInfo("finished - bringing down link");
-//                radio->disconnect();
+                //radio->disconnect();
                 post_timer.reset();
                 countingLoop +=1;
             }
@@ -280,16 +226,11 @@
         //return 0;
     }
     radio->disconnect();
-    timeStamp = loop_timer.read_ms();
+    timeStamp = post_timer.read_ms();
     logInfo("loop timer = %d", timeStamp);
     logInfo("\r\n\n\nEnd Of Line\r\n");
 }
 
-
-/***********************************************
-  *   below are the call routines
-/***********************************************/
-
 bool init_mtsas()
 {
     io = new mts::MTSSerialFlowControl(RADIO_TX, RADIO_RX, RADIO_RTS, RADIO_CTS);