t3

Dependencies:   C027_Support

Fork of C027_SupportTest by u-blox

main.cpp

Committer:
PetriI2
Date:
2017-01-09
Revision:
36:50511f65f5a0
Parent:
35:ead6b88cebeb

File content as of revision 36:50511f65f5a0:

#include "mbed.h"

//------------------------------------------------------------------------------------
/* This example was tested on C027-U20 and C027-G35 with the on board modem. 
   
   Additionally it was tested with a shield where the SARA-G350/U260/U270 RX/TX/PWRON 
   is connected to D0/D1/D4 and the GPS SCL/SDA is connected D15/D15. In this 
   configuration the following platforms were tested (it is likely that others 
   will work as well)
   - U-BLOX:    C027-G35, C027-U20, C027-C20 (for shield set define C027_FORCE_SHIELD)
   - NXP:       LPC1549v2, LPC4088qsb
   - Freescale: FRDM-KL05Z, FRDM-KL25Z, FRDM-KL46Z, FRDM-K64F
   - STM:       NUCLEO-F401RE, NUCLEO-F030R8
                mount resistors SB13/14 1k, SB62/63 0R
*/
#include "GPS.h"
#include "MDM.h"
//------------------------------------------------------------------------------------
// You need to configure these cellular modem / SIM parameters.
// These parameters are ignored for LISA-C200 variants and can be left NULL.
//------------------------------------------------------------------------------------
//! Set your secret SIM pin here (e.g. "1234"). Check your SIM manual.
#define SIMPIN      "1234"
/*! The APN of your network operator SIM, sometimes it is "internet" check your 
    contract with the network operator. You can also try to look-up your settings in 
    google: https://www.google.de/search?q=APN+list */
#define APN         "internet"
//! Set the user name for your APN, or NULL if not needed
#define USERNAME    "dna"
//! Set the password for your APN, or NULL if not needed
#define PASSWORD    "internet" 
//------------------------------------------------------------------------------------

//#define CELLOCATE

AnalogIn temperature(A5);
DigitalOut led1(LED1);

DigitalOut ledD1(D10); //inverted
DigitalOut ledD9(D11); //inverted
DigitalOut ledD2(D12);
DigitalOut ledD3(D13);
DigitalOut ledD11(D9); //inverted

DigitalIn S1(D5);
DigitalIn S2(D3);
DigitalIn S3(D7);
DigitalIn S4(D8);
DigitalIn S5(D2);

DigitalIn A(D4);
DigitalIn B(D6);

/*another thread to read IOs*/ 
void btn_thread(void const *args) {
   
   //d4.mode(PullUp);
   
    while(true) {

        if(S1 == 1) {
            //printf("S1 OFF\r\n");
            ledD11 = 1;
        }
        else {
            //printf("S1 ON\r\n");
            ledD11 = 0;
        }

        if(S2 == 0) {
            printf("Down\r\n");
        }

        if(S3 == 0) {
            printf("Right\r\n");
        }

        if(S4 == 0) {
            printf("Up\r\n");
        }
        
        if(S5 == 0) {
            printf("Left\r\n");
        }
                
        if(A == 0) {
            ledD3 = 0;
        }
        else {
            ledD3=1;
        }
        
        if(B == 0) {
            printf("b0\r\n");
        }
            
        wait(1);
    }
}

int main(void)
{
    int ret;
#ifdef LARGE_DATA
    char buf[2048] = "";
#else
    char buf[512] = "";
#endif

    char buffer[500];
    char csrfMiddleware[40]={0};
    char csrfMiddleware2[50]={0};
    char* buff; 

    unsigned int macAddr[6] = {0x00,0x1d,0xc9,0x1b,0x94,0x3d};
    int tlsData[256];
    unsigned int TLSdata[2] = {1000,2000};
    float lat=65.3256, lon=27.462;
    unsigned int dataLen=0;
    int contentLenStr[10];
    int len=0, opcode=0, sleepTime=0;
    char a[2];
    char http_cmd[700] = {""};
    
    double la = 0, lo = 0;
    bool mdmOk;
    
    
    /*start another thread to read IOs*/    
    Thread thread(btn_thread);
    
    //Set all leds ON
    ledD1 = 0;
    ledD9 = 0;
    ledD2 = 0; 
    ledD3 = 0; 
    ledD11 = 0; 

    wait(2); //5s

    printf("Temperature1: %f \r\n", temperature.read());
    printf("Temperature2: %3.3f \r\n", temperature.read()*100.0f);
    led1 = (temperature > 0.5f) ? 1 : 0;
    
    printf("Voltage1: 0x%04X \r\n", temperature.read_u16());
    printf("Voltage2: %f \r\n", temperature.read_u16()*(3.3/65536));
    //float voltage = (f*(3.3/4096.0));
    
    //Set all leds OFF
    ledD1 = ~ledD1;
    ledD9 = ~ledD9;
    ledD2 = ~ledD2; 
    ledD3 = ~ledD3; 
    ledD11 = ~ledD11; 
    

    // Create the GPS object
#if 1   // use GPSI2C class
    GPSI2C gps;
#else   // or GPSSerial class 
    GPSSerial gps; 
#endif
    // Create the modem object
    MDMSerial mdm; // use mdm(D1,D0) if you connect the cellular shield to a C027
//    mdm.setDebug(4); // enable this for debugging issues 
//    mdm.setDebug(1); // enable this for debugging issues 
    // initialize the modem 
    MDMParser::DevStatus devStatus = {};
    MDMParser::NetStatus netStatus = {};
         
    do {
        mdmOk = mdm.init(SIMPIN, &devStatus);
        wait(5);
        mdm.dumpDevStatus(&devStatus);
     
        printf("mdmOk status=%d\r\n", mdmOk);
        //wait(2);
    }while (!mdmOk);
    
    if (mdmOk) {
        // wait until we are connected
        mdmOk = mdm.registerNet(&netStatus);
        mdm.dumpNetStatus(&netStatus);
    }
    if (mdmOk)
    {
        ledD1 = 0;
        // join the internet connection 
        MDMParser::IP ip = mdm.join(APN,USERNAME,PASSWORD);
        if (ip == NOIP)
            printf("Not able to join network");
        else
        {
            mdm.dumpIp(ip);
            printf("Make a Http Post Request\r\n");
            int socket = mdm.socketSocket(MDMParser::IPPROTO_TCP);
            printf("Socket created: %d\r\n", socket);
            if (socket >= 0)
            {
                mdm.socketSetBlocking(socket, 10000);                
                //if (mdm.socketConnect(socket, "mbed.org", 80))
                if (mdm.socketConnect(socket, "212.116.37.180", 81))
                {
                    //const char http[] = "GET /media/uploads/mbed_official/hello.txt HTTP/1.0\r\n\r\n";
                    //mdm.socketSend(socket, http, sizeof(http)-1);
                    
                    char http_cmdg[100] = "GET /cloudmgr/sensor/data/";
                    strcat(http_cmdg, " HTTP/1.1");
                    strcat(http_cmdg, "\r\n");
                    strcat(http_cmdg, "Connection: keep-alive");
                    strcat(http_cmdg, "\r\n");    
                    strcat(http_cmdg, "Host: 212.116.37.180:81");    
                    strcat(http_cmdg, "\r\n\r\n");
                    strcat(http_cmdg, "\0");
                    int leng = strlen(http_cmdg);
                    printf("Sending %d chars to server:\r\n%s\r\n", leng, http_cmdg);
                    //sock.send_all(http_cmdg, leng);
                    mdm.socketSend(socket, http_cmdg, leng);
                
                    ret = mdm.socketRecv(socket, buffer, sizeof(buffer)-1);
                    if (ret > 0) {
                        buffer[ret] = '\0';
                        printf("Socket Recv \"%*s\"\r\n", ret, buffer);
                        if(ret > 100) {
                            buff=strstr(buffer, "csrftoken=");
                            strncpy(csrfMiddleware, &buff[10], 32); 
                            strncpy(csrfMiddleware2, &buff[0], 42); 
                            printf("Received csrfMiddleware= %s\r\n", csrfMiddleware);
                            printf("Received csrfMiddleware2= %s\r\n", csrfMiddleware2);
                            //break;
                        }
                    }
                    
                    /*Prepare data to send to server*/
                    printf("Prepare to POST\r\n");                    
                    sprintf((char *)tlsData, "csrfmiddlewaretoken=%s&serial=%x%x%x%x%x%x&value=%d&gpslat=%f&gpslon=%f",
                        csrfMiddleware, macAddr[0],macAddr[1],macAddr[2],macAddr[3],macAddr[4],macAddr[5], 4096-TLSdata[1], lat, lon); //req_value for POST
                          
                    dataLen = strlen((char const*)tlsData);
                    sprintf((char *)&contentLenStr[0],"%d", dataLen);                    
                    memset(buffer, 0, sizeof(buffer));
                        
                    /*Send a POST message to server*/
                    //char http_cmd[700] = "POST /cloudmgr/sensor/data/";
                    strcat(http_cmd, "POST /cloudmgr/sensor/data/");
                    strcat(http_cmd, " HTTP/1.1");
                    strcat(http_cmd, "\r\n");    
                    strcat(http_cmd, "Connection: keep-alive");    
                    strcat(http_cmd, "\r\n"); 
                    strcat(http_cmd, "Host: 212.116.37.180:81");  
                    strcat(http_cmd, "\r\n");   
                    strcat(http_cmd, "Content-Type: application/x-www-form-urlencoded");
                    strcat(http_cmd, "\r\n"); 
                    strcat(http_cmd, "Content-Length: ");
                    strcat(http_cmd, (char const*)contentLenStr);
                    strcat(http_cmd, "\r\n");
                    strcat(http_cmd, "Cookie: ");
                    strcat(http_cmd, csrfMiddleware2);
                    strcat(http_cmd, "\r\n\r\n");
                    strcat(http_cmd, (char const*)tlsData);
                    strcat(http_cmd, "\0");
                    len = strlen(http_cmd);
                    printf("Sending %d chars to server:\n%s\r\n", len, http_cmd);
                    //sock.send_all(http_cmd, len);
                    mdm.socketSend(socket, http_cmd, len);
                    ret=1;    
                    
                    /*reveive answer message (sleeptime) from server*/      
                    while (true) {
                        ret = mdm.socketRecv(socket, buffer, sizeof(buffer)-1);
                        if (ret <= 0) {
                            printf("Received %d chars from server:\r\n%s\r\n", ret, buffer);
                            break;
                        }
                        buffer[ret] = '\0';
                    
                        printf("Received %d chars from server:\r\n%s\r\n", ret, buffer);
                        
                        if((strncmp((char const*)buffer, "200", 3))) {
                            strncpy(a, &buffer[ret-1], 1); 
                            opcode = atoi(a);
                            //printf("Received opcode= %d, %s\r\n", opcode, a);
                            switch (opcode) {
                                case 1 :
                                  sleepTime = 5;
                                  break;              
                                case 2 :
                                  sleepTime = 30;
                                  break;
                                case 3 :
                                  sleepTime = 300;
                                  break;
                                default :
                                  sleepTime = 5;
                                  break; 
                            }
                            printf("Received sleeptime= %d\r\n", sleepTime);
                            break;
                            
                        }
                        else {
                            break;
                        }
                    }    
                        
                    mdm.socketClose(socket);
                }
                mdm.socketFree(socket);
            }
            // disconnect  
            mdm.disconnect();
            ledD1 = ~ledD1;
        }
            
    }


 
    printf("SMS and GPS Loop\r\n");
    char link[128] = "";
    unsigned int i = 0xFFFFFFFF;
    const int wait = 100;
    bool abort = false;

    //DigitalOut led(LED1);
    while (!abort) {
        //printf("GPS Loop Start\r\n");
    //    led = !led;
#ifndef CELLOCATE
        while ((ret = gps.getMessage(buf, sizeof(buf))) > 0)
        {
            ledD9 = 0;
            int len = LENGTH(ret);
            //printf("GPS len: %d\r\n", len); 
            //printf("NMEA: %.*s\r\n", len-2, msg); 
            if ((PROTOCOL(ret) == GPSParser::NMEA) && (len > 6))
            {
                //printf("GPS len: %s\r\n", buf); 
                // talker is $GA=Galileo $GB=Beidou $GL=Glonass $GN=Combined $GP=GPS
                if ((buf[0] == '$') || buf[1] == 'G') {
                    #define _CHECK_TALKER(s) ((buf[3] == s[0]) && (buf[4] == s[1]) && (buf[5] == s[2]))
                    if (_CHECK_TALKER("GLL")) {
                        
                        char ch;
                        if (gps.getNmeaAngle(1,buf,len,la) && 
                            gps.getNmeaAngle(3,buf,len,lo) && 
                            gps.getNmeaItem(6,buf,len,ch) && ch == 'A')
                        {
                            printf("GPS Location: %.5f %.5f\r\n", la, lo); 
                            sprintf(link, "I am here!\n"
                                          "https://maps.google.com/?q=%.5f,%.5f", la, lo); 
                        }
                    } else if (_CHECK_TALKER("GGA") || _CHECK_TALKER("GNS") ) {
                        double a = 0; 
                        if (gps.getNmeaItem(9,buf,len,a)) // altitude msl [m]
                            printf("GPS Altitude: %.1f\r\n", a); 
                    } else if (_CHECK_TALKER("VTG")) {
                        double s = 0; 
                        if (gps.getNmeaItem(7,buf,len,s)) // speed [km/h]
                            printf("GPS Speed: %.1f\r\n", s); 
                    }
                }
            }
            ledD9 = ~ledD9;
        }
#endif        
    
        if (mdmOk && (i++ == 5000/wait)) {
            i = 0;
            ledD2 = 0;
            
            // check the network status
            if (mdm.checkNetStatus(&netStatus)) {
                mdm.dumpNetStatus(&netStatus, fprintf, stdout);
            }
                

            printf("Voltage A5: %f \r\n", temperature.read_u16()*(3.3/65536));
            led1 = (temperature > 0.5f) ? 1 : 0;

            
            if (mdmOk)
            {
                // join the internet connection 
                MDMParser::IP ip = mdm.join(APN,USERNAME,PASSWORD);
                if (ip == NOIP)
                    printf("Not able to join network");
                else
                {
                    ledD1 = 0;
                    mdm.dumpIp(ip);
                    printf("Make a Http Post Request\r\n");
                    int socket = mdm.socketSocket(MDMParser::IPPROTO_TCP);
                    printf("Socket created: %d\r\n", socket);
                    if (socket >= 0)
                    {
                        mdm.socketSetBlocking(socket, 10000);                
                        //if (mdm.socketConnect(socket, "mbed.org", 80))
                        if (mdm.socketConnect(socket, "212.116.37.180", 81))
                        {
                           
                            printf("Prepare to POST\r\n");                    
                            sprintf((char *)tlsData, "csrfmiddlewaretoken=%s&serial=%x%x%x%x%x%x&value=%d&gpslat=%f&gpslon=%f",
                                csrfMiddleware, macAddr[0],macAddr[1],macAddr[2],macAddr[3],macAddr[4],macAddr[5], 65536-temperature.read_u16(), la, lo); //req_value for POST
                                  
                            dataLen = strlen((char const*)tlsData);
                            sprintf((char *)&contentLenStr[0],"%d", dataLen);                    
                            memset(buffer, 0, sizeof(buffer));
                            memset(http_cmd, 0, sizeof(http_cmd));
                                
                            /*Send a POST message to server*/                            
                            strcat(http_cmd, "POST /cloudmgr/sensor/data/");
                            strcat(http_cmd, " HTTP/1.1");
                            strcat(http_cmd, "\r\n");    
                            strcat(http_cmd, "Connection: keep-alive");    
                            strcat(http_cmd, "\r\n"); 
                            strcat(http_cmd, "Host: 212.116.37.180:81");  
                            strcat(http_cmd, "\r\n");   
                            strcat(http_cmd, "Content-Type: application/x-www-form-urlencoded");
                            strcat(http_cmd, "\r\n"); 
                            strcat(http_cmd, "Content-Length: ");
                            strcat(http_cmd, (char const*)contentLenStr);
                            strcat(http_cmd, "\r\n");
                            strcat(http_cmd, "Cookie: ");
                            strcat(http_cmd, csrfMiddleware2);
                            strcat(http_cmd, "\r\n\r\n");
                            strcat(http_cmd, (char const*)tlsData);
                            strcat(http_cmd, "\0");
                            len = strlen(http_cmd);
                            printf("Sending %d chars to server:\r\n%s\r\n", len, http_cmd);
                            //sock.send_all(http_cmd, len);
                            mdm.socketSend(socket, http_cmd, len);
                            ret=1;    
                            
                            /*reveive answer message (sleeptime) from server*/      
                            while (true) {
                                ret = mdm.socketRecv(socket, buffer, sizeof(buffer)-1);
                                if (ret <= 0) {
                                    printf("Received %d chars from server:\r\n%s\r\n", ret, buffer);
                                    break;
                                }
                                buffer[ret] = '\0';
                            
                                printf("Received %d chars from server:\r\n%s\r\n", ret, buffer);
                                
                                if((strncmp((char const*)buffer, "200", 3))) {
                                    strncpy(a, &buffer[ret-1], 1); 
                                    opcode = atoi(a);
                                    //printf("Received opcode= %d, %s\r\n", opcode, a);
                                    switch (opcode) {
                                        case 1 :
                                          sleepTime = 5;
                                          break;              
                                        case 2 :
                                          sleepTime = 30;
                                          break;
                                        case 3 :
                                          sleepTime = 300;
                                          break;
                                        default :
                                          sleepTime = 5;
                                          break; 
                                    }
                                    printf("Received sleeptime= %d\r\n", sleepTime);
                                    break;
                                    
                                }
                                else {
                                    break;
                                }
                            }    
                                
                            mdm.socketClose(socket);
                        }
                        mdm.socketFree(socket);
                    }
                    // disconnect  
                    mdm.disconnect();
                    ledD1 = ~ledD1;
                }
                ledD2 = ~ledD2;            
            }
            
            
            
        }
#ifdef RTOS_H
        Thread::wait(wait);
#else
        ::wait_ms(wait);
#endif
    }
    gps.powerOff();
    mdm.powerOff();
    return 0;
}