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

Dependencies:   mbed CC3000_Hostdriver TEMT6200 TSI Wi-Go_eCompass_Lib_V3 WiGo_BattCharger

Fork of CC3000_Simple_Socket by Frank Vannieuwkerke

Information

This demo uses the old HostDriver.
A newer release using the mbed socket compatible API HostDriver is available at Wi-Go_IOT_Demo_MKII.

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

  • We need a large amount of free RAM for the eCompass library:
    Before compiling the code, check if CC3000_MAXIMAL_RX_SIZE is set to (511 + 1) in cc3000_common.h.
  • 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
PurpleSmartConfig
BlueWebServer
RedExosite Data Client
GreenAndroid Server

Swipe your index finger across the slider pad, the RGB LED color will change at approximately 25% 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/exosite.cpp

Committer:
frankvnk
Date:
2013-12-11
Revision:
16:dceb9f5108f7
Parent:
6:7c06ad22f206

File content as of revision 16:dceb9f5108f7:

/*****************************************************************************
*
*  exosite.c - Exosite cloud communications.
*  Copyright (C) 2012 Exosite LLC
*
*  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 "doTCPIP.h"
#include "exosite.h"
#include "exosite_hal.h"
#include "exosite_meta.h"
#include "strlib.h"

extern userFS_t userFS;

//local defines
#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(void);
void init_mac_address(unsigned char if_nbr);
void update_m2ip(void);
int readResponse(long socket, char * expectedCode);
long connect_to_exosite(void);
void sendLine(long socket, unsigned char LINE, char * payload);

// global functions
int Exosite_Write(char * pbuf, unsigned char bufsize);
int Exosite_Read(char * palias, char * pbuf, unsigned char bufsize);
int Exosite_Init(void);
int Exosite_ReInit(void);
void Exosite_SetCIK(char * pCIK);

// externs
extern char *itoa(int n, char *s, int b);
extern char activeCIK[];
extern int server_running;

// global variables
static unsigned char exositeWriteFailures = 0;


//*****************************************************************************
//
//! Exosite_Init
//!
//!  \param  None
//!
//!  \return 0 success; -1 failure
//!
//!  \brief  The function initializes the cloud connection to Exosite
//
//*****************************************************************************
int Exosite_Init(void)
{
    exosite_meta_init();          //always initialize our meta structure
    init_mac_address(IF_WIFI);    //always check to see if the MAC is up to date

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

    return Exosite_ReInit();
}


//*****************************************************************************
//
//! Exosite_ReInit
//!
//!  \param  None
//!
//!  \return 0 success; -1 failure
//!
//!  \brief  Called after Init has been ran in the past, but maybe comms were
//!          down and we have to keep trying...
//
//*****************************************************************************
int Exosite_ReInit(void)
{
    int i;
    char tempCIK[CIK_LENGTH];
    update_m2ip();        //check our IP api to see if the old IP is advertising a new one
    activate_device();    //the moment of truth - can this device provision with the Exosite cloud?...

    //sanity check on the CIK
    exosite_meta_read((unsigned char *)tempCIK, CIK_LENGTH, META_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++) userFS.CIK[i] = tempCIK[i];
    userFS.validCIK = 1;
    nvmem_write( NVMEM_USER_FILE_1_FILEID, sizeof(userFS), 0, (unsigned char *) &userFS);
    return 0;
}


//*****************************************************************************
//
//! Exosite_SetCIK
//!
//!  \param  pointer to CIK
//!
//!  \return None
//!
//!  \brief  Programs a new CIK to flash / non volatile
//
//*****************************************************************************
void
Exosite_SetCIK(char * pCIK)
{
    exosite_meta_write((unsigned char *)pCIK, CIK_LENGTH, META_CIK);
}


//*****************************************************************************
//
//! 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(char * pbuf, unsigned char bufsize)
{
    char strBuf[10];
    long sock = -1;

    sock = connect_to_exosite();
    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(sock, POSTDATA_LINE, "/onep:v1/stack/alias");
    sendLine(sock, HOST_LINE, NULL);
    sendLine(sock, CIK_LINE, NULL);
    sendLine(sock, CONTENT_LINE, NULL);
    sendLine(sock, LENGTH_LINE, strBuf);
    //printf("DAta=%s\n", pbuf);
    exoHAL_SocketSend(sock, pbuf, bufsize); //alias=value

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

    exoHAL_SocketClose(sock);

    if (exositeWriteFailures > 5)
    {
        // sometimes transport connect works even if no connection...
        exoHAL_HandleError(EXO_ERROR_WRITE);
    }

    if (!exositeWriteFailures)
    {
        exoHAL_ShowUIMessage(EXO_CLIENT_RW);
        return 0; // success
    }
    return 0;
}    


//*****************************************************************************
//
//! Exosite_Read
//!
//!  \param  palias - string, name of the datasource alias to read from
//!          pbuf - read buffer to put the read response into
//!          buflen - size of the input buffer
//!
//!  \return number of bytes read
//!
//!  \brief  The function reads data from Exosite
//
//*****************************************************************************
int Exosite_Read(char * palias, char * pbuf, unsigned char buflen)
{
    unsigned char strLen, len, vlen;
    char *p, *pcheck;
    long sock = -1;

    while (sock < 0)
    sock = connect_to_exosite();

// This is an example read GET
//  s.send('GET /api:v1/stack/alias?temp HTTP/1.1\r\n')
//  s.send('Host: m2.exosite.com\r\n')
//  s.send('X-Exosite-CIK: 5046454a9a1666c3acfae63bc854ec1367167815\r\n')
//  s.send('Accept: application/x-www-form-urlencoded; charset=utf-8\r\n\r\n')

    sendLine(sock, GETDATA_LINE, palias);
    sendLine(sock, HOST_LINE, NULL);
    sendLine(sock, CIK_LINE, NULL);
    sendLine(sock, ACCEPT_LINE, "\r\n");

    pcheck = palias;
    vlen = 0;

    if (0 == readResponse(sock, "200"))
    {
        char strBuf[RX_SIZE];
        unsigned char crlf = 0;
        exoHAL_ShowUIMessage(EXO_CLIENT_RW);
        do
        {
            strLen = exoHAL_SocketRecv(sock, 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 "<key>=<value>"
            if (0 < len && 4 == crlf && buflen > vlen)
            {
                // Move past "<key>"
                while (0 < len && 0 != *pcheck)
                {
                    if (*pcheck == *p)
                    {
                        ++pcheck;
                    }
                    else
                    {
                        pcheck = palias;
                    }
                    ++p;
                    --len;
                }

                // Match '=',  we should now have '<key>='
                if (0 < len && 0 == *pcheck && '=' == *p)
                {
                    ++p;
                    --len;
                }

                // read in the rest of the body as the value
                while (0 < len && buflen > vlen)
                {
                    pbuf[vlen++] = *p++;
                    --len;
                }
            }
        } while (RX_SIZE == strLen);
    }
    exoHAL_SocketClose(sock);
    return vlen;
}


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

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

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

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

    if (0 == readResponse(sock, "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 = exoHAL_SocketRecv(sock, 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_SetCIK(NCIK);
        }
    }
    else
    {
        printf("Activation failed\n");
        getchar();
    }
  exoHAL_SocketClose(sock);
}


//*****************************************************************************
//
//! update_m2ip
//!
//!  \param  none
//!
//!  \return none
//!
//!  \brief  Checks /ip API to see if a new server IP address should be used
//
//*****************************************************************************
void update_m2ip(void)
{
    //TODO - stubbed out
    return;
}


//*****************************************************************************
//
//! init_mac_address
//!
//!  \param  Interface Number (1 - WiFi)
//!
//!  \return None
//!
//!  \brief  Reads the MAC address from the hardware
//
//*****************************************************************************
void init_mac_address(unsigned char if_nbr)
{
    const char hex[] = "0123456789abcdef";
    char strmac[18];
    unsigned char addr_hw[MAC_LEN];

    exoHAL_ReadHWMAC(if_nbr, addr_hw);
    printf("MAC=%08x\n", addr_hw);
    strmac[0]  = hex[addr_hw[0] >> 4];
    strmac[1]  = hex[addr_hw[0] & 15];
    strmac[2]  = ':';
    
    strmac[3]  = hex[addr_hw[1] >> 4];
    strmac[4]  = hex[addr_hw[1] & 15];
    strmac[5]  = ':';

    strmac[6]  = hex[addr_hw[2] >> 4];
    strmac[7]  = hex[addr_hw[2] & 15];
    strmac[8]  = ':';

    strmac[9]  = hex[addr_hw[3] >> 4];
    strmac[10]  = hex[addr_hw[3] & 15];
    strmac[11]  = ':';

    strmac[12]  = hex[addr_hw[4] >> 4];
    strmac[13]  = hex[addr_hw[4] & 15];
    strmac[14]  = ':';

    strmac[15] = hex[addr_hw[5] >> 4];
    strmac[16] = hex[addr_hw[5] & 15];
    strmac[17] = NULL;
    printf("\n\nMAC= %s\n\n", strmac);
    exosite_meta_write((unsigned char *)strmac, 17, META_UUID);
}


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

    if (connectRetries++ > 5)
    {
        connectRetries = 0;
        exoHAL_HandleError(EXO_ERROR_CONNECT);
    }

    sock = exoHAL_SocketOpenTCP();
    //printf("socket=%d\n", sock);
    if (sock == -1)
    {
        //wlan_stop();  //TODO - if we stop the wlan, we have to recover somehow...
        exoHAL_MSDelay(100);
        return -1;
    }

    if (exoHAL_ServerConnect(sock) < 0)  // Try to connect
    {
        // TODO - the typical reason the connect doesn't work is because
        // something was wrong in the way the CC3000 was initialized (timing, bit
        // error, etc...). There may be a graceful way to kick th CC3000 module
        // back into gear at the right state, but for now, we just
        // return and let the caller retry us if they want
        printf("Connection to server failed\n");
        exoHAL_SocketClose(sock);
        exoHAL_MSDelay(100);
        return -1;
    }
    else
    {
        connectRetries = 0;
        exoHAL_ShowUIMessage(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(long socket, char * code)
{
    char rxBuf[12];
    unsigned char rxLen;
    rxLen = exoHAL_SocketRecv(socket, rxBuf, 12);
    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(long 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);
    exoHAL_SocketSend(socket, strBuf, strLen);
    return;
}