Example of using the Dragonfly HTTP library with the m2x http api

Dependencies:   MbedJSONValue X_NUCLEO_IKS01A1 mbed mtsas_lat3

Fork of VVV_MultiTech_Dragonfly_ATT_Dallas by Paul Jaeger

Revision:
10:65b7d33f18d9
Parent:
9:3dcbe04adfd0
Child:
12:493eba0c12c7
--- a/main.cpp	Tue Aug 23 08:08:39 2016 +0000
+++ b/main.cpp	Tue Sep 26 04:53:17 2017 +0000
@@ -7,8 +7,11 @@
 #include "MbedJSONValue.h"
 #include "HTTPJson.h"
 #include <string>
-#include "FXAS21002.h"
-#include "FXOS8700.h"
+#include <sstream>
+#include "x_nucleo_iks01a1.h"
+
+#define HTTP_RX_BUFFER_SIZE 1024
+char http_rx_buf[HTTP_RX_BUFFER_SIZE];
 
 // Debug serial port
 static Serial debug(USBTX, USBRX);
@@ -21,20 +24,40 @@
 
 // APN associated with SIM card
 // this APN should work for the AT&T SIM that came with your Dragonfly
-static const std::string apn = "";
+static const std::string apn = "broadband";
 
 // Phone number to send SMS messages to
 // just change the x digits - the 1 needs to stay!
-static const std::string phone_number = " NEED A NUMBER with a 1";
+static const std::string phone_number = "18594335160"; //" NEED A NUMBER with a 1";
+
+// Keys needed by the m2x API
+// see more details here: https://m2x.att.com/developer/documentation/v2/overview
+// m2x device ID
+static const std::string m2x_device_id = "e47069be38f20e5d2ca885d21aaa74c8";
+
+// M2X primary API key
+static const std::string m2x_api_key = "db8e88f58b405811ad5340a9590b5d69";
 
-FXOS8700 accel(D14,D15);
-FXOS8700 mag(D14,D15);
-FXAS21002 gyro(D14,D15);
+/* Instantiate the expansion board */
+static X_NUCLEO_IKS01A1 *mems_expansion_board = X_NUCLEO_IKS01A1::Instance(I2C_SDA, I2C_SCL);
+
+/* Retrieve the composing elements of the expansion board */
+static GyroSensor *gyroscope = mems_expansion_board->GetGyroscope();
+static MotionSensor *accelerometer = mems_expansion_board->GetAccelerometer();
+static MagneticSensor *magnetometer = mems_expansion_board->magnetometer;
+static HumiditySensor *humidity_sensor = mems_expansion_board->ht_sensor;
+static PressureSensor *pressure_sensor = mems_expansion_board->pt_sensor;
+static TempSensor *temp_sensor1 = mems_expansion_board->ht_sensor;
+static TempSensor *temp_sensor2 = mems_expansion_board->pt_sensor;
 
 // variables for sensor data
 char streamAcc[] = "acc_rms";
 char streamMag[] = "mag_rms";
 char streamGyr[] = "gyr_rms";
+char streamTemp[] = "temp_c";
+char streamPres[] = "pressure";
+char streamHum[] = "humidity";
+char streamAccel[] = "accel";
 
 // misc variables
 static int sms_interval_ms = 60000;
@@ -48,6 +71,7 @@
 // function prototypes
  ****************************************************************************************************/
 bool init_mtsas();
+char* httpResToStr(HTTPResult res);
 
 /****************************************************************************************************
 // main
@@ -61,13 +85,18 @@
     /****************************************************************************************************
           Initialize I2C Devices ************
      ****************************************************************************************************/
-    accel.accel_config();
-    mag.mag_config();
-    gyro.gyro_config();
 
-    float accel_data[3];
+    int32_t accel_data[3];
+    float accel_sensitivity;
     //float mag_data[3];
     //float gyro_data[3];
+    
+    float dataX = 0.0f;
+    float dataY = 0.0f;
+    float dataZ = 1.0f;
+    float humidity = 0.0f;
+    float temperature = 0.0f;
+    float pressure = 0.0f;
 
 // Initialization Radio Section **********************************************************
 
@@ -78,9 +107,7 @@
         logInfo("MTSAS is ok");
 
 //End Radio Initialization Section **********************************************************
-    float dataX = 0;
-    float dataY = 0;
-    float dataZ = 1;
+
     Timer sms_timer;
     sms_timer.start();
     Timer read_timer;
@@ -89,24 +116,71 @@
     print_timer.start();
     Timer motion_timer;
     motion_timer.start();
+    
+// http object initialization
+    // HTTPClient object used for HTTP requests.
+    HTTPClient http;
+    
+    // Enable strict certificate validation.
+    // 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");
 
     while (true) {
         if (read_timer.read_ms() > read_interval_ms) {
 
-            accel.acquire_accel_data_g(accel_data);
-            dataX = accel_data[0];
-            dataY = accel_data[1];
-            dataZ = accel_data[2];
-
+            accelerometer->get_x_axes(accel_data);
+            accelerometer->get_x_sensitivity(&accel_sensitivity);
+            dataX = accel_data[0] * accel_sensitivity;
+            dataY = accel_data[1] * accel_sensitivity;
+            dataZ = accel_data[2] * accel_sensitivity;
+            humidity_sensor->get_humidity(&humidity);
+            temp_sensor1->get_temperature(&temperature);
+            pressure_sensor->get_pressure(&pressure);
             read_timer.reset();
         }
-
+// send to m2x on same interval as printing
         if (print_timer.read_ms() > print_interval_ms) {
 
             logDebug("SENSOR DATA");
             logDebug("DataZ  %0.3f", dataZ);
             logDebug("DataY  %0.3f", dataY);
+            logDebug("DataX  %0.3f", dataX);
+            logDebug("Humidity: %0.2f", humidity);
+            logDebug("Temperature: %0.1f", temperature);
+            logDebug("Presure: %f", pressure);
+            
+            HTTPResult res;
+            // IHTTPDataIn object - will contain data received from server.
+            HTTPText http_rx(http_rx_buf, HTTP_RX_BUFFER_SIZE);
+            
+            std::ostringstream json_packet;
+            json_packet << "{\"values\": {\"value\" : " \
+                    << temperature << "}}";
+            
+            // IHTTPDataOut object - contains data to be posted to server.
+            // HTTPJson automatically adds the JSON content-type header to the request.
+            char *tx_string = new char[json_packet.str().length()];
+            sprintf(tx_string, json_packet.str().c_str());
+            HTTPJson http_tx(tx_string, json_packet.str().length());
+            std::string m2x_header = "X-M2X-KEY: " + m2x_api_key + "\r\n";
+            std::string url = "https://api-m2x.att.com/v2/devices/" + \
+                                m2x_device_id + \
+                                "/streams/temperature/values";
+            http.setHeader(m2x_header.c_str());
+            
+            http.post(url.c_str(), http_tx, &http_rx);
+            delete tx_string;
+            if (res != HTTP_OK)
+                logError("HTTPS POST failed [%d][%s]", res, httpResToStr(res));
+            else
+                logInfo("HTTPS POST succeeded [%d]\r\n%s", http.getHTTPResponseCode(), http_rx_buf);
+            
             print_timer.reset();
+            
         }
 
 // SMS
@@ -155,3 +229,34 @@
 
     return true;
 }
+
+char* httpResToStr(HTTPResult res) {
+    switch(res) {
+        case HTTP_PROCESSING:
+            return "HTTP_PROCESSING";
+        case HTTP_PARSE:
+            return "HTTP_PARSE";
+        case HTTP_DNS:
+            return "HTTP_DNS";
+        case HTTP_PRTCL:
+            return "HTTP_PRTCL";
+        case HTTP_NOTFOUND:
+            return "HTTP_NOTFOUND";
+        case HTTP_REFUSED:
+            return "HTTP_REFUSED";
+        case HTTP_ERROR:
+            return "HTTP_ERROR";
+        case HTTP_TIMEOUT:
+            return "HTTP_TIMEOUT";
+        case HTTP_CONN:
+            return "HTTP_CONN";
+        case HTTP_CLOSED:
+            return "HTTP_CLOSED";
+        case HTTP_REDIRECT:
+            return "HTTP_REDIRECT";
+        case HTTP_OK:
+            return "HTTP_OK";
+        default:
+            return "HTTP Result unknown";
+    }
+}