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

main.cpp

Committer:
BlueShadow
Date:
2016-08-23
Revision:
5:dbedb2422089
Parent:
4:d16e07588838
Child:
6:8f1ad9d2193e

File content as of revision 5:dbedb2422089:

/* 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
 *
 * Configures the Sensor board for Ambient Light, cellular radio, brings up the cellular link,
 * and does HTTPS POST requests.
 * To do HTTPS requests with a certain server, the root certificate used to validate that server's certificate must be installed. See ssl_certificates.h for information on how to get the proper root certificate.
 *
 *
  *
 * The following hardware is required to successfully run this program:
 *   - 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,
 *
 * What this program does:
 *   - reads data from all sensors
 *   - 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
 *
 * Setup:
 *   - Correctly insert SIM card into Dragonfly
 *   - Seat the Dragonfly on the UDK2 board
 *   - Connect an antenna to the connector on the Dragonfly labled "M"
 *   - Stack the Base Shield on the UDK2 Arduino headers
 *   - Stack the MEMs board on top of the Base Shield
 *   - Plug in the power cable
 *   - Plug a micro USB cable into the port below and slightly to the
 *     left of the Dragonfly (NOT the port on the Dragonfly)
 *
 * Go have fun and make something cool!
 *
 ************************************************************************/
/*
 * 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.
 */

#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

//-------- Customise these values -----------

#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 --------


//*****************************************************************************************************************************************************
DigitalOut Led1Out(LED1);

DigitalOut bc_nce(PB_2);

bool init_mtsas();
char* httpResToStr(HTTPResult res);

// The MTSSerialFlowControl object represents the physical serial link between the processor and the cellular radio.
mts::MTSSerialFlowControl* io;
// The Cellular object represents the cellular radio.
mts::Cellular* radio;

// An APN is required for GSM radios.
static const char apn[] = "iot.aer.net";

bool radio_ok = false;

//Define Pins for I2C Interface
I2C i2c(I2C_SDA, I2C_SCL);
bool        RepStart = true;
bool        NoRepStart = false;

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;

    logDebug("Begin Data Acquisition from FXOS8700 and FXAS21002....\r\n\r\n");

    static int post_interval_ms = 10000; //************* it was 30000, I don't want to wait 30 seconds ************************/



    //Sets the log level to INFO, higher log levels produce more log output.
    //Possible levels: NONE, FATAL, ERROR, WARNING, INFO, DEBUG, TRACE
    mts::MTSLog::setLogLevel(mts::MTSLog::TRACE_LEVEL);


//****************************************************************************************************/
// Initialization Radio Section **********************************************************
//****************************************************************************************************/
    logInfo("initializing cellular radio");
    radio_ok = init_mtsas();
    if (! radio_ok) {
        while (true) {
            logError("failed to initialize cellular radio");
            wait(1);
        }
    }

    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 {

        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);

                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);

                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("\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");

                // 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");

                // HTTP POST example - QUickstart

//                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;

                // IHTTPDataIn object - will contain data received from server.
//                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);

                // 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);

                //logInfo("finished - bringing down link");
//                radio->disconnect();
                post_timer.reset();
                countingLoop +=1;
            }
        }

        //return 0;
    }
    radio->disconnect();
    timeStamp = loop_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);
    if (! io)
        return false;

    // radio default baud rate is 115200
    io->baud(115200);
    radio = mts::CellularFactory::create(io);
    if (! radio)
        return false;

    // Transport must be set properly before any TCPSocketConnection or UDPSocket objects are created
    Transport::setTransport(radio);

    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";
    }
}