No Description

Dependencies:   mbed mtsas picojson

Fork of Dragonfly_Cellular_HTTP_Example by MultiTech

main.cpp

Committer:
dabraham
Date:
2017-08-29
Revision:
3:c6a13980819b
Parent:
2:e8fe29290fc1

File content as of revision 3:c6a13980819b:

/** Dragonfly Cellular HTTP Example
 * Configures the cellular radio, brings up the cellular link, and does HTTP GET and POST requests.
 *
 * NOTE: This example changes the baud rate of the debug port to 115200 baud!
 */

#include "mbed.h"
#include "mtsas.h"
#include "picojson.h"
//#include "Cellular.h"
#include "MTSLog.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <sstream>

// 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();
char* httpResToStr(HTTPResult res);
string id="1";
int interval;

// 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[] = "rogers-core-appl1.apn";

bool radio_ok = false;

int main() {
    while(true){
    // 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(9600);
    
    //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::INFO_LEVEL);
    
    logInfo("initializing cellular radio");
    radio_ok = init_mtsas();
    if (! radio_ok) {
        while (true) {
            logError("failed to initialize cellular radio");
            wait(1);
        }
    }
    
    logInfo("setting APN");
    if (radio->setApn(apn) != MTS_SUCCESS)
        logError("failed to set APN to \"%s\"", apn);
        
    logInfo("bringing up the link");
    if (! radio->connect()) {
        logError("failed to bring up the link");
    } else {
        string imei = radio->getEquipmentIdentifier();
        logInfo("The IMEI is \r\n%s", imei);
        // HTTPClient object used for HTTP requests.
        HTTPClient http;
        
        // HTTP GET example.
        {
            char http_rx_buf[1024];
            HTTPResult res;
            
            // IHTTPDataIn object - will contain data received from server.
            HTTPText http_rx(http_rx_buf, sizeof(http_rx_buf));
            
            // Make a HTTP GET request to http://httpbin.org/
            string url = "http://locationtracker-env.fu8xgvitxi.ca-central-1.elasticbeanstalk.com/GetDevice/" + id;
            const char *URL = url.c_str();
            res = http.get(URL, &http_rx);
            if (res != HTTP_OK)
                logError("HTTP GET failed [%d][%s]", res, httpResToStr(res));
            else{
                logInfo("HTTP GET succeeded [%d]\r\n%s", http.getHTTPResponseCode(), http_rx_buf);
                string resStr(http_rx_buf);
                logInfo("The received responce is \r\n%s", resStr);
                
                picojson::value responseValue;
                const char *jsonResponse = resStr.c_str(); 
                string json = picojson::parse(responseValue, jsonResponse, jsonResponse + strlen(jsonResponse));
                logInfo("The received responce is =%s\r\n%s", json.c_str());
                //printf("res error? %s\r\n", err.c_str());
                logInfo("device_serial =%s\r\n" ,  responseValue.get("device_serial").get<string>().c_str());
                //printf("number =%f\r\n" ,  responseValue.get("number").get<double>());
                //printf("integer =%d\r\n" ,  (int)v.get("integer").get<double>());
                interval = (int)responseValue.get("tracking_interval").get<double>() * 60;
            }
        }
        
        
        // HTTP POST example.
        {
            char http_rx_buf[1024];
            HTTPResult res;
            
            // Enable GPS
    radio->GPSenable();
    
    // Get GPS position
        Cellular::gpsData gps_data = radio->GPSgetPosition();        
        bool gps_success = gps_data.success;
        string latitude = gps_data.latitude;
        string longitude = gps_data.longitude;
        float hdop = gps_data.hdop;
        float altitude = gps_data.altitude;
        float fix = gps_data.fix;
        string cog = gps_data.cog;
        float kmhr = gps_data.kmhr;
        float knots = gps_data.knots;
        string timestamp = gps_data.timestamp;
        string battery_percentage = "50";
        string device_id = "1";
        string device_serial = "MTQ-01";
        
        stringstream ss;
        ss << gps_data.satellites;
        string satellites = ss.str();
                
        if(gps_success == true){
            picojson::object gps_attributes;

            gps_attributes["latitude"] = picojson::value(latitude);
            gps_attributes["longitude"] = picojson::value(longitude);
            gps_attributes["hdop"] = picojson::value(hdop);
            gps_attributes["altitude"] = picojson::value(altitude);
            gps_attributes["fix"] = picojson::value(fix);
            gps_attributes["cog"] = picojson::value(cog);
            gps_attributes["kmhr"] = picojson::value(kmhr);
            gps_attributes["knots"] = picojson::value(knots);
            gps_attributes["satellites"] = picojson::value(satellites);
            gps_attributes["time_stamp"] = picojson::value(timestamp);
            gps_attributes["battery_percentage"] = picojson::value(battery_percentage);
            gps_attributes["device_id"] = picojson::value(device_id);
            gps_attributes["device_serial"] = picojson::value(device_serial);
                        
            const char *GPSJSONString = picojson::value(gps_attributes).serialize().c_str();   // serialize the json_msg and convert the string result to char* using c_str()
            logInfo("The current JSON value is %s", GPSJSONString);
            
            char http_tx_buf[1024];
            strcpy(http_tx_buf, GPSJSONString); // convert the char* result(GPSJSONString) to char[](http_tx_buf)
            
            // 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, sizeof(http_tx_buf));            
            
            // Make a HTTP POST request to http://httpbin.org/
            res = http.post("http://locationtracker-env.fu8xgvitxi.ca-central-1.elasticbeanstalk.com/PostGPS", http_tx, &http_rx);
            if (res != HTTP_OK)
                logError("HTTP POST failed [%d][%s]", res, httpResToStr(res));
            else
                logInfo("HTTP POST succeeded [%d]\r\n%s", http.getHTTPResponseCode(), http_rx_buf);
            
        }
        else{
            logInfo("GPS Location failed");
        }                                                                                                            
    }                                                           
    }
    
    logInfo("finished - bringing down link");
    radio->GPSdisable();
    radio->disconnect();
    wait(interval);
}    
    return 0;
}


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