Versão atual 13-12-2013.

Dependencies:   EthernetInterface mbed-rtos mbed

Codes/Http_post.cpp

Committer:
rebonatto
Date:
2013-12-13
Revision:
1:238ac24e46dd
Parent:
0:65c41a68b49a

File content as of revision 1:238ac24e46dd:

/*
 * Http_post.cpp
 *
 *  Created on: 
 *      Author: 
 */
#include "Http_post.h"

extern "C" void mbed_reset();

void HttpPost::HttpPost_Thread(void const *arg)
{
    printf("HTTP POST Thread starting...\r\n");    
    
    //inicializar socket
   // TCPSocketConnection sock;
    
    CaptureMailbox& mbox = EventDetector::GetMailbox();
    
    osEvent evt;
    //printf("aqui\n");
    while(1)
    {
        TCPSocketConnection sock;
        //printf("Esperando Evento\n");
        evt = mbox.get();

        if(evt.status == osEventMail)
        {
            //printf("Recebido osEventMail...\n ");
            CaptureEvent* cap = (CaptureEvent*)evt.value.p;
            DoPost(sock,Settings::get_ServerUrl(),cap);    
            mbox.free(cap);
            //printf("Enviado e Liberado Mbox ...\n ");
            //sock.reset_address();
        }
        //Thread::yield();
    }
}



void HttpPost::DoPost(TCPSocketConnection sock, char *host, CaptureEvent* dados){
    char http_cmd[500]; 
    int escritos, r=-1, i;
    FILE *f;
    
    //Timer t;
    //t.start();
    
    //printf("HTTP Socket %s:%d\n", host, sock.get_port());
    //printf("Antes Connect\n");
    //rs= sock.connect(host, 80);   
    //printf("%d\n", rs);
    //printf("Depois Connect "); 
    
    //t.stop();
    //printf("HHTP: The time taken in connection was %d useconds\n", t.read_us());
           
    //http_cmd = (char *) malloc(500);
    memset(http_cmd, 0, 500);
    PreparePost( dados,http_cmd );
    //printf("Fuga\n");
    //printf("%d\n", strlen(http_cmd));
    
    //http_cmd = prepare_POST( dados );
    
    //printf("Tamanho comando %d\n", strlen(http_cmd));     
    //printf("Request %d\n [%s]\n", Settings::get_MaxTries(), http_cmd);     

    
    for(i=0; i < Settings::get_MaxTries(); i++){
        r = sock.connect(host, 80);        
        if (r < 0) {
            printf("Error: Unable to connect to (%s) on port (%d) Try %d\n", host, 80, i);
            Thread::wait(Settings::get_DelayTry());
        }
        else
            break;            
    }     
    if (r == 0){
        for(i=0; i < Settings::get_MaxTries(); i++){
            escritos = sock.send_all(http_cmd, strlen(http_cmd));        
            if(escritos != strlen(http_cmd)){
                printf("Erro ao gravar no socket HTTP!! Escritos %d\t Tam %d Try %d\n", escritos, strlen(http_cmd), i);            
                Thread::wait(Settings::get_DelayTry());
            }
            else 
                break;
        }
        if (i != Settings::get_MaxTries() )
            Thread::wait(Settings::get_DelaySend());
        else{
            //printf("Reset\n");
            f = fopen(FILENAMERESET, "a");
            if (f == NULL)            
                f = fopen(FILENAMERESET, "w");
            fprintf(f, "Reset - Connect\n");
            fclose(f);
                
            mbed_reset();
        }            
            
    //Codigo para buscar o retorno do servidor HTTP
    /*
    printf("Vai pegar retorno\n");
    
    char buffer[300];
    int ret;
    while (true) {
        ret = sock.receive(buffer, sizeof(buffer)-1);
        if (ret <= 0)
            break;
        buffer[ret] = '\0';
        printf("Received %d chars from server:\n%s\n", ret, buffer);
    }
    */
    }
    else{
        printf("Reset\n");
        f = fopen(FILENAMERESET, "a");
        if (f == NULL)            
            f = fopen(FILENAMERESET, "w");
        fprintf(f, "Reset - Send\n");
        fclose(f);
            
        mbed_reset();
    }
    
    sock.close();  
}

void HttpPost::PreparePost(CaptureEvent* dados,char *strfinal){
    char str[400];
    char aux[NUMBER_OF_HARMONICS];
    int i;

    const char *header1 = "POST /capture.php HTTP/1.1\r\n";
                //"Host: 192.168.1.26\r\n"
                //"Content-Length: "
                
    const char *header2 = "\r\n"
                "Content-Type: application/x-www-form-urlencoded\r\n"
                "\r\n";
    
    //str = (char *) malloc(450);
    //strfinal = (char *) malloc(450);
    memset(str,0,400);
    memset(strfinal,0,500);
            
    strcat(strfinal, header1);    
    strcat(strfinal, "Host: ");
    strcat(strfinal, Settings::get_ServerUrl() );
    strcat(strfinal, "\r\n");
    
    sprintf(aux,"TYPE=0%d",dados->get_Type());
    strcat(str, aux);

    sprintf(aux,"&OUTLET=%02d",dados->get_OutletNumber());
    strcat(str, aux);
    
    sprintf(aux,"&RFID=%s", dados->get_RFID());
    strcat(str,aux);

    sprintf(aux,"&OFFSET=%04d",dados->get_Offset());
    strcat(str,aux);
    
    float f = dados->get_Gain();
    sprintf(aux,"&GAIN=%08X", *(unsigned int*)&f);
    strcat(str,aux);
    
    f = dados->get_RMSValue();
    sprintf(aux,"&RMS=%08X",*(unsigned int*)&f);
    strcat(str,aux);

    f = dados->get_MeanValue();
    sprintf(aux,"&MV=%08X",*(unsigned int*)&f);
    strcat(str,aux);        

    strcat(str,"&SIN=");
    for(i=0;i<Settings::get_MaxHarmonics();i++)
    {
        char s[10];
        //According to RFC1738,RFC3986 the semicolon is a reserved character and must be encoded
        f = dados->get_SineValue(i);
        sprintf(s,"%08X",*(unsigned int*)&f);
        strcat(str,s);
        if (i < (Settings::get_MaxHarmonics() - 1))
            strcat(str, "%3B");
    }

    strcat(str,"&COS=");
    for(i=0;i<Settings::get_MaxHarmonics();i++)
    {
        char c[10];
        //According to RFC1738,RFC3986 the semicolon is a reserved character and must be encoded
        f = dados->get_CossineValue(i);
        sprintf(c,"%08X",*(unsigned int*)&f);
        strcat(str,c);
        if (i < (Settings::get_MaxHarmonics()-1))
            strcat(str, "%3B");
    }
    strcat(str,"\r\n");
    
    char len[5];
    sprintf(len,"%d",strlen(str));        
    
    strcat(strfinal, "Content-Length: ");
    strcat(strfinal, len);
    strcat(strfinal, header2);
    strcat(strfinal, str);    
    strcat(strfinal, "\r\n");
    
    //printf("Request=[%s]\n",strfinal);
    //printf("Tamanho STR %d\n", strlen(str));
    //printf("Tamanho STRFINAL %d\n", strlen(strfinal));       
 }