Wifi Pressure Sensor

Dependencies:   HTTPClient MPL3115A2 NTPClient TMP102 USBDevice cc3000_hostdriver_mbedsocket mbed

tcpTests.cpp

Committer:
markirwin
Date:
2014-06-20
Revision:
17:49ff1aa294dd
Parent:
16:a7902d75bef3

File content as of revision 17:49ff1aa294dd:

#include "mbed.h"
#include "cc3000.h"
#include "USBSerial.h"

#include "TCPSocketConnection.h"
#include "TCPSocketServer.h"
#include "HTTPClient.h"
//#include "Websocket.h"
//#include "TMP102.h"
#include "MPL3115A2.h"
using namespace mbed_cc3000;

extern cc3000 wifi;
extern USBSerial pc;

HTTPClient http;

// NOTE : Change SolderSplashLabs to anything else for your own channel
// Goto the viewier page here : http://sockets.mbed.org/SolderSplashLabs/viewer to see the websocket writes
const char WEB_SOCKET_URL[] = {"ws://sockets.mbed.org/ws/SolderSplashLabs/rw"};
const char* ECHO_SERVER_ADDRESS = "192.168.0.10";
const int ECHO_SERVER_PORT_TCP = 80;
char hello[] = "Hello World\r\n";

// Put the tmpbuffer into RAM1
char tmpBuffer[512] __attribute__((section("AHBSRAM0")));
char tmpDataBuffer[128] __attribute__((section("AHBSRAM0")));

// Add your own feed Id and API key here..
char XivelyHostname[] = "api.xively.com";
char XivelyPath[] = "/v2/feeds/601288128";
char XivelyApiKey[] = "6X82TDHSY7YKSJSraTBmS0nIMwO3W5NOMbVbeKPwwLNBgggw";

uint32_t number = 0;

AnalogIn adc0(P0_11); //P2
AnalogIn adc1(P0_12); //P3
AnalogIn adc2(P0_13); //P4
AnalogIn adc3(P0_14); //P5
AnalogIn adc5(P0_16); //P8
AnalogIn adc6(P0_22); //P9
AnalogIn adc7(P0_23); //P10


//TMP102 temperature(P0_5, P0_4, 0x90); //A0 pin is connected to ground
// Turn on and initalise the sensor

//I2C i2c(P0_5, P0_4);       // sda, scl
//Serial pc(USBTX, USBRX); // tx, rx
//MPL3115A2 sensor(&i2c);
// ------------------------------------------------------------------------------------------------------------
/*!
    @Post Pressure and Temperature Values to website
*/
// ------------------------------------------------------------------------------------------------------------
void TempTest (void)
{
I2C i2c(P0_5, P0_4);       // sda, scl

MPL3115A2 sensor(&i2c);

//float tempt = 0;
//float pressure = 0;
//float random = 0; 
pc.printf("** MPL3115A2 SENSOR **\r\n");

sensor.init();

//pc.printf("Who Am I: 0x%X\r\n", sensor.whoAmI());

Altitude a;
Temperature t;
Pressure p;

// Offsets for Dacula, GA
//sensor.setOffsetAltitude(83);
//sensor.setOffsetTemperature(20);
//sensor.setOffsetPressure(-32);

while (1) 
    {
        sensor.readAltitude(&a);
        sensor.readTemperature(&t);
        
        sensor.setModeStandby();
        sensor.setModeBarometer();
        sensor.setModeActive();
        sensor.readPressure(&p);
        
        pc.printf("Altitude: %sM, Temp: %sºC, Pressure: %sPa\r\n", a.print(), t.print(), p.print());
     //   pc.printf("OFF_H: 0x%X, OFF_T: 0x%X, OFF_P: 0x%X\r\n", sensor.offsetAltitude(), sensor.offsetTemperature(), sensor.offsetPressure());
    
        wait(600);
 
        sensor.setModeStandby();
        sensor.setModeAltimeter();
        sensor.setModeActive();
        
        /*tempt = temperature.read();
        
        pc.printf( "%05d\r\nTEMP, %.1f\r\n\0", tempt);
       // HTTP POST Test
       
        random +=1; */
        HTTPMap map;
        HTTPText inText(tmpBuffer, 512);
       
        //char buffer[50];
        //sprintf (buffer, "%.1f", tempt);
    
        map.put("Temperature", t.print());
        //map.put("test", "1234");
        pc.printf(" \r\nTrying to post data.. %0.1f \r\n", t.print());
        int ret = http.post("http://markirwin.herokuapp.com/readings", map, &inText);
        if (!ret)
        {
          pc.printf("Executed POST successfully - read %d characters \r\n", strlen(tmpBuffer));
          pc.printf("Result: %s \r\n", tmpBuffer);
        }
        else
        {
          pc.printf("Error - ret = %d - HTTP return code = %d \r\n", ret, http.getHTTPResponseCode());
        }
 
        wait_ms(1000);
        
        if ( pc.readable() )
        {
            pc.printf("Ending Temp Posting \r\n");
            pc.getc();
            break;
        }
    }
    
   
}

// ------------------------------------------------------------------------------------------------------------
/*!
    @brief Post all analog inputs to xively every second
*/
// ------------------------------------------------------------------------------------------------------------

void XivelySimpleTest ( void )
{
TCPSocketConnection socket;
int res = 0;
uint16_t counter = 0;
int httpCmdLen = 0;
int httpDataLen = 0;
float tempt = 0;
    
    //if ( wifi.is_connected() )
        
    while (1)
    {   
        if (socket.connect(XivelyHostname, 80) < 0) 
        {
            pc.printf("\r\nUnable to connect to (%s) on port (%d)\r\n", XivelyHostname, 80);
            socket.close();
        }
        else
        {
            // Block for 1 second
            socket.set_blocking( true, 1000 );
            counter ++;

            // loop
            if (number > 10)
            {number = 0;}
            else 
            {number++;}
            // Temp Read
            //tempt = temperature.read();
            
            // Build the data string
            httpDataLen = sprintf(&tmpDataBuffer[0], "COUNT, %05d\r\nRAMP, %05d\r\nTEMP, %.1f\r\n\0", counter, number, tempt);
                  
            //httpDataLen += sprintf(&tmpDataBuffer[0], "ADC0, %05d\r\nADC1, %05d\r\nADC2, %05d\r\nADC3, %05d\r\nADC5, %05d\r\nADC6, %05d\r\nADC7, %05d\r\n\0", 
            //adc0.read_u16(), adc1.read_u16(), adc2.read_u16(), adc3.read_u16(), adc5.read_u16(), adc6.read_u16(), adc7.read_u16());
                
            // Build the header
            httpCmdLen = sprintf(&tmpBuffer[0], "PUT %s.csv HTTP/1.1\r\n", XivelyPath );
            httpCmdLen += sprintf(&tmpBuffer[httpCmdLen], "Host: %s\r\nUser-Agent: WiFi-DipCortex\r\n", XivelyHostname);
            httpCmdLen += sprintf(&tmpBuffer[httpCmdLen], "X-ApiKey: %s\r\n", XivelyApiKey);
            // TODO : hardcoded data length of 91, using printf with padding to fix the string length
            httpCmdLen += sprintf(&tmpBuffer[httpCmdLen], "Content-Type: text/csv\r\nContent-Length: %d\r\n", httpDataLen);
            httpCmdLen += sprintf(&tmpBuffer[httpCmdLen], "Connection: close\r\n\r\n");
            // Add the data            
            httpCmdLen += sprintf(&tmpBuffer[httpCmdLen], "%s\0", tmpDataBuffer);
           
            pc.printf("HTTP Data to be sent : \r\n %s", tmpBuffer);
    
            pc.printf("Posting ADC's to Xively \r\n");
            res = socket.send_all(tmpBuffer, httpCmdLen);
            
            if ( res > 0 )
            {
                pc.printf("%05d : Data Sent \r\n", counter);
            }
            else
            {
                pc.printf("Failed to send\r\n");
                break;
            }
            
            res = socket.receive(tmpBuffer, 512);
            
            if ( res > 0 )
            {
                pc.printf("TCP Socket Recv'd : \r\n %s", tmpBuffer);
                tmpBuffer[res] = '\0';
            }
            else
            {
                tmpBuffer[0] = '\0';
                pc.printf("TCP : Failed to Recv\r\n");
                break;
            }
            
            socket.close();
        }
        
        wait_ms(1000);

        if ( pc.readable() )
        {
            pc.printf("Ending Xively Post \r\n");
            pc.getc();
            break;
        }
    }
}

// ------------------------------------------------------------------------------------------------------------
/*!
    @brief Exercise the HTTP Client library
*/
// ------------------------------------------------------------------------------------------------------------
void HttpClientTest ( void )
{

    //GET data
    pc.printf("\r\nTrying to fetch page... \r\n");
    int ret = http.get("http://mbed.org/media/uploads/donatien/hello.txt", tmpBuffer, 128);
    if (!ret)
    {
      pc.printf("Page fetched successfully - read %d characters \r\n", strlen(tmpBuffer));
      pc.printf("Result: %s \r\n", tmpBuffer);
    }
    else
    {
      pc.printf("Error - ret = %d - HTTP return code = %d \r\n", tmpBuffer, http.getHTTPResponseCode());
    }
 
    //POST data
    HTTPMap map;
    HTTPText inText(tmpBuffer, 512);
    map.put("Hello", "World");
    map.put("test", "1234");
    pc.printf(" \r\nTrying to post data... \r\n");
    ret = http.post("http://httpbin.org/post", map, &inText);
    if (!ret)
    {
      pc.printf("Executed POST successfully - read %d characters \r\n", strlen(tmpBuffer));
      pc.printf("Result: %s \r\n", tmpBuffer);
    }
    else
    {
      pc.printf("Error - ret = %d - HTTP return code = %d \r\n", ret, http.getHTTPResponseCode());
    }
 
    //PUT data
    strcpy(tmpBuffer, "This is a PUT test!");
    HTTPText outText(tmpBuffer);
    //HTTPText inText(tmpBuffer, 512);
    pc.printf(" \r\nTrying to put resource... \r\n");
    ret = http.put("http://httpbin.org/put", outText, &inText);
    if (!ret)
    {
      pc.printf("Executed PUT successfully - read %d characters \r\n", strlen(tmpBuffer));
      pc.printf("Result: %s \r\n", tmpBuffer);
    }
    else
    {
      pc.printf("Error - ret = %d - HTTP return code = %d \r\n", ret, http.getHTTPResponseCode());
    }
 
    //DELETE data
    //HTTPText inText(tmpBuffer, 512);
    pc.printf(" \r\nTrying to delete resource... \r\n");
    ret = http.del("http://httpbin.org/delete", &inText);
    if (!ret)
    {
      pc.printf("Executed DELETE successfully - read %d characters \r\n", strlen(tmpBuffer));
      pc.printf("Result: %s \r\n", tmpBuffer);
    }
    else
    {
      pc.printf("Error - ret = %d - HTTP return code = %d \r\n", ret, http.getHTTPResponseCode());
    }
}

// ------------------------------------------------------------------------------------------------------------
/*!
    @brief Open a WebSocket, send a string
*/
// ------------------------------------------------------------------------------------------------------------
void WebSocketTest ( void )
{
/*
int res = 0;
uint16_t counter = 0;
uint16_t reconnects = 0;
uint8_t myMAC[8];

    wifi.get_mac_address(myMAC);
    
    Websocket ws((char *)WEB_SOCKET_URL);
    if ( ws.connect() )
    {
        pc.printf("Connected to websocket server.\r\n");
        
        pc.printf("\r\n!! Press any key to stop sending !!\r\n\r\n");
        while (1)
        {   
            counter ++;
            sprintf(tmpBuffer, "WiFi DipCortex / CC3000 - %05d - %02x:%02x:%02x:%02x:%02x:%02x\r\n", counter, myMAC[0], myMAC[1], myMAC[2], myMAC[3], myMAC[4], myMAC[5]);
            
            if ( wifi.is_connected() )
            {
                res = ws.send(tmpBuffer);
                pc.printf("Reconnects : %05d, Messages Sent : %05d, Websocket send returned : %d.\r\n", reconnects, counter, res);
            
                if ( -1 == res ) 
                {
                    pc.printf("Websocket Failure, reconnecting .... \r\n");
                    ws.close();
                    if ( ws.connect() )
                    {
                        // Reconnected
                        reconnects ++;
                    }
                    else
                    {
                        // Failure!
                        break;
                    }
                }
                
                wait_ms(1000);
            }
            else
            {
                pc.printf("WiFi Connection Lost .... \r\n");
            }
            
            if ( pc.readable() )
            {
                pc.printf("Closing Socket \r\n");
                pc.getc();
                break;
            }
        }
        
        ws.close();
        pc.printf("Websocket Closed \r\n");
    }
    else
    {
        pc.printf("Websocket connection failed\r\n");
    }
    */
}

// ------------------------------------------------------------------------------------------------------------
/*!
    @brief Open a WebSocket, send a string
*/
// ------------------------------------------------------------------------------------------------------------
void WebSocketReadTest ( void )
{
/*
int res = 0;
uint16_t counter = 0;
uint16_t reconnects = 0;
uint8_t myMAC[8];

    wifi.get_mac_address(myMAC);
    
    Websocket ws((char *)WEB_SOCKET_URL);
    if ( ws.connect() )
    {
        pc.printf("Connected to websocket server.\r\n");
        
        pc.printf("\r\n!! Press any key to stop receiving !!\r\n\r\n");
        while (1)
        {   
            counter ++;
            //sprintf(tmpBuffer, "WiFi DipCortex / CC3000 - %05d - %02x:%02x:%02x:%02x:%02x:%02x\r\n", counter, myMAC[0], myMAC[1], myMAC[2], myMAC[3], myMAC[4], myMAC[5]);
            
            if ( wifi.is_connected() )
            {
                res = ws.read(tmpBuffer);
                
                if ( res )
                {
                    pc.printf("Websocket Received : %s (Reconnects : %05d, Messages Recv : %05d)\r\n", tmpBuffer, reconnects, counter);
                }
                
                if ( ws.is_connected() )
                {
                
                }
                else
                {
                    pc.printf("Websocket Closed, reconnecting .... \r\n");
                    ws.close();
                    if ( ws.connect() )
                    {
                        // Reconnected
                        reconnects ++;
                    }
                    else
                    {
                        // Failure!
                        break;
                    }
                }
            }
            else
            {
                pc.printf("WiFi Connection Lost .... \r\n");
            }
            
            if ( pc.readable() )
            {
                pc.printf("Closing Socket \r\n");
                pc.getc();
                break;
            }
        }
        
        ws.close();
        pc.printf("Websocket Closed \r\n");
    }
    else
    {
        pc.printf("Websocket connection failed\r\n");
    }
    */
}

// ------------------------------------------------------------------------------------------------------------
/*!
    @brief Open a TCP port send a string and wait for a reply
*/
// ------------------------------------------------------------------------------------------------------------
void TcpClientTest ( void )
{
uint16_t counter = 0;
TCPSocketConnection socket;
int n = 0;
        
    if (socket.connect(ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT_TCP) < 0) 
    {
        pc.printf("\r\nUnable to connect to (%s) on port (%d)\r\n", ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT_TCP);
    }
    else
    {
        // Block for 1 second
        socket.set_blocking( true, 1000 );
        
        pc.printf("\r\n!! Press any key to stop sending !!\r\n\r\n");
        while (1)
        {   
            counter ++;
        
            n = socket.send_all(hello, sizeof(hello) - 1);
            
            if ( n > 0 )
            {
                pc.printf("%05d : TCP Socket Sent : Hello World\r\n", counter);
            }
            else
            {
                pc.printf("Failed to send\r\n");
                break;
            }
     
            n = socket.receive(tmpBuffer, 256);
            
            if ( n > 0 )
            {
                pc.printf("TCP Socket Recv'd : %s \r\n", tmpBuffer);
                tmpBuffer[n] = '\0';
            }
            else
            {
                tmpBuffer[0] = '\0';
                pc.printf("TCP : Failed to Recv\r\n");
                break;
            }
            
            wait_ms(50);
            
            // Should we stop?
            if ( pc.readable() )
            {
                pc.printf("Closing Socket \r\n");
                pc.getc();
                break;
            }
        }
        if ( wifi.is_connected() )
        {
            socket.close();
        }
        pc.printf("Completed.\r\n");
    }
}


// ------------------------------------------------------------------------------------------------------------
/*!
    @brief Opens a sockets to listen for connections, upon connection a message is sent and the 
           client disconnected
*/
// ------------------------------------------------------------------------------------------------------------
void TcpServerTest ( void )
{
int32_t status;
TCPSocketServer server;
TCPSocketConnection client;
    
    server.bind(80);
    server.listen();
    pc.printf("\r\n!! Press any key to stop listening !!\r\n\r\n");
    while (1) 
    {
        status = server.accept(client);
        if (status >= 0) 
        {
            client.set_blocking(false, 1500); // Timeout after (1.5)s
            pc.printf("Connection from: %s \r\n", client.get_address());
            //client.receive(buffer, sizeof(buffer));
            //pc.printf("Received: %s \r\n",buffer);
            pc.printf("Sending the message to the server. \r\n");
            client.send_all(hello, sizeof(hello));
            client.close();
        }
        
        // Should we stop?
        if ( pc.readable() )
        {
            pc.printf("Closing Socket \r\n");
            pc.getc();
            break;
        }
        
        if (! wifi.is_connected() )
        {
            pc.printf("WiFi Connection lost \r\n");
            break;
        }
    }
    
    if ( wifi.is_connected() )
    {
        server.close();
    }
}