Sample code for connecting u-blox c027 to AerCloud

Dependencies:   C027_Support_AerCloud HTTPClient_AerCloud mbed

Fork of HTTPClient_Cellular_HelloWorld by u-blox

main.cpp

Committer:
mchowla
Date:
2014-11-14
Revision:
14:fcdfdd37affe
Parent:
12:955439e7166f

File content as of revision 14:fcdfdd37affe:

// Copyright 2014 Aeris Communications Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
//  limitations under the License.

//  
// AerCloud sample code for the u-blox C027 board 
//  Details on the C027: http://developer.mbed.org/platforms/u-blox-C027/
//  Details on AerCloud: http://www.aeris.com/technology/aercloud/
//  AerCloud Developer Forum: https://developer.aeris.com/
//
// Sample writes latitude, longitude, altitude, speed & GPS time to an AerCloud container
//
// Dependencies:
//     mbed HTTP Client Libary
//     C027_Support Library
//     mbed Library
//
// To get the sample running, you'll need to fill in the following parameters below
//   Your cellular provider's APN: APN
//   AerCloud API Key: AC_APIKEY
//   AerCloud Account ID: acId
//   AerCloud Container: AC_CONTAINER
//
// and you'll also need to create an AerCloud contianer with the schema 
// described below
//

#include "mbed.h"
#include "HTTPClient.h"
#include "GPS.h"

#include "MDM.h"

//------------------------------------------------------------------------------------
// Connectivity Parameters
//------------------------------------------------------------------------------------

//! Aeris SIM does not use PIN
#define SIMPIN      NULL

//! The APN of your Aeris SIM
//    You can find the APN for your SIM at https://aerport.aeris.com
#define APN         "_INSERT_YOUR_APN_HERE_"

//! User name and password are not required to use Aeris APN
#define USERNAME    NULL

//! User name and password are not required to use Aeris APN
#define PASSWORD    NULL 


// ------------------------------------------------------------------------------------
// AerCloud Paramers
// ------------------------------------------------------------------------------------

// AerCloud BASE URL
#define AC_BASE     "http://api.aercloud.aeris.com/v1"

//! AerCloud API Key
//   You can find your api key at https://aerport.aeris.com"
#define AC_APIKEY "_INSERT_YOUR_AERCLOUD_API_KEY_HERE_"

//! Aercloud Account Id
//   You can find your account id at https://aerport.aeris.com
int acId = 1;

// AerCloud Container
//  The name of the AerCloud Container to write data into
#define AC_CONTAINER "C027_Sample"  // Example Container

//------------------------------------------------------------------------------------
// AerCloud SCL (Device) Data Model
// ------------------------------------------------------------------------------------
//
// Code assumes an AerCloud Data Model with the following fields
//
//   Altitude DOUBLE  GPS altitude
//   Speed DOUBLE     GPS speed
//   VSLat STRING     GPS latitude
//   VSLong STRING    GPS longitude
//   GPSTime DOUBLE   Raw GPS time
//   GPSDate DOUBLE   Raw GPS Date
//   SCLID INT        AerCloud Device Identifier (i.e. IMEI)
//

//------------------------------------------------------------------------------------

char str[512];
char simImei[16];

const char* HttpResultToString(HTTPResult r) {
    switch(r) {
        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 - 404";
        case HTTP_REFUSED:
            return "HTTP_REFUSED - 403";
        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_OK:
//            return "HTTP_OK";
    }
    
    return "UNKNOWN ERROR CODE";
} 

int main() 
{
    bool simProvisioned = false;
    int ret;
    char buf[512] = "";
    int itn = 580;
    const int wait = 100;
    double lastLat = 0, lastLong = 0, lastAlt = 0, lastSpeed = 0, lastTime = 0, lastDate = 0;
    bool abort = false;
    
    GPSI2C gps;

    printf("GPS object created\r\n");
    // turn on the supplies of the Modem
    MDMSerial mdm;
    printf("Modem object created\r\n");
    //mdm.setDebug(4); // enable this for debugging issues 
    if (!mdm.connect(SIMPIN, APN,USERNAME,PASSWORD)) {
        printf("Unabled to connect to the network.\r\n");
        return -1;
    }
    HTTPClient http;
  
    //get SIM IMEI
    mdm.getIMEI(simImei);
    printf("Requesting provision info for IMEI %s\r\n",simImei);
    
    // Check if SIM is provisioned in AerCloud
    printf("\r\nIs the SIM provisioned?  ");
    char url[512];
    snprintf(url, sizeof(url), "%s/%d/scls/%s?apiKey=%s", AC_BASE, acId, simImei, AC_APIKEY);
    ret = http.get(url, str, 128);
    if (ret == HTTP_OK)
    {
      // We're already provisioned
      printf("Yes\r\n");
      printf("Page fetched successfully - read %d characters\r\n", strlen(str));
      printf("Result: %s\r\n", str);
      simProvisioned = true;
    }
    else
    {
        printf("No\r\n");
        printf("Error - ret = %d - HTTP return code = %d\r\n", ret, http.getHTTPResponseCode());
        //SIM is not provisioned. trying to provision it...
        char url[512];
        snprintf(url, sizeof(url), "%s/%d/scls?apiKey=%s", AC_BASE, acId, AC_APIKEY);

        snprintf(str, sizeof(str), "{\"sclId\":\"%s\"}\0",simImei);
        HTTPText outText(str);
        HTTPText inText(str, 512);
        ret = http.post(url, outText, &inText);
        if (!ret)
        {
          printf("Executed POST successfully - read %d characters\r\n", strlen(str));
          printf("Result: %s\r\n", str);
          simProvisioned = true;
        }
        else
        {
          if(http.getHTTPResponseCode() == 200)
            simProvisioned = true;
          printf("Error - ret = %d - HTTP return code = %d\r\n", ret, http.getHTTPResponseCode());
        }      
    }
    
    //POST data to containers if SIM has been successfully provisioned
    if(simProvisioned)
    {
        //Read GPS    
        while (!abort) 
        {
            while ((ret = gps.getMessage(buf, sizeof(buf))) > 0)
            {
                int len = LENGTH(ret);
                if ((PROTOCOL(ret) == GPSParser::NMEA) && (len > 6))
                {
                    if (!strncmp("$GPGLL", buf, 6)) 
                    {
                        //Get Lat/Long
                        double la = 0, lo = 0;
                        char ch;
                        if (gps.getNmeaAngle(1,buf,len,la) && 
                            gps.getNmeaAngle(3,buf,len,lo) && 
                            gps.getNmeaItem(6,buf,len,ch) && ch == 'A')
                        {
                            lastLat = la;
                            lastLong = lo;
                        }
                    } 
                    else if (!strncmp("$GPGGA", buf, 6)) 
                    {
                        //Get Altitude
                        double a = 0; 
                        if (gps.getNmeaItem(9,buf,len,a)) // altitude msl [m]
                        {
                            lastAlt = a;
                        }
                    } 
                    else if (!strncmp("$GPVTG", buf, 6)) 
                    {
                        //Get Speed
                        double s = 0; 
                        if (gps.getNmeaItem(7,buf,len,s)) // speed [km/h]
                        {
                            lastSpeed = s;
                        }   
                    }
                    else if (!strncmp("$GPRMC", buf, 6))
                    {
                        //Get Timestamp
                        double fixTime = 0;
                        double fixDate = 0;
                         
                        if (gps.getNmeaItem(1,buf,len,fixTime)) // speed [km/h]
                        {
                            lastTime = fixTime;
                        }
                        if (gps.getNmeaItem(9,buf,len,fixDate)) // speed [km/h]
                        {
                            lastDate = fixDate;
                        }
 //                       printf("time: %f\n Date:%f\n", lastTime, lastDate);
                    }
                }
            }    
            wait_ms(wait); 
            itn++;
            //post every 60 seconds
            if(itn == 590)
            {
                 // POST data to AerCLoud
                char url[512];
                snprintf(url, sizeof(url), "%s/%d/scls/%s/containers/%s/contentInstances?apiKey=%s", AC_BASE, acId, simImei, AC_CONTAINER, AC_APIKEY);
            
                sprintf(str,"{\"VSLat\": %.5f, \"VSLong\":  %.5f, \"Altitude\": %.5f, \"Speed\":%.5f, \"GPSTime\":%.5f, \"GPSDate\":%.5f, \"SCLID\":\"%s\"}", lastLat, lastLong, lastAlt, lastSpeed, lastTime, lastDate, simImei);
                HTTPText outText(str);
                HTTPText inText(str, 512);
                printf("\r\nPost acquired data...\r\n");
                ret = http.post(url, outText, &inText);
                if (ret == HTTP_OK)
                {
                  printf("Executed POST successfully - read %d characters\r\n", strlen(str));
                  printf("Result: %s\r\n", str);
                }
                else
                {
                  printf("Error - ret = %d (%s), - HTTP return code = %d\r\n", ret, HttpResultToString((HTTPResult)ret), http.getHTTPResponseCode());
                }
                itn = 0;
            }        
        }
        gps.powerOff();        
    } else {
        printf("SIM is not provisioned.\r\n");
    }
    

    mdm.disconnect();
    mdm.powerOff();

    return 0;
}