Port from Avnet's Internet Of Things full WiGo demo: SmartConfig - WebServer - Exosite - Android sensor Fusion App

Dependencies:   NVIC_set_all_priorities mbed cc3000_hostdriver_mbedsocket TEMT6200 TSI Wi-Go_eCompass_Lib_V3 WiGo_BattCharger

Wi-Go Reference Design Overview


For additional information on Wi-Go, please visit http://www.em.avnet.com/wi-go
For additional information on Freescale eCompass, please visit
http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=E-Compass
Ported from Avnet's Wi-Go KEIL code.
Special thanks to Jim Carver from Avnet for providing the Wi-Go board and for his assistance.


Multiple Wi-Fi applications are provided within the latest version of Wi-Go software:

  • SmartConfig App for auto-setup of Wi-Go network parameters.
  • WebServer display of live sensor data.
  • Exosite portal sensor data feed by Wi-Go.
  • Freescale's Sensor Fusion App data feed by Wi-Go.

Wi-Go is intended for "untethered" portable operation (using it's high-capacity Lithium-Polymer battery). The serial terminal text interface is only required for initial setup, thereafter selection of an application from those available is via finger position on the Touch Slider during the initial 6 second startup period.

Running the Wi-Go Demo Suite

Warning

The on-board Firmware must be updated to mbed enable a Wi-Go system.
Goto the Component page to get the FirmwareUpdate tool (scroll down to the FirmwareUpdate topic).

MAG3110 sensor and eCompass Calibration!

As with the other sensor applications, the eCompass function requires quality calibration data to achieve best accuracy.
For the first 15 seconds after power-up it is recommended that "Figure 8" movements with Wi-Go be done in a smooth, repetitive pattern. Don't touch the slider pad during calibration.

Startup
The RGB LED blinks in a GREEN-ORANGE sequence to inform the user the module is waiting for input.
The RGB LED color designates which of the following Apps to launch.

RGB LED ColorApplication to Launch
OrangeErase all wireless profiles
PurpleSmartConfig
BlueWebServer
RedExosite Data Client
GreenAndroid Server

Swipe your index finger across the slider pad, the RGB LED color will change at approximately 20% intervals.
Removing your finger latches the last color displayed. After about 3 seconds, the selected app will start.
Another app can be selected when the slider pad is touched again within the 3 seconds timeout.

After launch of Exosite or Android Server Apps, the eCompass function then controls the RGB LED.
(not in WebServer mode where RGB LEDs are manually controlled by the User).

RGB LED ColorDirection Indication
BlueNear to North
GreenNorth
RedEast / West
PurpleSouth

__Note!__ The D1, D2 and D3 User LEDs on Wi-Go adhere to the following convention for the different Apps

User LED#Description of function controlling the LED
D1is the board heartbeat, derived from the timer interrupt
D2indicates network activity as follows:
Web Server Wi-Go webpage is being served.
Exosite Client Wi-Go is sending data.
Android App Wi-Go is sending data
D3WLAN Network is Connected

Detail of Wi-Go Applications

App #1: SmartConfig
See TI's pages on how to use the SmartConfig tool:

  • Preferred method : Configuration using the SmartConfig tool
  • SmartConfig download: Smart Config and Home Automation
    • iOS app : available at Apple app store.
    • Android app : download and install the Android SmartConfig Application on a PC.
      This file contains the source code as well as the compiled APK file.
      The APK file is stored in ti\CC3000AndroidApp\SmartConfigCC3X\bin.

App #2: WebServer display of live sensor data
__Note!__
When using the WebServer for the first time on a Wi-Fi network you will need to determine the IP address that's assigned to Wi-Go by the DHCP Server. To do this, it is recommended you use one of the following two methods:

  • While Wi-Go is initially tethered to a laptop via USB, launch of the WebServer Application and note the IP address that is reported on the terminal screen immediately after selection of this App.
  • Alternatively, use a 3rd party LAN SCAN type tool to view Wi-Go's IP address.
    eg. FING, - available for free download from Google Play or iTunes App Stores…

Wi-Go's WebServer Application is selected as follows:

  • Press RESET, followed by the eCompass Calibration (mentioned at the top of this page).
    Then use index finger on slider to select the WebServer App (RGB LED = BLUE).
    At end of the 3 second selection period the WebServer App shall launch.
  • If you are tethered to a laptop and have a terminal open the Wi-Fi network connection confirmation will be seen, eg.

'*** Wi-Go board DHCP assigned IP Address = 192.168.43.102
  • Once you have noted Wi-Go's reported IP address, the USB cable may be disconnected and Wi-Go then used as intended, running on it's own battery power.
  • Use an Internet Browser on SmartPhone/Tablet/Laptop (connected to same Hot-Spot/Wireless Router subnet), to now connect to the noted Wi-Go IP address and view the WebServer output: /media/uploads/frankvnk/wi-go_webserver.png
  • the Webserver sensor data is auto-updated every 2 seconds a manual refresh (F5 on laptop).
  • In the event of an error, press refresh to regenerate the screen.
  • Use the mouse (or touch-screen) to exercise the RGB LED output.

App #3: Exosite Data Client
Wi-Go's sensor data gets transmitted via Wi-Fi to a cloud-based Exosite portal where the sensor measurements are displayed graphically on a "dashboard". Users can create unique customized dashboards using drag and drop GUI widgets from the library provided on the Exosite website.
__Note!__ For the Exosite application a "live" connection to the Internet is required !!!

  • Press RESET, followed by the eCompass Calibration (mentioned at the top of this page).
    Then use index finger on slider to select the Exosite Client App (RGB LED = RED)
  • On launching this App, note Wi-Go's MAC address displayed on your terminal
    (if not running a terminal use FING or other WLAN Scan tool to determine Wi-Go's MAC address) /media/uploads/frankvnk/mac_address.png
  • Using your computer's internet browser, go to avnet.exosite.com and sign-up for a free Avnet Trial Exosite Account: /media/uploads/frankvnk/avnet_trial_exosite.png
  • On the next screen, click on the Sign-Up Now button in the displayed Avnet Trial account option.
  • Complete the Account Info and Contact Info then click on Create Account (make sure to use a valid email address!).
  • Check for new incoming email from avnet.exosite.com to the address you provided and click on the link in this email to activate your new Exosite account.
  • Once activated, login using the email address and password that you chose in your registration. Your Exosite Portal and Dashboard should now display. The first time you log-in to your new account, the default Home dashboard will be displayed, pre-configured with two widgets. On the left is the Welcome widget for tips and information. On the right is the Device List widget.
    Dashboards are configurable, so at any time this default dashboard can be changed, widgets deleted and added (Clicking the upside-down triangle icon in a widget's Title bar will allow you to edit it).
  • Before going further with the Dashboard, you need to connect your Wi-Go device to your Exosite account. Do this by going to the left sidebar and selecting Devices followed by selecting the +Add Device link (on right of screen). /media/uploads/frankvnk/add_device.png
  • In the Setup screens that follow, enter the following
Select a supported deviceWi-Go
Enter device MAC Addressnn:nn:nn:nn:nn:nn [your Wi-Go's MAC address including colons]
Enter device Name[choose a descriptive name]
Enter device Location[description of your location]
  • Once completed, under Devices the name chosen for the added Wi-Go device should now be listed.
  • Click on this new Wi-Go device to examine (and edit if necessary) it's Device Information screen.
    /media/uploads/frankvnk/device_information.png
  • Click the CLOSE button to exit the Device Information screen.
  • On your Wi-Go kit now press RESET, followed by the eCompass Calibration (mentioned at the top of this page)
    and again select the Exosite Client App (RGB LED = RED) using your index finger.
  • Refresh your browser (press F5) a couple've times until the Active indicator changes to On (Green).
    /media/uploads/frankvnk/active_indicator.png
  • From the left sidebar click on Home and click on the recently named Wi-Go device which is located under the Device List.
    This will bring-up a default dashboard display similar to what's shown below.
    (Dashboards are typically accessed via the Dashboards menu entry). Check the dashboard is updating with live data by moving your Wi-Go Kit through different orientations.
    /media/uploads/frankvnk/dashboard.png
  • To create a custom dashboard, select Dashboards from the sidebar menu, followed by +Add Dashboard (on right side of Your Dashboards title bar). After completion of the initial configuration screen you will then be able to add Widgets to display the various Wi-Go data sources as well as pictures and text to support your application.
  • More guidance on the creation, editing and sharing of custom dashboards is available under the Exosite support pages

App #4: Android Sensor Fusion App

  • Press RESET, followed by the eCompass Calibration (mentioned at the top of this page)
    , then use index finger on slider to select the Android App (RGB LED = GREEN)
  • Freescale's ''Xtrinsic Sensor Fusion Toolbox'" will run on Android 3.0 or above phone or tablet. Free to download from Google Play, type Sensor fusion in the search box to find it. freescale.sensors.sfusion /media/uploads/frankvnk/sensor_fusion_toolbox.png
  • The Freescale App is well documented. To access the built-in documentation, press the NAV button at top of screen followed by Documentation from the scroll-down menu:
    /media/uploads/frankvnk/sensor_fusion_doc.png
  • Freescale's sensors site provides additional resources such as this overview: free-android-app-teaches-sensor-fusion-basics
  • Go to the Options Menu and select Preferences… /media/uploads/frankvnk/sensor_fusion_preferences.png
  • The following items need to be taken care of:
Enter WiGo's IP address
Enter the SSID (of the Hot-Spot or Wireless Access Point used by Wi-Go)
  • Press Save and Exit!
    /media/uploads/frankvnk/sensor_fusion_save_and_exit.png
  • Exit the Application completely then re-launch the Sensor Fusion Application.
  • Select the ''Source/Algorithm'" menu and change the data source to Wi-Go mag/accel /media/uploads/frankvnk/sensor_fusion_wigo_mag_accel.png
  • The Android App should now be displaying a 3-D image of Wi-Go that you can rotate and flip-over by moving the Wi-Go board accordingly…
  • Use NAV > Device View to display if this view does not come-up by default. /media/uploads/frankvnk/sensor_fusion_nav_device_view.png
  • A Serial Terminal connection is not necessary but if you happen to have one open you should see the following messages as Wi-Go connects to the Android App:
    "Server waiting for connection" followed by
    "connected, transmit buffer size= 96", and then
    "input = 0123456789"
    at which time Wi-Go starts streaming data to the Android App.

Webserver/run_exosite.cpp

Committer:
frankvnk
Date:
2015-02-28
Revision:
7:9d86d022fa68
Parent:
4:8f8d0d19e6f1

File content as of revision 7:9d86d022fa68:

/*****************************************************************************
*
*  demo.c - CC3000 Main Demo Application
*  Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*    Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
*
*    Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the   
*    distribution.
*
*    Neither the name of Texas Instruments Incorporated nor the names of
*    its contributors may be used to endorse or promote products derived
*    from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/

#include "run_exosite.h"
#include "Wi-Go_eCompass_Lib_V3.h"
#include "mbed.h"
#include "defLED.h"
#include "strlib.h"

extern DigitalOut ledr;
extern DigitalOut ledg;
extern DigitalOut ledb;
extern DigitalOut led1;
extern DigitalOut led2;
extern DigitalOut led3;

// local defines
#define WRITE_INTERVAL 5
#define EXO_BUFFER_SIZE 300 //reserve 300 bytes for our output buffer

typedef struct
{
    float *p;
    char *s;
} exo_data_ft;

typedef struct
{
    int16_t *p;
    char *s;
} exo_data_it;

//extern tUserFS user_info;

extern char requestBuffer[];

extern unsigned int compass_type, seconds;

char exo_meta[META_SIZE];

#define RX_SIZE 60
#define MAC_LEN 6

typedef enum
{
    CIK_LINE,
    HOST_LINE,
    CONTENT_LINE,
    ACCEPT_LINE,
    LENGTH_LINE,
    GETDATA_LINE,
    POSTDATA_LINE,
    VENDOR_LINE,
    EMPTY_LINE
} lineTypes;

#define STR_CIK_HEADER "X-Exosite-CIK: c3c675e0601551c6d4d3230e162d62cc8bba3311\r\n"
#define STR_CONTENT_LENGTH "Content-Length: "
#define STR_GET_URL "GET /api:v1/stack/alias?"
#define STR_HTTP "  HTTP/1.1\r\n"
#define STR_HOST "Host: avnet.m2.exosite.com\r\n"
#define STR_ACCEPT "Accept: application/x-www-form-urlencoded; charset=utf-8\r\n"
#define STR_CONTENT "Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n"
#define STR_VENDOR "vendor=avnet&model=wigosmartconfig&sn="
#define STR_CRLF "\r\n"
#define MY_CIK "27b9684751332589be52c8e5819e7c438f7e7479"
char myCIK[] = "c3c675e0601551c6d4d3230e162d62cc8bba3311";

// local functions
void activate_device(TCPSocketConnection *socket);
int readResponse(TCPSocketConnection *socket, char * expectedCode);
long connect_to_exosite(TCPSocketConnection *socket);
void sendLine(TCPSocketConnection *socket, unsigned char LINE, char * payload);
void exosite_meta_write(unsigned char * write_buffer, unsigned short srcBytes, unsigned char element);
void exosite_meta_read(unsigned char * read_buffer, unsigned short destBytes, unsigned char element);
int Exosite_Write(TCPSocketConnection *socket, char * pbuf, unsigned char bufsize);
int Exosite_Read(char * palias, char * pbuf, unsigned char bufsize);
int Exosite_Init(TCPSocketConnection *socket);

// global variables
static unsigned char exositeWriteFailures = 0;

// exported functions

// externs
extern char *itoa(int n, char *s, int b);

extern axis6_t axis6;
extern int secondFlag;
extern int server_running;

/** \brief Definition of data packet to be sent by server */
unsigned char dataPacket[] = { '\r', 0xBE, 128, 128, 128, 70, 36, 0xEF };
char activeCIK[41];

exo_data_ft exo_fdata[] = {
        &axis6.fGax,    "acc_x=%f&",
        &axis6.fGay,    "acc_y=%f&",
        &axis6.fGaz,    "acc_z=%f&",
        &axis6.fUTmx,   "mag_x=%f&",
        &axis6.fUTmy,   "mag_y=%f&",
        &axis6.fUTmz,   "mag_z=%f&",    
        &axis6.q0,      "q_w=%f&",  
        &axis6.q1,      "q_x=%f&",  
        &axis6.q2,      "q_y=%f&",  
        &axis6.q3,      "q_z=%f&",  
        0, 0 };

exo_data_it exo_idata[] = {
        &axis6.roll,    "roll=%d&",
        &axis6.pitch,   "pitch=%d&",
        &axis6.yaw,     "yaw=%d&",
        &axis6.alt,     "alt=%d&",
        &axis6.temp,    "temp=%d&",
        &axis6.light,   "light=%d&",
        0, 0
};
    
//*****************************************************************************
//
//!  main
//!
//!  \param  None
//!
//!  \return none
//!
//!  \brief   The main loop is executed here
//
//*****************************************************************************
void run_exosite(TCPSocketConnection *socket)
{
    int value;
    exo_data_it *tsp;
    exo_data_ft *tspf;
    
    printf("\nConnecting to Exosite\n");
    //user_info.validCIK = 0; // uncomment this to force provisioning every time, only used for debug
    
    if(!user_info.validCIK)
    {
        printf("Activating Wi-Go System on Exosite\n");
        uint8_t myMAC[8];
        wifi.get_mac_address(myMAC);
        printf(" MAC address %02x:%02x:%02x:%02x:%02x:%02x \r\n \r\n", myMAC[0], myMAC[1], myMAC[2], myMAC[3], myMAC[4], myMAC[5]);
        wait_ms(100);
        printf("Enter the device MAC on your Exosite device portal to prepare\n");
        wait_ms(100);
        printf("the system for provisioning your Wi-Go system onto Exosite\n");
        wait_ms(100);
        printf("Hit any key to continue.....\n");
        getchar();
        Exosite_Init(socket);
    }
    
    for(value=0 ;value < CIK_LENGTH ; value++) activeCIK[value] = user_info.CIK[value];
    activeCIK[value] = NULL;
    // Main Loop
    while (1)
    {
        while(!secondFlag) /*__wfi()*/;
        secondFlag = 0;
        LED_D2_ON;

        // Build string
        requestBuffer[0] = 0;
        tsp     = &exo_idata[0];
        tspf    = &exo_fdata[0];
        while(tsp->p)
        {
            sprintf( requestBuffer + strlen(requestBuffer), tsp->s, *tsp->p);
            tsp++;
        }
        while(tspf->p)
        {
            sprintf( requestBuffer + strlen(requestBuffer), tspf->s, *tspf->p);
            tspf++;
        }
        sprintf( requestBuffer + strlen(requestBuffer), "time=%d\r\n", axis6.timestamp);

        if(strlen(requestBuffer) > 300) printf("Buffer size= %d too small!!!", strlen(requestBuffer));
        //printf("Buffer size= %d\n", strlen(requestBuffer));
        value = Exosite_Write(socket, requestBuffer, strlen(requestBuffer));    //write all sensor values to the cloud
        LED_D2_OFF; 
        if(value == -1)
        {
            LED_D3_OFF;
            wifi.stop();
            if (wifi.connect() == -1)
                printf("Failed to connect. Please verify connection details and try again. \r\n");
            else
            {
                printf("Connected - IP address: %s \r\n",wifi.getIPAddress());
                LED_D3_ON;
            }
        }
    }
}

//*****************************************************************************
//
//! Exosite_Init
//!
//!  \param  None
//!
//!  \return 0 success; -1 failure
//!
//!  \brief  The function initializes the cloud connection to Exosite
//
//*****************************************************************************
int Exosite_Init(TCPSocketConnection *socket)
{
    char strBuf[META_MARK_SIZE];
    const unsigned char meta_server_ip[6] = {173,255,209,28,0,80};
    uint8_t mac_status = 1;
    uint8_t myMAC[8];
    int i;
    char tempCIK[CIK_LENGTH];

    //check our meta mark - if it isn't there, we wipe the meta structure
    exosite_meta_read((unsigned char *)strBuf, META_MARK_SIZE, META_MARK);
    if (strncmp(strBuf, EXOMARK, META_MARK_SIZE))
    {
        memset(exo_meta, 0, META_SIZE); //erase the information currently in meta
        exosite_meta_write((unsigned char *)meta_server_ip, 6, META_SERVER);     //store server IP
        exosite_meta_write((unsigned char *)EXOMARK, META_MARK_SIZE, META_MARK); //store exosite mark
    }

    while(mac_status) mac_status = wifi.get_mac_address(myMAC);
    exosite_meta_write((unsigned char *)myMAC, 17, META_UUID);

    //setup some of our globals for operation
    exositeWriteFailures = 0;

    //exosite Re-init : Called after Init has been ran in the past, but maybe
    //                  comms were down and we have to keep trying...
    activate_device(socket);    //the moment of truth - can this device provision with the Exosite cloud?...
    exosite_meta_read((unsigned char *)tempCIK, CIK_LENGTH, META_CIK); //sanity check on the CIK
    for (i = 0; i < CIK_LENGTH; i++)
    {
        if (!(tempCIK[i] >= 'a' && tempCIK[i] <= 'f' || tempCIK[i] >= '0' && tempCIK[i] <= '9'))
        {
            return -1;
        }
    }
    for(i=0;i<CIK_LENGTH;i++) user_info.CIK[i] = tempCIK[i];
    user_info.validCIK = 1;
    wifi._nvmem.write( NVMEM_USER_FILE_1_FILEID, sizeof(user_info), 0, (unsigned char *) &user_info);
    return 0;
}

//*****************************************************************************
//
//! Exosite_Write
//!
//!  \param  pbuf - string buffer containing data to be sent
//!          bufsize - number of bytes to send
//!
//!  \return 0 success; -1 failure
//!
//!  \brief  The function writes data to Exosite
//
//*****************************************************************************
int Exosite_Write(TCPSocketConnection *socket, char * pbuf, unsigned char bufsize)
{
    char strBuf[10];
    long sock = -1;

    sock = connect_to_exosite(socket);
    if(sock == -1) return(sock);

// This is an example write POST...
//  s.send('POST /api:v1/stack/alias HTTP/1.1\r\n')
//  s.send('Host: m2.exosite.com\r\n')
//  s.send('X-Exosite-CIK: 5046454a9a1666c3acfae63bc854ec1367167815\r\n')
//  s.send('Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n')
//  s.send('Content-Length: 6\r\n\r\n')
//  s.send('temp=2')

    sprintf(strBuf, "%d", (int)bufsize); //make a string for length

    sendLine(socket, POSTDATA_LINE, "/onep:v1/stack/alias");
    sendLine(socket, HOST_LINE, NULL);
    sendLine(socket, CIK_LINE, NULL);
    sendLine(socket, CONTENT_LINE, NULL);
    sendLine(socket, LENGTH_LINE, strBuf);
    //printf("Data=%s\n", pbuf);
    socket->send_all(pbuf, bufsize); //alias=value
    wifi._event.hci_unsolicited_event_handler();

    if (0 == readResponse(socket, "204"))
    {
        exositeWriteFailures = 0;
    }
    else
    {
        exositeWriteFailures++;
    }

    socket->close();

    if (exositeWriteFailures > 5)
    {
        // sometimes transport connect works even if no connection...
        printf("ERROR %d\r\n", EXO_ERROR_WRITE);
    }

    if (!exositeWriteFailures)
    {
        //printf("ShowUIcode %d\n", EXO_CLIENT_RW);
        return 0; // success
    }
    return 0;
}    


//*****************************************************************************
//
//! activate_device
//!
//!  \param  none
//!
//!  \return none
//!
//!  \brief  Calls activation API - if successful, it saves the returned
//!          CIK to non-volatile
//
//*****************************************************************************
void activate_device(TCPSocketConnection *socket)
{
    long sock = -1;
    volatile int length;
    char strLen[5];

    while (sock < 0)
    sock = connect_to_exosite(socket);
    printf("Activating Device\n");

    length = strlen(STR_VENDOR) + META_UUID_SIZE;
    itoa(length, strLen, 10); //make a string for length

    sendLine(socket, POSTDATA_LINE, "/provision/activate");
    sendLine(socket, HOST_LINE, NULL);
    sendLine(socket, CONTENT_LINE, NULL);
    sendLine(socket, LENGTH_LINE, strLen);
    sendLine(socket, VENDOR_LINE, NULL);

    if (0 == readResponse(socket, "200"))
    {
        char strBuf[RX_SIZE];
        unsigned char strLen, len;
        char *p;
        unsigned char crlf = 0;
        unsigned char ciklen = 0;
        char NCIK[CIK_LENGTH];

        do
        {
            strLen = socket->receive(strBuf, RX_SIZE);
            len = strLen;
            p = strBuf;
            // Find 4 consecutive \r or \n - should be: \r\n\r\n
            while (0 < len && 4 > crlf)
            {
                if ('\r' == *p || '\n' == *p)
                {
                    ++crlf;
                }
                else
                {
                    crlf = 0;
                }
                ++p;
                --len;
            }

            // The body is the CIK
            if (0 < len && 4 == crlf && CIK_LENGTH > ciklen)
            {
                // TODO, be more robust - match Content-Length header value to CIK_LENGTH
                unsigned char need, part;
                need = CIK_LENGTH - ciklen;
                part = need < len ? need : len;
                strncpy(NCIK + ciklen, p, part);
                ciklen += part;
            }
        } while (RX_SIZE == strLen);

        if (CIK_LENGTH == ciklen)
        {
            exosite_meta_write((unsigned char *)NCIK, CIK_LENGTH, META_CIK);
        }
    }
    else
    {
        printf("Activation failed\n");
        getchar();
    }
    socket->close();
}

//*****************************************************************************
//
//! connect_to_exosite
//!
//!  \param  None
//!
//!  \return socket handle
//!
//!  \brief  Establishes a connection with the Exosite API server
//
//*****************************************************************************
long connect_to_exosite(TCPSocketConnection *socket)
{    
    static unsigned char connectRetries = 0;
    long sock;

    if (connectRetries++ > 5)
    {
        connectRetries = 0;
        printf("ERROR %d\r\n", EXO_ERROR_CONNECT);
    }

    const char* ECHO_SERVER_ADDRESS = "173.255.209.28"; //TODO - use DNS or check m2.exosite.com/ip to check for updates
    const int ECHO_SERVER_PORT = 80;
    
    unsigned char server[META_SERVER_SIZE];
    exosite_meta_read(server, META_SERVER_SIZE, META_SERVER);

    sock = socket->connect(ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT);
    if(sock < 0)
    {
        printf("Connection to server failed\n");
        socket->close();
        wait_ms(200);
        return -1;
    }
    else
    {
        connectRetries = 0;
        //printf("ShowUIcode %d\n", EXO_SERVER_CONNECTED);
    }

    // Success
    //printf("success\n");
    return sock;
}


//*****************************************************************************
//
//! readResponse
//!
//!  \param  socket handle, pointer to expected HTTP response code
//!
//!  \return 0 if match, -1 if no match
//!
//!  \brief  Reads first 12 bytes of HTTP response and extracts the 3 byte code
//
//*****************************************************************************
int readResponse(TCPSocketConnection *socket, char * code)
{
    char rxBuf[12];
    unsigned char rxLen;
    rxLen = socket->receive(rxBuf, 12);
//PROBLEM : more than 12 chars are printed 
    printf("rec %s\n", rxBuf);
    if (12 == rxLen && code[0] == rxBuf[9] && code[1] == rxBuf[10] && code[2] == rxBuf[11])
    {
        return 0;
    }

    return -1;
}


//*****************************************************************************
//
//! sendLine
//!
//!  \param  Which line type
//!
//!  \return socket handle
//!
//!  \brief  Sends data out the socket
//
//*****************************************************************************
void sendLine(TCPSocketConnection *socket, unsigned char LINE, char * payload)
{
    char strBuf[80];
    unsigned char strLen = 0;

    switch(LINE)
    {
    case CIK_LINE:
        sprintf(strBuf, "X-Exosite-CIK: %s\r\n", activeCIK);    
        strLen = strlen(strBuf);
        //strLen = 57;
        //memcpy(strBuf,STR_CIK_HEADER,strLen);
        //exosite_meta_read((unsigned char *)&strBuf[strLen], CIK_LENGTH, META_CIK);
        //strLen += CIK_LENGTH;
        //memcpy(&strBuf[strLen],STR_CRLF, 2);
        //strLen += 2;
        break;
    case HOST_LINE:
        strLen = 28;
        memcpy(strBuf,STR_HOST,strLen);
        strBuf[strLen] = NULL;
        break;
    case CONTENT_LINE:
        strLen = 64;
        memcpy(strBuf,STR_CONTENT,strLen);
        strBuf[strLen] = NULL;
        break;
    case ACCEPT_LINE:
        strLen = 58;
        memcpy(strBuf,STR_ACCEPT,strLen);
        memcpy(&strBuf[strLen],payload, strlen(payload));
        strLen += strlen(payload);
        break;
    case LENGTH_LINE: // Content-Length: NN
        strLen = 16;
        memcpy(strBuf,STR_CONTENT_LENGTH,strLen);
        memcpy(&strBuf[strLen],payload, strlen(payload));
        strLen += strlen(payload);
        memcpy(&strBuf[strLen],STR_CRLF, 2);
        strLen += 2;
        memcpy(&strBuf[strLen],STR_CRLF, 2);
        strLen += 2;
        strBuf[strLen] = NULL;
        break;
    case GETDATA_LINE:
        strLen = 24;
        memcpy(strBuf,STR_GET_URL,strLen);
        memcpy(&strBuf[strLen],payload, strlen(payload));
        strLen += strlen(payload);
        memcpy(&strBuf[strLen],STR_HTTP, 12);
        strLen += 12;
        break;
    case VENDOR_LINE:
        strLen = strlen(STR_VENDOR);
        memcpy(strBuf, STR_VENDOR, strLen);
        exosite_meta_read((unsigned char *)&strBuf[strLen], META_UUID_SIZE, META_UUID);
        strLen += META_UUID_SIZE;
        strBuf[strLen] = NULL;
        break;
    case POSTDATA_LINE:
        strLen = 5;
        memcpy(strBuf,"POST ", strLen);
        memcpy(&strBuf[strLen],payload, strlen(payload));
        strLen += strlen(payload);
        memcpy(&strBuf[strLen],STR_HTTP, 12);
        strLen += 12;
        strBuf[strLen] = NULL;
        break;
    case EMPTY_LINE:
        strLen = 2;
        memcpy(strBuf,STR_CRLF,strLen);
        break;
    default:
        break;
    }
    //printf("sendLine: %s\n", strBuf);
    socket->send_all(strBuf, strLen);
    wifi._event.hci_unsolicited_event_handler();
    return;
}

//*****************************************************************************
//
//! exosite_meta_write
//!
//!  \param  write_buffer - string buffer containing info to write to meta;
//!          srcBytes - size of string in bytes; element - item from
//!          MetaElements enum.
//!
//!  \return None
//!
//!  \brief  Writes specific meta information to meta memory.
//
//*****************************************************************************
void exosite_meta_write(unsigned char * write_buffer, unsigned short srcBytes, unsigned char element)
{
    exosite_meta * meta_info = 0;

    //TODO - do not write if the data already there is identical...

    switch (element)
    {
        case META_CIK:
            if (srcBytes > META_CIK_SIZE) return;
            memcpy((char *)(exo_meta + (int)meta_info->cik), write_buffer, srcBytes); //store CIK
            break;
        case META_SERVER:
            if (srcBytes > META_SERVER_SIZE) return;
            memcpy((char *)(exo_meta + (int)meta_info->server), write_buffer, srcBytes); //store server IP
            break;
        case META_MARK:
            if (srcBytes > META_MARK_SIZE) return;
            memcpy((char *)(exo_meta + (int)meta_info->mark), write_buffer, srcBytes); //store exosite mark
            break;
        case META_UUID:
            if (srcBytes > META_UUID_SIZE) return;
            memcpy((char *)(exo_meta + (int)meta_info->uuid), write_buffer, srcBytes); //store UUID
            break;
        case META_MFR:
            if (srcBytes > META_MFR_SIZE) return;
            memcpy((char *)(exo_meta + (int)meta_info->mfr), write_buffer, srcBytes); //store manufacturing info
            break;
        case META_NONE:
        default:
            break;
    }
    return;
}


//*****************************************************************************
//
//! exosite_meta_read
//!
//!  \param  read_buffer - string buffer to receive element data; destBytes -
//!          size of buffer in bytes; element - item from MetaElements enum.
//!
//!  \return None
//!
//!  \brief  Writes specific meta information to meta memory.
//
//*****************************************************************************
void exosite_meta_read(unsigned char * read_buffer, unsigned short destBytes, unsigned char element)
{
    exosite_meta * meta_info = 0;

    switch (element)
    {
        case META_CIK:
            if (destBytes < META_CIK_SIZE) return;
            memcpy(read_buffer, (char *)(exo_meta + (int)meta_info->cik), destBytes); //read CIK
            break;
        case META_SERVER:
            if (destBytes < META_SERVER_SIZE) return;
            memcpy(read_buffer, (char *)(exo_meta + (int)meta_info->server), destBytes); //read server IP
            break;
        case META_MARK:
            if (destBytes < META_MARK_SIZE) return;
            memcpy(read_buffer, (char *)(exo_meta + (int)meta_info->mark), destBytes); //read exosite mark
            break;
        case META_UUID:
            if (destBytes < META_UUID_SIZE) return;
            memcpy(read_buffer, (char *)(exo_meta + (int)meta_info->uuid), destBytes); //read exosite mark
            break;
        case META_MFR:
            if (destBytes < META_MFR_SIZE) return;
            memcpy(read_buffer, (char *)(exo_meta + (int)meta_info->mfr), destBytes); //read exosite mark
            break;
        case META_NONE:
            default:
            break;
    }
    return;
}