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.

Files at this revision

API Documentation at this revision

Comitter:
frankvnk
Date:
Sat Sep 07 15:41:49 2013 +0000
Parent:
2:13ced2cb5933
Child:
4:aa85f9c11a41
Commit message:
First release

Changed in this revision

CC3000_Hostdriver.lib Show diff for this revision Revisions of this file
Drivers/CC3000_Hostdriver.lib Show annotated file Show diff for this revision Revisions of this file
Drivers/FRDM_MMA8451Q.lib Show annotated file Show diff for this revision Revisions of this file
Drivers/MAG3110.lib Show annotated file Show diff for this revision Revisions of this file
Drivers/MPL3115A2.lib Show annotated file Show diff for this revision Revisions of this file
Drivers/TEMT6200.lib Show annotated file Show diff for this revision Revisions of this file
Drivers/TSI.lib Show annotated file Show diff for this revision Revisions of this file
Drivers/Wi-Go_eCompass_Lib_V3.lib Show annotated file Show diff for this revision Revisions of this file
Drivers/WiGo_BattCharger.lib Show annotated file Show diff for this revision Revisions of this file
Utilities/strlib.cpp Show annotated file Show diff for this revision Revisions of this file
Utilities/strlib.h Show annotated file Show diff for this revision Revisions of this file
Webserver/AvnetHTML.h Show annotated file Show diff for this revision Revisions of this file
Webserver/demo.cpp Show annotated file Show diff for this revision Revisions of this file
Webserver/demo.h Show annotated file Show diff for this revision Revisions of this file
Webserver/exosite.cpp Show annotated file Show diff for this revision Revisions of this file
Webserver/exosite.h Show annotated file Show diff for this revision Revisions of this file
Webserver/exosite_hal.cpp Show annotated file Show diff for this revision Revisions of this file
Webserver/exosite_hal.h Show annotated file Show diff for this revision Revisions of this file
Webserver/exosite_meta.cpp Show annotated file Show diff for this revision Revisions of this file
Webserver/exosite_meta.h Show annotated file Show diff for this revision Revisions of this file
Webserver/httpserver.cpp Show annotated file Show diff for this revision Revisions of this file
Webserver/httpserver.h Show annotated file Show diff for this revision Revisions of this file
Webserver/run_exosite.cpp Show annotated file Show diff for this revision Revisions of this file
Webserver/run_exosite.h Show annotated file Show diff for this revision Revisions of this file
cc3000.cpp Show annotated file Show diff for this revision Revisions of this file
doTCPIP.cpp Show annotated file Show diff for this revision Revisions of this file
doTCPIP.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/CC3000_Hostdriver.lib	Sun Aug 18 07:06:20 2013 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://mbed.org/users/frankvnk/code/CC3000_Hostdriver/#8db50def96e5
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/CC3000_Hostdriver.lib	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/frankvnk/code/CC3000_Hostdriver/#8db50def96e5
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/FRDM_MMA8451Q.lib	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/clemente/code/FRDM_MMA8451Q/#13e2af71e2cf
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/MAG3110.lib	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/SomeRandomBloke/code/MAG3110/#cf40601402b7
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/MPL3115A2.lib	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/clemente/code/MPL3115A2/#59e9ba115d0a
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/TEMT6200.lib	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/frankvnk/code/TEMT6200/#5d1118cb5702
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/TSI.lib	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/TSI/#1a60ef257879
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/Wi-Go_eCompass_Lib_V3.lib	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/frankvnk/code/Wi-Go_eCompass_Lib_V3/#6296487369d8
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Drivers/WiGo_BattCharger.lib	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/frankvnk/code/WiGo_BattCharger/#fb966ae74766
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Utilities/strlib.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,193 @@
+/*****************************************************************************
+*
+*  strlib.c - String Library functions implementation
+*  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 <stdlib.h>
+#include <stdio.h>
+#include <string.h>*/
+#include "mbed.h"
+#include "strlib.h"
+
+//*****************************************************************************
+//
+//! \brief   Integer to ASCII
+//!
+//! \param  n is the number to be converted to ASCII
+//! \param s is a pointer to an array where the ASCII string will be placed
+//! \param b is the base (10 for decimal)
+//!
+//! \return none
+//
+//*****************************************************************************
+char *itoa(int n, char *s, int b)
+{
+    const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
+    unsigned int i = 0;
+    int sign;
+    
+    if ((sign = n) < 0)
+        n = -n;
+
+    do {
+        s[i++] = digits[n % b];
+    } while ((n /= b) > 0);
+
+    if (sign < 0)
+        s[i++] = '-';
+    s[i] = '\0';
+
+    return strrev(s);
+}
+
+//*****************************************************************************
+//
+//! \brief   Reverses a string
+//!
+//! \param  str is a pointer to the string to be reversed
+//!
+//! \return none
+//
+//*****************************************************************************
+char *strrev(char *str)
+{
+    char *p1, *p2;
+
+    if (!str || !*str)
+        return str;
+
+    for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) {
+        *p1 ^= *p2;
+        *p2 ^= *p1;
+        *p1 ^= *p2;
+    }
+
+    return str;
+}
+
+//*****************************************************************************
+//
+//! atoc
+//!
+//! \param  none
+//!
+//! \return none
+//!
+//! \brief  Convert nibble to hexdecimal from ASCII
+//
+//*****************************************************************************
+unsigned char
+atoc(char data)
+{
+    unsigned char ucRes;
+
+    if ((data >= 0x30) && (data <= 0x39))
+    {
+        ucRes = data - 0x30;
+    }
+    else
+    {
+        if (data == 'a')
+        {
+            ucRes = 0x0a;;
+        }
+        else if (data == 'b')
+        {
+            ucRes = 0x0b;
+        }
+        else if (data == 'c')
+        {
+            ucRes = 0x0c;
+        }
+        else if (data == 'd')
+        {
+            ucRes = 0x0d;
+        }
+        else if (data == 'e')
+        {
+            ucRes = 0x0e;
+        }
+        else if (data == 'f')
+        {
+            ucRes = 0x0f;
+        }
+    }
+
+
+    return ucRes;
+}
+
+
+//*****************************************************************************
+//
+//! atoshort
+//!
+//! \param  none
+//!
+//! \return none
+//!
+//! \brief  Convert 2 nibbles in ASCII into a short number
+//
+//*****************************************************************************
+
+unsigned short
+atoshort(char b1, char b2)
+{
+    unsigned short usRes;
+
+    usRes = (atoc(b1)) * 16 | atoc(b2);
+
+    return usRes;
+}
+
+//*****************************************************************************
+//
+//! ascii_to_char
+//!
+//! \param  none
+//!
+//! \return none
+//!
+//! \brief  Convert 2 bytes in ASCII into one character
+//
+//*****************************************************************************
+
+unsigned char
+ascii_to_char(char b1, char b2)
+{
+    unsigned char ucRes;
+
+    ucRes = (atoc(b1)) << 4 | (atoc(b2));
+
+    return ucRes;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Utilities/strlib.h	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,55 @@
+/*****************************************************************************
+*
+*  strlib.h - String Library functions definitions
+*
+*  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.
+*
+*****************************************************************************/
+
+#ifndef STRLIB_H
+#define STRLIB_H
+
+#ifdef    __cplusplus
+extern "C" {
+#endif
+
+char *itoa(int n, char *s, int b);
+char *strrev(char *str);
+unsigned char atoc(char data);
+unsigned short atoshort(char b1, char b2);
+unsigned char ascii_to_char(char b1, char b2);
+
+#ifdef    __cplusplus
+}
+#endif // __cplusplus
+
+#endif // STRLIB_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/AvnetHTML.h	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,110 @@
+#ifndef AVNET_HTML_H
+#define AVNET_HTML_H
+
+#ifdef    __cplusplus
+extern "C" {
+#endif
+
+// ---------- HTML Webpage Content is defined here ----------
+// Caution! Field labels and spaces in the HTML should not be edited without making corresponding changes in the C-code!
+char index[] = {
+"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html lang=\"en-US\">"
+"<head>"
+"<META content=\"text/html;charset=ISO-8859-1\" http-equiv=\"content-type\">"
+"<title>Wi-Go WebServer</title>"
+//"<META HTTP-EQUIV=\"refresh\" content=\"2\">"   // Uncomment for auto-refresh every 2 seconds
+"</head>"
+
+"<body><div style=\"text-align: left\"><font size=\"6\" color=\"Red\" face=\"Tahoma\">"
+"<b>Avnet Wi-Go Webserver</b></font>"
+"<hr size=3 width=600 align=left>"
+"<font size=\"5\" color=\"Red\" face=\"Tahoma\"><b>LED RGB color select...</b></font>"
+
+//"<font size=\"5\" color=\"Black\" face=\"monospace\"></font>" 
+"<form method=\"get\" action=\"index.html\" name=\"server\">"
+"<input name=\"ledCon\" type=\"submit\" value=\"-Red-\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
+"<input name=\"ledCon\" type=\"submit\" value=\"Green\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
+"<input name=\"ledCon\" type=\"submit\" value=\"Blue-\">"
+"</form></div>" 
+
+"<hr size=3 width=600 align=left>"
+"<div style=\"text-align: left\"><font size=\"5\" color=\"Red\" face=\"Tahoma\">"
+"<b>Navigation Sensors</b></font></div>"
+
+"<div style=\"text-align:left\"><font size=\"4\" color=\"Black\" face=\"monospace\"><b>"
+"Acceleration(G)..                                       <br>"
+"Magnetometer(uT).                                       <br>"
+"eCompass.........                                         <br>"
+"Altitude.........                <br></b></font></div>"
+
+"<hr size=3 width=600 align=left>"
+"<div style=\"text-align: left\"><font size=\"5\" color=\"Red\" face=\"Tahoma\">"
+"<b>Status and Control</b></font></div>"
+
+"<div style=\"text-align:left\"><font size=\"4\" color=\"Black\" face=\"monospace\"><b>"
+"Battery Voltage..       <br>"
+"Ambient Light....       <br>"
+"Temperature......          <br>"
+"Slider Position..          <br>"
+"Page Views.......        </b></font>"
+"<hr size=3 width=600 align=left>"
+"</body></html>"};  // delete this line if adding the SVG code below...
+
+// Optional section 1: Full SVG graphic example: Uncomment this section to display the standard Wi-Fi logo in lower area of webpage
+// Browsers supporting SVG: Chrome and FireFox (all versions), Android (3.0 onwards), Safari (5.0 onwards), IE (9.0 onwards?)
+/*
+"<!--[if !IE]><!-->"  // This prevents SVG content being sent to Internet Explorer
+"<svg>" 
+"xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" height=\"175.49\" width=\"400\""
+"xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\""
+"xmlns:cc=\"http://creativecommons.org/ns#\""
+"xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
+"<defs></defs>"
+"<metadata>"
+"<rdf:RDF>"
+"<cc:Work rdf:about=\"\">"
+"<dc:format>image/svg+xml</dc:format>"
+"<dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>"
+"<dc:title/>"
+"</cc:Work>"
+"</rdf:RDF>"
+"</metadata>"
+"<g transform=\"translate(-309.85919,-343.20843)\">"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,576.05074,474.82936)\">"
+"<path fill-rule=\"nonzero\" fill=\"#231f20\" d=\"m0,0c4.977,0,9.049,4.077,9.049,9.049v5.389c0,4.973-4.072,9.048-9.049,9.048h-35.433c-4.973,0-9.049-4.075-9.049-9.048v-5.389c0-4.972,4.076-9.049,9.049-9.049\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,514.3818,441.01715)\">"
+"<path fill-rule=\"nonzero\" fill=\"#FFF\" d=\"m0,0,0,5.389c0,4.072,3.314,7.32,7.32,7.32h9.187c4.007,0,7.253-3.248,7.253-7.32v-5.389c0-4.005-3.246-7.32-7.253-7.32h-20.239c2.281,1.656,3.732,4.284,3.732,7.32\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,469.99257,451.60916)\">"
+"<path fill-rule=\"nonzero\" fill=\"#FFF\" d=\"m0,0-3.043,0-0.55,2.56c-0.345,1.794-0.692,4.005-0.761,4.833-0.069-0.828-0.416-3.039-0.825-4.833l-0.555-2.56h-2.968l-2.767,11.748h3.317l0.343-2.004c0.276-1.66,0.556-3.659,0.695-5.044,0.136,1.385,0.481,3.384,0.896,5.044l0.412,2.004h2.972l0.413-2.004c0.348-1.66,0.693-3.659,0.833-5.044,0.136,1.385,0.482,3.384,0.757,5.044l0.278,2.004h3.313\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,491.40819,416.23898)\">"
+"<path fill-rule=\"nonzero\" fill=\"#FFF\" d=\"m0,0c-0.968,0-1.727,0.553-1.727,1.451,0,0.899,0.759,1.45,1.727,1.45,1.036,0,1.796-0.551,1.796-1.45,0-0.898-0.76-1.451-1.796-1.451m-1.521-0.968,3.0401,0,0-8.4984-3.0401,0,0,8.4984z\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,541.9845,418.05849)\">"
+"<path fill-rule=\"nonzero\" fill=\"#231f20\" d=\"m0,0,0-2.618,6.22,0,0-2.767-6.22,0,0-3.593-3.247,0,0,11.748,10.156,0,0-2.77\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,580.44446,416.23898)\">"
+"<path fill-rule=\"nonzero\" fill=\"#231f20\" d=\"m0,0c-0.97,0-1.727,0.553-1.727,1.451,0,0.899,0.757,1.45,1.727,1.45,1.035,0,1.797-0.551,1.797-1.45,0-0.898-0.762-1.451-1.797-1.451m-1.521-0.968,3.0371,0,0-8.4984-3.0371,0,0,8.4984z\"/>"
+"</g>"
+"</g>"
+"</svg>"
+"<!--<![endif]-->"  
+*/                // end of conditional inclusion of SVG graphic (excludes Internet Explorer browser)
+// ---- End of Wi-Fi logo SVG image definition ----
+
+// Optional section 2: Simple SVG graphic example: Uncomment this section to generate a filled circle  in lower area of webpage
+// eg. Could use to indicate RGB LED color (with addition of applicable C-code to dynamically update specified "fill=" color)
+/*
+"<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">"
+"<circle cx=\"155\" cy=\"22\" r=\"20\" stroke=\"DimGrey\" stroke-width=\"2\" fill=\"Red\"/>"
+"</svg>"
+"</body></html>"};
+*/
+
+#ifdef    __cplusplus
+}
+#endif // __cplusplus
+#endif // AVNET_HTML_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/demo.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,308 @@
+
+/*****************************************************************************
+* Dynamic HTML string handlers: 
+* Nine dynamic HTML fields are updated on browser refresh or button press: 
+*     Acceleration
+*     Magnetometer                  
+*     eCompass      
+*     Altitude
+*     Battery Voltage
+*     Ambient Light
+*     Temperature                   
+*     Slider Position       
+*     Page Views
+*
+* CGI HTML forms: 
+* Three CGI form inputs are used to submit data from browser to the Server: 
+* On screen buttons: -Red-, Green, Blue (for control of RGB LED output color) 
+*
+* myindex[] contains the HTML string that defines the webpage that is served
+* Use an online HTML validator to verify HTML code before running it on the MCU
+* eg. 
+* www.w3schools.com/tags/tryit.asp?filename=tryhtml_div_test
+* www.onlinewebcheck.com/check.php?adv=1
+* Note: Before checking the HTML in one of these validators, 
+* strip-out all “\” backslash characters (using search & replace)
+*
+* Webserver code is based on TI's CC3000 Simple HTTP Webserver:  
+* http://processors.wiki.ti.com/index.php/CC3000_Wi-Fi_for_MCU
+* 
+* More detail on implementation of this Webserver App is available here:
+* http://processors.wiki.ti.com/index.php/CC3000_HTTP_Server_Demo_Session
+*
+* A more advanced Webserver and Client App is also available from TI for the CC3000:
+* http://processors.wiki.ti.com/index.php/CC3000_Web_Server_Client_Application
+* (at this time not yet ported to Kinetis-L as the host processor)
+* 
+******************************************************************************
+*
+*  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 "demo.h"
+#include "doTCPIP.h"
+#include "httpserver.h"
+#include "AvnetHTML.h"
+
+extern void getAccelXYZ_Str(char * str);   // Get dominant Accelerometer Axis value 
+extern void getTemperatureStr(char * str); // Get Temperature
+extern void getTSI_sliderStr(char * str) ; // Get TSI Slider position 
+extern void getAltitudeStr(char * str);    // Get Altitude 
+extern void getCompassStr(char * str) ;    // Get eCompass 
+extern void getM3110Str(char * str);
+extern void initTCPIP(void);
+
+extern unsigned short adc_sample3;
+
+void errorHandler(void);
+
+// Setup the functions to handle our CGI parameters
+cgi_handler pHandlers;
+dyn_html_handler htmlHandlers;
+
+extern tNetappIpconfigRetArgs ipinfo2;
+
+extern axis6_t axis6;
+extern int server_running;
+
+/*
+// ---------- HTML Webpage Content is defined here ----------
+// Caution! Field labels and spaces in the HTML should not be edited without making corresponding changes in the C-code!
+char index[] = {
+"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html lang=\"en-US\">"
+"<head>"
+"<META content=\"text/html;charset=ISO-8859-1\" http-equiv=\"content-type\">"
+"<title>Wi-Go WebServer</title>"
+//"<META HTTP-EQUIV=\"refresh\" content=\"2\">"   // Uncomment for auto-refresh every 2 seconds
+"</head>"
+
+"<body><div style=\"text-align: left\"><font size=\"6\" color=\"Red\" face=\"Tahoma\">"
+"<b>Avnet Wi-Go Webserver</b></font>"
+"<hr size=3 width=600 align=left>"
+"<font size=\"5\" color=\"Red\" face=\"Tahoma\"><b>LED RGB color select...</b></font>"
+
+//"<font size=\"5\" color=\"Black\" face=\"monospace\"></font>" 
+"<form method=\"get\" action=\"index.html\" name=\"server\">"
+"<input name=\"ledCon\" type=\"submit\" value=\"-Red-\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
+"<input name=\"ledCon\" type=\"submit\" value=\"Green\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
+"<input name=\"ledCon\" type=\"submit\" value=\"Blue-\">"
+"</form></div>" 
+
+"<hr size=3 width=600 align=left>"
+"<div style=\"text-align: left\"><font size=\"5\" color=\"Red\" face=\"Tahoma\">"
+"<b>Navigation Sensors</b></font></div>"
+
+"<div style=\"text-align:left\"><font size=\"4\" color=\"Black\" face=\"monospace\"><b>"
+"Acceleration(G)..                                       <br>"
+"Magnetometer(uT).                                       <br>"
+"eCompass.........                                         <br>"
+"Altitude.........                <br></b></font></div>"
+
+"<hr size=3 width=600 align=left>"
+"<div style=\"text-align: left\"><font size=\"5\" color=\"Red\" face=\"Tahoma\">"
+"<b>Status and Control</b></font></div>"
+
+"<div style=\"text-align:left\"><font size=\"4\" color=\"Black\" face=\"monospace\"><b>"
+"Battery Voltage..       <br>"
+"Ambient Light....       <br>"
+"Temperature......          <br>"
+"Slider Position..          <br>"
+"Page Views.......        </b></font>"
+"<hr size=3 width=600 align=left>"
+"</body></html>"};  // delete this line if adding the SVG code below...
+*/
+// Optional section 1: Full SVG graphic example: Uncomment this section to display the standard Wi-Fi logo in lower area of webpage
+// Browsers supporting SVG: Chrome and FireFox (all versions), Android (3.0 onwards), Safari (5.0 onwards), IE (9.0 onwards?)
+/*
+"<!--[if !IE]><!-->"  // This prevents SVG content being sent to Internet Explorer
+"<svg>" 
+"xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" height=\"175.49\" width=\"400\""
+"xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\""
+"xmlns:cc=\"http://creativecommons.org/ns#\""
+"xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
+"<defs></defs>"
+"<metadata>"
+"<rdf:RDF>"
+"<cc:Work rdf:about=\"\">"
+"<dc:format>image/svg+xml</dc:format>"
+"<dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>"
+"<dc:title/>"
+"</cc:Work>"
+"</rdf:RDF>"
+"</metadata>"
+"<g transform=\"translate(-309.85919,-343.20843)\">"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,576.05074,474.82936)\">"
+"<path fill-rule=\"nonzero\" fill=\"#231f20\" d=\"m0,0c4.977,0,9.049,4.077,9.049,9.049v5.389c0,4.973-4.072,9.048-9.049,9.048h-35.433c-4.973,0-9.049-4.075-9.049-9.048v-5.389c0-4.972,4.076-9.049,9.049-9.049\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,514.3818,441.01715)\">"
+"<path fill-rule=\"nonzero\" fill=\"#FFF\" d=\"m0,0,0,5.389c0,4.072,3.314,7.32,7.32,7.32h9.187c4.007,0,7.253-3.248,7.253-7.32v-5.389c0-4.005-3.246-7.32-7.253-7.32h-20.239c2.281,1.656,3.732,4.284,3.732,7.32\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,469.99257,451.60916)\">"
+"<path fill-rule=\"nonzero\" fill=\"#FFF\" d=\"m0,0-3.043,0-0.55,2.56c-0.345,1.794-0.692,4.005-0.761,4.833-0.069-0.828-0.416-3.039-0.825-4.833l-0.555-2.56h-2.968l-2.767,11.748h3.317l0.343-2.004c0.276-1.66,0.556-3.659,0.695-5.044,0.136,1.385,0.481,3.384,0.896,5.044l0.412,2.004h2.972l0.413-2.004c0.348-1.66,0.693-3.659,0.833-5.044,0.136,1.385,0.482,3.384,0.757,5.044l0.278,2.004h3.313\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,491.40819,416.23898)\">"
+"<path fill-rule=\"nonzero\" fill=\"#FFF\" d=\"m0,0c-0.968,0-1.727,0.553-1.727,1.451,0,0.899,0.759,1.45,1.727,1.45,1.036,0,1.796-0.551,1.796-1.45,0-0.898-0.76-1.451-1.796-1.451m-1.521-0.968,3.0401,0,0-8.4984-3.0401,0,0,8.4984z\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,541.9845,418.05849)\">"
+"<path fill-rule=\"nonzero\" fill=\"#231f20\" d=\"m0,0,0-2.618,6.22,0,0-2.767-6.22,0,0-3.593-3.247,0,0,11.748,10.156,0,0-2.77\"/>"
+"</g>"
+"<g transform=\"matrix(3.7361528,0,0,-3.7361528,580.44446,416.23898)\">"
+"<path fill-rule=\"nonzero\" fill=\"#231f20\" d=\"m0,0c-0.97,0-1.727,0.553-1.727,1.451,0,0.899,0.757,1.45,1.727,1.45,1.035,0,1.797-0.551,1.797-1.45,0-0.898-0.762-1.451-1.797-1.451m-1.521-0.968,3.0371,0,0-8.4984-3.0371,0,0,8.4984z\"/>"
+"</g>"
+"</g>"
+"</svg>"
+"<!--<![endif]-->"  
+*/                // end of conditional inclusion of SVG graphic (excludes Internet Explorer browser)
+// ---- End of Wi-Fi logo SVG image definition ----
+
+// Optional section 2: Simple SVG graphic example: Uncomment this section to generate a filled circle  in lower area of webpage
+// eg. Could use to indicate RGB LED color (with addition of applicable C-code to dynamically update specified "fill=" color)
+/*
+"<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">"
+"<circle cx=\"155\" cy=\"22\" r=\"20\" stroke=\"DimGrey\" stroke-width=\"2\" fill=\"Red\"/>"
+"</svg>"
+"</body></html>"};
+*/
+
+// ----------------------------------------------------------
+
+char ssid_name[] = SSID;
+char testString[20];
+int vcc = 0;
+//*****************************************************************************
+//
+//!  demo_wi-fi_main
+//!
+//!  \param  None
+//!
+//!  \return none
+//!
+//!  \brief   The main loop is executed here
+//
+//*****************************************************************************
+
+int demo_wifi_main(void)
+{
+    server_running = 1;
+    initTCPIP();
+    while(1)
+    {
+      /* Configure dynamic HTML string handlers
+         0 : Acceleration
+         1 : Magnetometer                   
+         2 : eCompass       
+         3 : Altitude
+         ------------------- 
+         4 : Battery Voltage
+         5 : Ambient Light
+         6 : Temperature                    
+         7 : Slider Position        
+         8 : Page Views
+      */                    
+        (htmlHandlers.dynHtmlFunc[0]) = getAccelXYZ_Str; 
+        memcpy(htmlHandlers.dynHtmlParamName[0],"Acceleration(G).. ",strlen("Acceleration(G).. "));
+        htmlHandlers.dynHtmlParamName[0][strlen("Acceleration(G).. ")] ='\0';
+
+        (htmlHandlers.dynHtmlFunc[1]) = getM3110Str; 
+        memcpy(htmlHandlers.dynHtmlParamName[1],"Magnetometer(uT). ",strlen("Magnetometer(uT). "));
+        htmlHandlers.dynHtmlParamName[1][strlen("Magnetometer(uT). ")] ='\0';
+
+        (htmlHandlers.dynHtmlFunc[2]) = getCompassStr;
+        memcpy(htmlHandlers.dynHtmlParamName[2],"eCompass......... ",strlen("eCompass......... "));
+        htmlHandlers.dynHtmlParamName[2][strlen("eCompass......... ")] ='\0';
+
+        (htmlHandlers.dynHtmlFunc[3]) = getAltitudeStr; 
+        memcpy(htmlHandlers.dynHtmlParamName[3],"Altitude......... ",strlen("Altitude......... "));
+        htmlHandlers.dynHtmlParamName[3][strlen("Altitude......... ")] ='\0';
+
+        (htmlHandlers.dynHtmlFunc[4]) = getBatteryVoltageStr;
+        memcpy(htmlHandlers.dynHtmlParamName[4],"Battery Voltage.. ",strlen("Battery Voltage.. "));
+        htmlHandlers.dynHtmlParamName[4][strlen("Battery Voltage.. ")] ='\0';
+
+        (htmlHandlers.dynHtmlFunc[5]) = getLightVoltageStr;
+        memcpy(htmlHandlers.dynHtmlParamName[5],"Ambient Light.... ",strlen("Ambient Light.... "));
+        htmlHandlers.dynHtmlParamName[5][strlen("Ambient Light.... ")] ='\0';
+            
+        (htmlHandlers.dynHtmlFunc[6]) = getTemperatureStr; 
+        memcpy(htmlHandlers.dynHtmlParamName[6],"Temperature...... ",strlen("Temperature...... "));
+        htmlHandlers.dynHtmlParamName[6][strlen("Temperature...... ")] ='\0';
+
+        (htmlHandlers.dynHtmlFunc[7]) = getTSI_sliderStr; 
+        memcpy(htmlHandlers.dynHtmlParamName[7],"Slider Position.. ",strlen("Slider Position.. "));
+        htmlHandlers.dynHtmlParamName[7][strlen("Slider Position.. ")] ='\0';
+
+        (htmlHandlers.dynHtmlFunc[8]) = getViewsNum;
+        memcpy(htmlHandlers.dynHtmlParamName[8],"Page Views....... ",strlen("Page Views....... "));
+        htmlHandlers.dynHtmlParamName[8][strlen("Page Views....... ")] ='\0';
+
+        // Configure CGI Handler
+        (pHandlers.cgiHandlerFunc[0]) = testFunc;
+
+        initHTTPServer(HTTP_PORT,(char *)index, &pHandlers, &htmlHandlers);
+        serverMain();
+    }
+}
+
+
+void testFunc(char * str)
+{
+    memcpy(testString,str,strlen(str));
+    if(strcmp(str, "-Red-") == 0)
+    {
+        RED_ON; GREEN_OFF; BLUE_OFF; 
+    }
+    else if(strcmp(str, "Green") == 0) 
+    {
+        RED_OFF; GREEN_ON; BLUE_OFF;
+    }
+    else if (strcmp(str, "Blue-") == 0) 
+    {
+        RED_OFF; GREEN_OFF; BLUE_ON;
+    }      
+}
+
+void getBatteryVoltageStr(char * str)
+{
+    sprintf(str,"    "); //clears field (needed if previous string had more characters)
+    sprintf(str, "%d %%", adc_sample3);
+}
+ 
+void getLightVoltageStr(char * str)
+{
+    int LightPercent = 0;
+    LightPercent = (axis6.light * 100) / 4096; 
+    sprintf(str,"    "); //clears field (needed if previous string had more characters)
+    sprintf(str, "%d %%", LightPercent);
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/demo.h	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,19 @@
+#ifndef DEMO_H
+#define DEMO_H
+
+#ifdef    __cplusplus
+extern "C" {
+#endif
+
+int demo_wifi_main(void);
+void testFunc(char * str);
+void getTempStr(char * str);
+void getBatteryVoltageStr(char * str);
+void getLightVoltageStr(char * str);
+
+
+#ifdef    __cplusplus
+}
+#endif // __cplusplus
+#endif // DEMO_H
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/exosite.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,663 @@
+/*****************************************************************************
+*
+*  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;
+
+    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;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/exosite.h	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,95 @@
+/*****************************************************************************
+*
+*  exosite.h - Exosite library interface header
+*  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.
+*
+*****************************************************************************/
+
+#ifndef EXOSITE_H
+#define EXOSITE_H
+
+#ifdef    __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+// defines
+enum UUIDInterfaceTypes
+{
+    IF_WIFI,
+    IF_ENET,
+    IF_FILE,
+    IF_HDD,
+    IF_I2C,
+    IF_GPRS,
+    IF_NONE
+};
+
+enum ExositeStatusCodes
+{
+    EXO_STATUS_OK,
+    EXO_STATUS_INIT,
+    EXO_STATUS_BAD_UUID,
+    EXO_STATUS_BAD_VENDOR,
+    EXO_STATUS_BAD_MODEL,
+    EXO_STATUS_BAD_INIT,
+    EXO_STATUS_BAD_TCP,
+    EXO_STATUS_BAD_SN,
+    EXO_STATUS_CONFLICT,
+    EXO_STATUS_BAD_CIK,
+    EXO_STATUS_NOAUTH,
+    EXO_STATUS_END
+};
+
+#define EXOSITE_VENDOR_MAXLENGTH                20
+#define EXOSITE_MODEL_MAXLENGTH                 20
+#define EXOSITE_SN_MAXLENGTH                    EXOSITE_HAL_SN_MAXLENGTH
+#define EXOSITE_DEMO_UPDATE_INTERVAL            4000// ms
+#define CIK_LENGTH                              40
+
+// functions for export
+int Exosite_Write(char * pbuf, unsigned char bufsize);
+int Exosite_Read(char * palias, char * pbuf, unsigned char buflen);
+int Exosite_Init(const char *vendor, const char *model, const unsigned char if_nbr, int reset);
+int Exosite_Activate(void);
+void Exosite_SetCIK(char * pCIK);
+int Exosite_GetCIK(char * pCIK);
+int Exosite_StatusCode(void);
+int Exosite_GetResponse(void);
+
+#ifdef    __cplusplus
+}
+#endif // __cplusplus
+
+#endif // EXOSITE_H
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/exosite_hal.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,314 @@
+/*****************************************************************************
+*
+*  exosite_hal.c - Exosite hardware & environmenat adapation layer.
+*  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 "socket.h"
+#include "nvmem.h"
+#include "strlib.h"
+#include "evnt_handler.h"    // for socketaddr extern
+#include "board.h"
+#include "common.h"*/
+
+// local defines
+
+char exo_meta[META_SIZE];
+// local functions
+
+// externs
+extern sockaddr tSocketAddr;
+extern void errorHandler(void);
+
+// global variables
+
+
+//*****************************************************************************
+//
+//! exoHAL_ReadHWMAC
+//!
+//!  \param  Interface Number (1 - WiFi), buffer to return hexadecimal MAC
+//!
+//!  \return None
+//!
+//!  \brief  Reads the MAC address from the hardware
+//
+//*****************************************************************************
+void exoHAL_ReadHWMAC(unsigned char if_nbr, unsigned char * macBuf)
+{
+    switch (if_nbr)
+    {
+        case IF_WIFI:
+            nvmem_read(NVMEM_MAC_FILEID, 6, 0, (unsigned char *)macBuf);
+            break;
+        default:
+            break;
+    }
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_EnableNVMeta
+//!
+//!  \param  None
+//!
+//!  \return None
+//!
+//!  \brief  Enables meta non-volatile memory, if any
+//
+//*****************************************************************************
+void exoHAL_EnableMeta(void)
+{
+    return; //nothing to do on msp430 (FRAM is awesome)
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_EraseNVMeta
+//!
+//!  \param  None
+//!
+//!  \return None
+//!
+//!  \brief  Wipes out meta information - replaces with 0's.
+//
+//*****************************************************************************
+void exoHAL_EraseMeta(void)
+{
+    memset(exo_meta, 0, META_SIZE); //on msp430, simply set the region to 0
+    return;
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_WriteMetaItem
+//!
+//!  \param  buffer - string buffer containing info to write to meta; len -
+//!          size of string in bytes; offset - offset from base of meta
+//!          location to store the item.
+//!
+//!  \return None
+//!
+//!  \brief  Stores information to the NV meta structure.
+//
+//*****************************************************************************
+void exoHAL_WriteMetaItem(unsigned char * buffer, unsigned char len, int offset)
+{
+    memcpy((char *)(exo_meta + offset), buffer, len); //on msp430, simply put the info into mem
+    return;
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_ReadMetaItem
+//!
+//!  \param  buffer - string buffer containing info to write to meta; len -
+//!          size of string in bytes; offset - offset from base of meta
+//!          location to store the item.
+//!
+//!  \return None
+//!
+//!  \brief  Stores information to the NV meta structure.
+//
+//*****************************************************************************
+void exoHAL_ReadMetaItem(unsigned char * buffer, unsigned char len, int offset)
+{
+    memcpy(buffer, (char *)(exo_meta + offset), len); //on msp430, simply read the info from mem
+    return;
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_SocketClose
+//!
+//!  \param  socket - socket handle
+//!
+//!  \return None
+//!
+//!  \brief  The function closes a socket
+//
+//*****************************************************************************
+void exoHAL_SocketClose(long socket)
+{
+    closesocket(socket);
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_SocketOpenTCP
+//!
+//!  \param  None
+//!
+//!  \return socket - socket handle
+//!
+//!  \brief  The function opens a TCP socket
+//
+//*****************************************************************************
+long exoHAL_SocketOpenTCP()
+{
+    return((long)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_ServerConnect
+//!
+//!  \param  None
+//!
+//!  \return socket - socket handle
+//!
+//!  \brief  The function opens a TCP socket
+//
+//*****************************************************************************
+long exoHAL_ServerConnect(long sock)
+{
+    unsigned char server[META_SERVER_SIZE];
+
+    tSocketAddr.sa_family = 2;
+
+
+    exosite_meta_read(server, META_SERVER_SIZE, META_SERVER);
+
+    //TODO - use DNS or check m2.exosite.com/ip to check for updates
+    tSocketAddr.sa_data[0] = 0;   //server[4];//(port & 0xFF00) >> 8;
+    tSocketAddr.sa_data[1] = 80;  //server[5];//(port & 0x00FF);
+    tSocketAddr.sa_data[2] = 173; //server[0];//173;  // First octet of destination IP
+    tSocketAddr.sa_data[3] = 255; //server[1];//255;  // Second Octet of destination IP
+    tSocketAddr.sa_data[4] = 209; //server[2];//209;  // Third Octet of destination IP
+    tSocketAddr.sa_data[5] =  28; //server[3];//28;   // Fourth Octet of destination IP
+    //printf("Waiting for connection\n");
+    return connect(sock, &tSocketAddr, sizeof(tSocketAddr));
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_SocketSend
+//!
+//!  \param  socket - socket handle; buffer - string buffer containing info to
+//!          send; len - size of string in bytes;
+//!
+//!  \return Number of bytes sent
+//!
+//!  \brief  Sends data out the network interface
+//
+//*****************************************************************************
+unsigned char exoHAL_SocketSend(long socket, char * buffer, unsigned char len)
+{
+    int i;
+    i = -2;
+    while(i == -2) i = send(socket, buffer, (long)len, 0); //always set flags to 0 for CC3000
+    return (unsigned char) i;
+}
+
+//*****************************************************************************
+//
+//! exoHAL_SocketRecv
+//!
+//!  \param  socket - socket handle; buffer - string buffer to put info we
+//!          receive; len - size of buffer in bytes;
+//!
+//!  \return Number of bytes received
+//!
+//!  \brief  Sends data out the network interface
+//
+//*****************************************************************************
+unsigned char exoHAL_SocketRecv(long socket, char * buffer, unsigned char len)
+{
+    return (unsigned char)recv(socket, buffer, (long)len, 0); //always set flags to 0 for CC3000
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_HandleError
+//!
+//!  \param  code - error code;
+//!
+//!  \return None
+//!
+//!  \brief  Handles errors in platform-specific way
+//
+//*****************************************************************************
+void exoHAL_HandleError(unsigned char code)
+{
+    printf("ERROR\n");
+    return;
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_ShowUIMessage
+//!
+//!  \param  code - UI code for message to display;
+//!
+//!  \return None
+//!
+//!  \brief  Displays message in a platform specific way
+//
+//*****************************************************************************
+void exoHAL_ShowUIMessage(unsigned char code)
+{
+    //printf("ShowUIcode %d\n", code);
+    return;
+}
+
+
+//*****************************************************************************
+//
+//! exoHAL_MSDelay
+//!
+//!  \param  delay - milliseconds to delay
+//!
+//!  \return None
+//!
+//!  \brief  Delays for specified milliseconds
+//
+//*****************************************************************************
+void exoHAL_MSDelay(unsigned short delay)
+{
+    wait_ms(delay);
+    return;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/exosite_hal.h	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,91 @@
+/*****************************************************************************
+*
+*  exosite_hal.h - Common header for Exosite hardware adapation layer
+*  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.
+*
+*****************************************************************************/
+
+#ifndef EXOSITE_HAL_H
+#define EXOSITE_HAL_H
+
+#ifdef    __cplusplus
+extern "C" {
+#endif
+
+// defines
+/*typedef enum
+{
+    IF_WIFI,
+    IF_ENET,
+    IF_FILE,
+    IF_HDD,
+    IF_I2C,
+    IF_NONE
+} UUIDInterfaceTypes;*/
+
+typedef enum
+{
+    EXO_ERROR_WRITE,
+    EXO_ERROR_READ,
+    EXO_ERROR_CONNECT,
+    EXO_ERROR_UNKNOWN,
+    EXO_ERROR_END
+} ExositeErrorCodes;
+
+typedef enum
+{
+    EXO_SERVER_CONNECTED,
+    EXO_CLIENT_RW,
+    EXO_UI_END
+} ExositeUICodes;
+
+
+// functions for export
+void exoHAL_ReadHWMAC(unsigned char if_nbr, unsigned char * macBuf);
+void exoHAL_EnableMeta(void);
+void exoHAL_EraseMeta(void);
+void exoHAL_WriteMetaItem(unsigned char * buffer, unsigned char len, int offset);
+void exoHAL_ReadMetaItem(unsigned char * buffer, unsigned char len, int offset);
+void exoHAL_SocketClose(long socket);
+long exoHAL_SocketOpenTCP(void);
+long exoHAL_ServerConnect(long socket);
+unsigned char exoHAL_SocketSend(long socket, char * buffer, unsigned char len);
+unsigned char exoHAL_SocketRecv(long socket, char * buffer, unsigned char len);
+void exoHAL_HandleError(unsigned char code);
+void exoHAL_ShowUIMessage(unsigned char code);
+void exoHAL_MSDelay(unsigned short delay);
+
+#ifdef    __cplusplus
+}
+#endif // __cplusplus
+
+#endif // EXOSITE_HAL
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/exosite_meta.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,193 @@
+/*****************************************************************************
+*
+*  exosite_meta.c - Exosite meta information handler.
+*  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 "exosite_meta.h"
+#include "exosite_hal.h"
+#include "mbed.h"
+//#include "strlib.h"
+//#include "stdlib.h"
+
+// local defines
+
+// local functions
+
+// externs
+
+// global variables
+
+
+//*****************************************************************************
+//
+//! exosite_meta_init
+//!
+//!  \param  None
+//!
+//!  \return None
+//!
+//!  \brief  Does whatever we need to do to initialize the NV meta structure
+//
+//*****************************************************************************
+void exosite_meta_init(void)
+{
+    char strBuf[META_MARK_SIZE];
+
+    exoHAL_EnableMeta();  //turn on the necessary hardware / peripherals
+
+    //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)) exosite_meta_defaults();
+
+}
+
+
+//*****************************************************************************
+//
+//! exosite_meta_defaults
+//!
+//!  \param  None
+//!
+//!  \return None
+//!
+//!  \brief  Writes default meta values to NV memory.  Erases existing meta
+//!          information!
+//
+//*****************************************************************************
+void exosite_meta_defaults(void)
+{
+    const unsigned char meta_server_ip[6] = {173,255,209,28,0,80};
+
+    exoHAL_EraseMeta(); //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
+
+    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;
+            exoHAL_WriteMetaItem(write_buffer, srcBytes, (int)meta_info->cik); //store CIK
+            break;
+        case META_SERVER:
+            if (srcBytes > META_SERVER_SIZE) return;
+            exoHAL_WriteMetaItem(write_buffer, srcBytes, (int)meta_info->server); //store server IP
+            break;
+        case META_MARK:
+            if (srcBytes > META_MARK_SIZE) return;
+            exoHAL_WriteMetaItem(write_buffer, srcBytes, (int)meta_info->mark); //store exosite mark
+            break;
+        case META_UUID:
+            if (srcBytes > META_UUID_SIZE) return;
+            exoHAL_WriteMetaItem(write_buffer, srcBytes, (int)meta_info->uuid); //store UUID
+            break;
+        case META_MFR:
+            if (srcBytes > META_MFR_SIZE) return;
+            exoHAL_WriteMetaItem(write_buffer, srcBytes, (int)meta_info->mfr); //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;
+            exoHAL_ReadMetaItem(read_buffer, destBytes, (int)meta_info->cik); //read CIK
+            break;
+        case META_SERVER:
+            if (destBytes < META_SERVER_SIZE) return;
+            exoHAL_ReadMetaItem(read_buffer, destBytes, (int)meta_info->server); //read server IP
+            break;
+        case META_MARK:
+            if (destBytes < META_MARK_SIZE) return;
+            exoHAL_ReadMetaItem(read_buffer, destBytes, (int)meta_info->mark); //read exosite mark
+            break;
+        case META_UUID:
+            if (destBytes < META_UUID_SIZE) return;
+            exoHAL_ReadMetaItem(read_buffer, destBytes, (int)meta_info->uuid); //read exosite mark
+            break;
+        case META_MFR:
+            if (destBytes < META_MFR_SIZE) return;
+            exoHAL_ReadMetaItem(read_buffer, destBytes, (int)meta_info->mfr); //read exosite mark
+            break;
+        case META_NONE:
+            default:
+            break;
+    }
+    return;
+}
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/exosite_meta.h	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,86 @@
+/*****************************************************************************
+*
+*  exosite_meta.h - Meta informatio header
+*  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.
+*
+*****************************************************************************/
+
+#ifndef EXOSITE_META_H
+#define EXOSITE_META_H
+
+#ifdef    __cplusplus
+extern "C" {
+#endif
+
+// defines
+#define META_SIZE                 256
+#define META_CIK_SIZE             40
+#define META_SERVER_SIZE          6
+#define META_PAD0_SIZE            2
+#define META_MARK_SIZE            8
+#define META_UUID_SIZE            17
+#define META_PAD1_SIZE            4
+#define META_RSVD_SIZE            56
+#define META_MFR_SIZE             128
+typedef struct {
+  char cik[META_CIK_SIZE];                   // our client interface key
+  char server[META_SERVER_SIZE];             // ip address of m2.exosite.com (not using DNS at this stage)
+  char pad0[META_PAD0_SIZE];                 // pad 'server' to 8 bytes
+  char mark[META_MARK_SIZE];                 // watermark
+  char uuid[META_UUID_SIZE];                 // UUID in ascii
+  char pad1[META_PAD1_SIZE];                 // pad 'uuid' to 16 bytes
+  char rsvd[META_RSVD_SIZE];                 // reserved space - pad to ensure mfr is at end of RDK_META_SIZE
+  char mfr[META_MFR_SIZE];                   // manufacturer data structure
+} exosite_meta;
+
+#define EXOMARK "exosite!"
+
+typedef enum
+{
+    META_CIK,
+    META_SERVER,
+    META_MARK,
+    META_UUID,
+    META_MFR,
+    META_NONE
+} MetaElements;
+
+// functions for export
+void exosite_meta_defaults(void);
+void exosite_meta_init(void);
+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);
+
+#ifdef    __cplusplus
+}
+#endif // __cplusplus
+
+#endif // EXOSITE_META_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/httpserver.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,399 @@
+/****************************************************************************
+*
+*  httpserver.c - General HTTP Server implementation
+*  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 "httpserver.h"
+#include "doTCPIP.h"
+#include "TSISensor.h"
+
+extern axis6_t axis6;
+extern TSISensor tsi;
+
+/** \brief Socket used by server to listen and accept connections */
+long httpServerSocket;
+
+/** \brief Variable holding the server's port */
+int serverPort = 0;
+
+/** \brief Pointer to the index HTML page */
+char * indexPage;
+extern unsigned char *dataPacket;
+
+/** \brief Pointer to CGI handler structure */
+cgi_handler * chList;
+
+/** \brief Pointer to Dynamic HTML handler structure */
+dyn_html_handler * htmlList;
+
+/** \brief Pointer to Dynamic HTML handler structure */
+http_server_event_handler * eventHandlers = NULL;
+
+
+/** \brief Client socket handle list */
+int clientList[MAX_CLIENTS];
+
+/** \brief Page view counter */
+int viewCounter = 1;
+#define REQ_BUFFER_SIZE     400   //
+#define HTTP_TX_BLOCK_SIZE  256   //
+
+
+extern char requestBuffer[REQ_BUFFER_SIZE];
+
+
+volatile int Delay;
+
+//extern char OkToDoShutDown;
+//extern int newData, secondFlag, ms5Flag;
+
+/********************************************************************/
+void getAccelXYZ_Str(char * str) // MMA8451Q accelerometer - report axis with highest value 
+{
+    sprintf(str,"                                    "); //clears field (needed if previous string had more characters)   
+    sprintf(str, "X= %1.2f, Y= %1.2f, Z= %1.2f", axis6.fGax, axis6.fGay, axis6.fGaz);;  
+}  
+
+/********************************************************************/
+void getTemperatureStr(char * str) // 
+{
+    sprintf(str, "%+d C", axis6.temp); 
+}
+
+/********************************************************************/
+void getTSI_sliderStr(char * str) // TSI Slider position 
+{
+    uint8_t slider_position; 
+    
+    slider_position = tsi.readPercentage() * 100; // Slider position as percentage
+    sprintf(str,"    "); //clears field (needed if previous string had more characters)
+    sprintf(str, "%d %%", slider_position);
+}   
+
+void getCompassStr(char * str)   // Mag3110 generated Compass bearing 
+{
+    char *compass_points[9] = {"North", "N-East", "East", "S-East", "South", "S-West", "West", "N-West", "North"};
+    signed short compass_bearing = (axis6.compass + 23) / 45;
+    sprintf(str,"                                        "); //clears field (needed if previous string had more characters)
+    sprintf(str, "Roll=%-d  Pitch=%-d  Yaw=%-d [%s]", axis6.roll, axis6.pitch, axis6.yaw, compass_points[compass_bearing]);   // 
+}   
+
+void getM3110Str(char * str)   // Mag3110 displayed in units of UT 
+{
+    sprintf(str,"                                    "); //clears field (needed if previous string had more characters)
+    sprintf(str, "X= %3.1f, Y= %3.1f, Z= %3.1f", axis6.fUTmx, axis6.fUTmy, axis6.fUTmz);
+}   
+
+/********************************************************************/
+extern void getAltitudeStr(char * str)    // Get Altitude 
+{
+    sprintf(str, "%+d meters", axis6.alt);   // str = integer portion of result 
+}   
+
+//*****************************************************************************
+//
+//! \brief  Initializes HTTP Server
+//!
+//! \param cnum is the client socket handle to be used
+//!
+//! \return 0 if successful
+//!
+//
+//*****************************************************************************
+char initHTTPServer(int port,
+                    char * ipage,
+                    cgi_handler * handleList,
+                    dyn_html_handler * dhList)
+{
+    sockaddr serverSocketAddr;
+    serverPort = port;
+    indexPage = ipage;
+    chList = handleList;
+    htmlList = dhList;
+
+
+    httpServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+    if (httpServerSocket == -1)
+    {
+        printf("oops\n");
+        wlan_stop();
+        return(-1);
+    }
+
+    serverSocketAddr.sa_family = AF_INET;
+
+    // Set the Port Number
+    serverSocketAddr.sa_data[0] = (port & 0xFF00)>> 8;
+    serverSocketAddr.sa_data[1] = (port & 0x00FF);
+
+    memset (&serverSocketAddr.sa_data[2], 0, 4);
+
+    if (bind(httpServerSocket, &serverSocketAddr, sizeof(sockaddr)) != 0);
+
+    return 0;
+}
+
+//*****************************************************************************
+//
+//! \brief  Main HTTP Server
+//!
+//! \param none
+//!
+//! \return none
+//!
+//
+//*****************************************************************************
+void serverMain()
+{
+    sockaddr clientaddr;
+    socklen_t addrlen;
+    int i = 0;
+    int currentClient = 0;
+        printf("Main HTTP server\n");
+    for(i = 0; i < MAX_CLIENTS; i++)
+        clientList[i] = -1;
+
+    // Start Listening
+    if (listen (httpServerSocket, MAX_CLIENTS) != 0);
+
+    // Handle Clients and Data
+    while(1)
+    {
+        addrlen = sizeof(clientaddr);
+        printf("Current Client= %d\n", currentClient);
+        // accept blocks until we receive a connection
+        //LED_D2_ON;
+        ms5Flag = 0;
+        while ( (clientList[currentClient] == -1) || (clientList[currentClient] == -2) )
+        {
+            clientList[currentClient] = accept(httpServerSocket, (sockaddr *) &clientaddr, &addrlen);
+        }
+     
+        if(clientList[currentClient] >= 0)
+        {
+            // Connection Accepted, Send Data
+            // Wait for a data update
+            newData = 0;
+            while(!newData);
+            SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;  // *** Disable SysTick Timer
+            handleHTTPRequest(currentClient);
+            closesocket(clientList[currentClient]);
+            clientList[currentClient]=-1;
+            wait_us(40);  
+        }
+        else if(clientList[currentClient] == -57)
+        {
+            // BUG: Socket inactive so reopen socket
+            // Inactive Socket, close and reopen it
+            printf("Oops!!!\n");
+            closesocket(httpServerSocket);
+            httpServerSocket = 0xFFFFFFFF;
+            initHTTPServer(serverPort, indexPage, chList, htmlList);
+            // Start Listening
+            if ( listen (httpServerSocket, 5) != 0 );
+        }
+        SysTick->CTRL |=  SysTick_CTRL_TICKINT_Msk;  // *** Re-Enable SysTick Timer
+    }
+}
+
+//*****************************************************************************
+//
+//! \brief  Handles HTTP Requests
+//!
+//! \param cnum is the client socket handle to be used
+//!
+//! \return none
+//!
+//
+//*****************************************************************************
+void handleHTTPRequest(int cnum)
+{
+
+    char * reqline[3];
+    char * cgiTok;
+
+    int i = 0;
+    char paramBuf[20];
+    int bytesRecvd;
+    char tempStr[40]; //PF was 26
+
+    memset(requestBuffer,0,sizeof (requestBuffer));
+    bytesRecvd = recv(clientList[cnum], requestBuffer, sizeof(requestBuffer), 0);
+
+    printf("\nhandleHTTPRequest\n");
+
+    if(bytesRecvd > 0)
+    {
+        // Received some data, check it and send data back
+        reqline[0] = strstr(requestBuffer, "GET");
+        if ( reqline[0] != NULL )
+        {
+            if (strstr (requestBuffer, "HTTP/1.0") != NULL && strstr (requestBuffer, "HTTP/1.1") != NULL )
+            {
+                send(clientList[cnum], "HTTP/1.0 400 Bad Request\n", 25,0);
+            }
+            else
+            {
+
+#ifdef HTTP_CGI_ENABLED
+                // Do we have CGI parameters we need to parse?
+                if(strchr(requestBuffer, '?') != NULL)
+                {
+                    // Decode URL and handle each parameter sequentially
+                    // according to table previously setup.
+                    cgiTok = strstr(requestBuffer,"=");
+                    if(cgiTok != NULL)
+                    {
+                        memset(paramBuf,0,sizeof(paramBuf));
+                        memcpy(paramBuf,cgiTok+1,5);     // hard-coded for demo: 5 character parameter (-Red-/Green/Blue-)
+                        chList->cgiHandlerFunc[0](paramBuf);
+
+                    }
+                }
+#endif
+
+#ifdef HTTP_DYN_HTML_ENABLED
+                // The code below replaces data in the HTML page
+                // with that generated by the specified functions.
+                for(i = 0; i < 9; i++)  // change the range here for more dynamic fields on webpage
+                {
+                    memset(tempStr,0,sizeof(tempStr));
+                    htmlList->dynHtmlFunc[i](tempStr);
+                    tempStr[strlen(tempStr)]= ' ';
+                    pageReplace((char *)indexPage,
+                                (char *)htmlList->dynHtmlParamName[i],
+                                (char *)tempStr);
+                }
+#endif
+                viewCounter++;
+
+                sendHTTPData(clientList[cnum], HTTP_RESP, strlen(HTTP_RESP));
+                                
+                for(i = 0; i < strlen(indexPage); i += HTTP_TX_BLOCK_SIZE)
+                {
+                                    
+                    if(strlen(indexPage) - i < HTTP_TX_BLOCK_SIZE)
+                    {
+                        sendHTTPData(clientList[cnum], &indexPage[i], strlen(indexPage) - i);
+                    }
+                    else
+                    {
+                        sendHTTPData(clientList[cnum], &indexPage[i], HTTP_TX_BLOCK_SIZE);
+                    }
+                                        // This delay is necessary, or else we run into issues
+                    for (Delay = 0; Delay < 1000; Delay++);   //PF
+                }
+            }
+        }
+    }
+}
+
+//*****************************************************************************
+//
+//! \brief  Inserts characters in page that appear after an indicator ind
+//! with the value from val
+//!
+//! \param  page is a pointer to the array holding the page's HTML code
+//! \param ind is a pointer to a string that has the name of the parameter on the page to modify
+//! \param val is the pointer to a string holding the string to insert in the XXX
+//!
+//! \return none
+//!
+//
+//*****************************************************************************
+void pageReplace(char * page, char * ind, char * val)
+{
+    char * indicLoc;
+    indicLoc = strstr (page,ind);
+    memcpy(indicLoc+strlen(ind), val, strlen(val));
+}
+
+//*****************************************************************************
+//
+//! \brief  Returns a string with the number of views of the page
+//!
+//! \param  str is a pointer to the array where the number of views will be put
+//!
+//! \return none
+//!
+//
+//*****************************************************************************
+extern uint32 cal_count;
+
+
+void getViewsNum(char * str)
+{
+    sprintf(str, "%d", viewCounter);
+}
+
+//*****************************************************************************
+//
+//! \brief  Sends HTTP Data
+//!
+//! \param sdesc is the socket descriptor of the socket used for sending data
+//! \param buf is a pointer to the buffer with the data to be sent
+//! \param len is the number of bytes to send
+//!
+//! \return none
+//!
+//
+//*****************************************************************************
+void sendHTTPData(long sdesc, const void *buf, long len)
+{
+    int bytesSent = -2;
+    while(bytesSent == -2) bytesSent = send(sdesc, buf, len,0);
+    if(bytesSent == -1)
+    {
+        // General Send Error
+    }
+    if (bytesSent != strlen(indexPage))
+    {
+        // ERROR: not all bytes sent
+    }
+}
+
+//*****************************************************************************
+//
+//! \brief  Initializes HTTP Server Event Handler
+//!
+//! \param eh is a pointer to the array handling server events
+//!
+//! \return none
+//!
+//
+//*****************************************************************************
+void initEventHandlers(http_server_event_handler * eh)
+{
+    eventHandlers = eh;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/httpserver.h	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,104 @@
+/*****************************************************************************
+*
+*  httpserver.h - General HTTP Server definitions
+*  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.
+*
+*****************************************************************************/
+#ifndef HTTPSERVER_H
+#define HTTPSERVER_H
+
+#ifdef    __cplusplus
+extern "C" {
+#endif
+
+#define MAX_CGI_PARAMS 4
+#define MAX_DYN_HTML_PARAMS 9
+#define MAX_DYN_HTML_PARAM_SIZE 40
+#define ROOT "/"
+
+
+#define MAX_CLIENTS 1  // We currently only support 1 client
+
+#define HTTP_RESP "HTTP/1.0 200 OK\n\n"
+
+#define HTTP_CGI_ENABLED
+#define HTTP_DYN_HTML_ENABLED
+
+#define MAX_REPLACE_CHAR 16
+
+
+// Struct that indicates all the elements necessary to handle
+typedef struct
+{
+    // name of parameter that will be analyzed
+    // Currently not implemented to verify each
+    // This would enable us to be flexible with parameter list
+    //char [][]
+    
+    // Array of functions that will handle each parameter
+    void (*cgiHandlerFunc[MAX_CGI_PARAMS])(char *);
+        
+} cgi_handler;
+
+
+typedef struct
+{
+     char dynHtmlParamName[MAX_DYN_HTML_PARAMS][MAX_DYN_HTML_PARAM_SIZE];
+     void (*dynHtmlFunc[40])(char *);  //PF was 20
+} dyn_html_handler;
+// HTTP Server Related
+
+/**
+ *  A structure representing pointers to functions handling
+ *  server events.
+ *
+ */
+typedef struct
+{
+    // Array of functions that will handle server events
+  void (*serverInitHandlerFunc)(char *);            /** Handler for Server Initialization Done */
+  void (*clientAcceptedHandlerFunc)(char *);        /** Handler for Client Accepted */
+  void (*httpRequestDoneHandlerFunc)(char *);       /** Handler for HTTP Request Done */
+        
+} http_server_event_handler;
+
+char initHTTPServer(int port, char * ipage,  cgi_handler * handleList, dyn_html_handler * dhList);
+void handleHTTPRequest(int cnum);
+void serverMain(void);
+void pageReplace(char * page, char * ind, char * val);
+void getViewsNum(char * str);
+void sendHTTPData(long sdesc, const void *buf, long len);
+void initEventHandlers(http_server_event_handler * eh);
+
+#ifdef    __cplusplus
+}
+#endif // __cplusplus
+#endif // HTTPSERVER_H
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/run_exosite.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,214 @@
+/*****************************************************************************
+*
+*  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 "doTCPIP.h"
+#include "run_exosite.h"
+#include "exosite.h"
+
+// 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 *p;
+    char *s;
+} exo_data_it;
+
+extern char requestBuffer[];
+
+extern uint32 compass_type, seconds;
+extern void init_eCompass(void);
+extern void print_mac(void);
+extern int LAN_Connected;
+
+
+// local functions
+extern unsigned char checkWiFiConnected(void);
+
+extern userFS_t userFS;
+
+// exported functions
+
+// externs
+extern const char sensorNames[10][11];
+extern int Exosite_Write(char * pbuf, unsigned char buflen);
+extern int Exosite_Read(char * palias, char * pbuf, unsigned char buflen);
+extern int Exosite_Init(void);
+extern int Exosite_ReInit(void);
+extern char *itoa(int n, char *s, int b);
+extern void busyWait(unsigned short delay);
+extern void board_init(void);
+
+extern axis6_t axis6;
+extern int secondFlag;
+
+// global variables
+int cloud_status = -1;
+
+/** \brief Flag indicating whether user requested to perform Smart Config */
+extern char runSmartConfig;
+//Flag to indicate Smart Config needs to be performed
+extern unsigned char ptrFtcAtStartup;
+//Flag to indicate Smart Config was performed in the past and CC3000 has a stored profile
+extern unsigned char SmartConfigProfilestored;
+extern unsigned char ConnectUsingSmartConfig; 
+
+extern unsigned long ulCC3000Connected;
+extern unsigned long SendmDNSAdvertisment;
+
+extern void initTCPIP(void);
+
+long serverSocket;
+sockaddr serverSocketAddr;
+
+/** \brief Definition of data packet to be sent by server */
+unsigned char dataPacket[] = { '\r', 0xBE, 128, 128, 128, 70, 36, 0xEF };
+char activeCIK[41];
+char serverErrorCode = 0;
+
+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
+};
+    
+void setCIK(void)
+{
+    int i;
+    for(i=0 ;i < CIK_LENGTH ; i++) activeCIK[i] = userFS.CIK[i];
+    activeCIK[i] = NULL;
+}
+
+void build_str(void)
+{
+    exo_data_it *tsp;
+    exo_data_ft *tspf;
+    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);
+}
+
+//*****************************************************************************
+//
+//!  main
+//!
+//!  \param  None
+//!
+//!  \return none
+//!
+//!  \brief   The main loop is executed here
+//
+//*****************************************************************************
+void run_exosite(void)
+{
+    int value;
+    
+    ulCC3000Connected = 0;
+    SendmDNSAdvertisment = 0;
+    printf("\nConnecting to Exosite\n");
+    initTCPIP();
+    //userFS.validCIK = 0; // uncomment this to force provisioning every time, only used for debug
+    
+    if(!userFS.validCIK)
+    {
+        printf("Activating Wi-Go System on Exosite\n");
+        print_mac();
+        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();
+    }
+    
+    setCIK();
+    // Main Loop
+    while (1)
+    {
+        while(!secondFlag) /*__wfi()*/;
+        secondFlag = 0;
+        LED_D2_ON;
+        build_str();   
+        if(strlen(requestBuffer) > 300) printf("Buffer size= %d too small!!!", strlen(requestBuffer));
+        //printf("Buffer size= %d\n", strlen(requestBuffer));
+        value = Exosite_Write(requestBuffer,strlen(requestBuffer));    //write all sensor values to the cloud
+        LED_D2_OFF; 
+        if(value == -1)
+        {
+            LAN_Connected = 0;
+            LED_D3_OFF;
+            wlan_stop();
+            initTCPIP();
+        }
+   }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Webserver/run_exosite.h	Sat Sep 07 15:41:49 2013 +0000
@@ -0,0 +1,18 @@
+#ifndef RUN_EXOSITE_H
+#define RUN_EXOSITE_H
+
+#ifdef    __cplusplus
+extern "C" {
+#endif
+
+void setCIK(void);
+void build_str(void);
+void run_exosite(void);
+
+
+#ifdef    __cplusplus
+}
+#endif // __cplusplus
+
+#endif // RUN_EXOSITE_H
+
--- a/cc3000.cpp	Sun Aug 18 07:06:20 2013 +0000
+++ b/cc3000.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -64,7 +64,7 @@
 extern unsigned char ConnectUsingSmartConfig; 
 extern volatile unsigned long ulCC3000Connected;
 extern volatile unsigned long SendmDNSAdvertisment;
-//extern int server_running;
+extern int server_running;
 extern char DevServname[];
 volatile unsigned long ulSmartConfigFinished, ulCC3000DHCP, OkToDoShutDown, ulCC3000DHCP_configured;
 volatile unsigned char ucStopSmartConfig;
@@ -97,12 +97,15 @@
     //sends a request to connect (does not necessarily connect - callback checks that for me)
     // wlan_connect(SECURITY, SSID, strlen(SSID), NULL, PASSPHRASE, strlen(PASSPHRASE));
 #ifndef CC3000_TINY_DRIVER
-    wlan_connect(0, ssidName, strlen(ssidName), NULL, NULL, 0);
+    #ifndef AP_KEY 
+        wlan_connect(0, ssidName, strlen(ssidName), NULL, NULL, 0);
+    #else
+        wlan_connect(AP_SECURITY, ssidName, strlen(ssidName), NULL, (unsigned char *)AP_KEY , strlen(AP_KEY));
+    #endif
 #else
     wlan_connect(ssidName, strlen(ssidName));
 #endif
-    // We don't wait for connection. This is handled somewhere else (in the main
-    // loop for example).
+    // We don't wait for connection. This is handled somewhere else (in the main loop for example).
     return 0;      
 }
 
@@ -117,12 +120,15 @@
     if (lEventType == HCI_EVNT_WLAN_UNSOL_CONNECT)
     {
         ulCC3000Connected = 1;
+        LED_D2_ON;
     }
     if (lEventType == HCI_EVNT_WLAN_UNSOL_DISCONNECT)
     {       
         ulCC3000Connected = 0;
         ulCC3000DHCP      = 0;
         ulCC3000DHCP_configured = 0;
+        LED_D2_OFF;
+        LED_D3_OFF;
     }
     if (lEventType == HCI_EVNT_WLAN_UNSOL_DHCP)
     {
@@ -134,10 +140,12 @@
         {
             sprintf( (char*)pucCC3000_Rx_Buffer,"IP:%d.%d.%d.%d\f\r", data[3],data[2], data[1], data[0] );
             ulCC3000DHCP = 1;
+            LED_D3_ON;
         }
         else
         {
             ulCC3000DHCP = 0;
+            LED_D3_OFF;
         }
     }
     if (lEventType == HCI_EVENT_CC3000_CAN_SHUT_DOWN)
@@ -302,7 +310,7 @@
 
 void StartSmartConfig(void)
 {
-//    server_running = 1;
+    server_running = 1;
     RED_OFF;
     GREEN_OFF;
     BLUE_ON;
@@ -314,7 +322,7 @@
     //Wait until CC3000 is disconected
     while (ulCC3000Connected == 1)
     {
-        wait_us(5);
+        wait_us(1);
         hci_unsolicited_event_handler();
     }
 
@@ -366,3 +374,5 @@
 
 
 
+
+
--- a/doTCPIP.cpp	Sun Aug 18 07:06:20 2013 +0000
+++ b/doTCPIP.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -36,13 +36,15 @@
 #include "doTCPIP.h"
 
 volatile unsigned char newData;
-//int server_running;
+int server_running;
 unsigned char ForceFixedSSID;
 char runSmartConfig;            // Flag indicating whether user requested to perform Smart Config
 volatile unsigned long ulCC3000Connected;
 unsigned char ConnectUsingSmartConfig;
 unsigned char myMAC[8];
 userFS_t userFS;
+axis6_t axis6;
+int do_mDNS = 0;
 
 // Setup the functions to handle our CGI parameters
 tNetappIpconfigRetArgs ipinfo2;
@@ -58,7 +60,104 @@
 char DevServname[] = "CC3000";
 volatile unsigned long SendmDNSAdvertisment;
 
+int sendTCPIP(int port)
+{
+    long temp, stat, sss, skip, skipc;
+    //socket descriptor 
+    long sock;
+    //new TCP socket descriptor
+    long newsock;
+    //destination address
+    sockaddr destAddr;
+    //local address
+    sockaddr LocalAddr;
 
+//    char buf2[40];
+    socklen_t addrlen;
+    memset(&LocalAddr, 0, 8);
+    LocalAddr.sa_family = AF_INET;
+    LocalAddr.sa_data[0] = (port >> 8) & 0xff;
+    LocalAddr.sa_data[1] = port & 0xff;  
+    memset (&LocalAddr.sa_data[2], 0, 4);
+    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+    while(sock == -1) sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_TCP);
+    temp = bind(sock,&LocalAddr,sizeof(sockaddr));
+    temp = listen(sock, 1);
+    addrlen = sizeof(destAddr);
+    skip = 0;
+    skipc = 0;
+    while(1)
+    {
+        newsock = -2;
+        printf("Server waiting for connection\n");
+        LED_D2_ON;
+        while((newsock == -1) || (newsock == -2))
+        {
+            newsock = accept(sock,&destAddr, &addrlen);
+            if(do_mDNS)
+            {
+                printf("mDNS= 0x%08x\n", mdnsAdvertiser(1, DevServname, sizeof(DevServname)));
+                do_mDNS = 0;
+            }
+        }
+        printf("Connected\n");
+        sss = seconds;
+        //receive TCP data
+        temp = 0;   
+        if(newsock >= 0)
+        {
+            recv(newsock, requestBuffer,20,0);
+            printf("Input = %s\n", requestBuffer);
+            HsecondFlag = 0;
+            while(1)
+            {
+                while(!newData) __wfi();
+                newData = 0;
+                ms5Flag = 0;
+                if(HsecondFlag)
+                {
+                    printf("FB= %d\n", tSLInformation.usNumberOfFreeBuffers);
+                    HsecondFlag = 0;
+                }
+                LED_D2_ON;  
+                stat = -2;
+                /*if(tSLInformation.usNumberOfFreeBuffers <= 2)
+                {
+                    printf("LOW= %d\n", tSLInformation.usNumberOfFreeBuffers);
+                }*/
+                //Disable sys tick interrupts for debugging
+                //SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk;       // *** Disable SysTick Timer Interrupt
+                stat = send(newsock,&axis6, sizeof(axis6), 0);
+                // Disable sys tick interrupts for debugging
+                //SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk;        // *** Enable SysTick Timer Interrupt   
+                LED_D2_OFF;
+                if(stat != 96)
+                {
+                    if(stat == -2)
+                    {
+                        skip++;
+                        skipc++;
+                    }
+                    //printf("status= %d\n", stat);
+                    if(stat == -1) break;
+                }
+                else
+                {
+                    temp++;
+                    skipc = 0;
+                }
+                if(skipc > 150)
+                {
+                    printf("Zero Buffer Error Sent=%d, time=%d\n", temp, seconds - sss);
+                    return(-1);
+                }
+            }   
+        } else printf("bad socket= %d\n", newsock);
+        closesocket(newsock);
+        printf("Done %d, time= %d, skipped= %d\n", temp, seconds - sss, skip);
+        skip = 0;
+    }
+}
 
 void sendPython(int port)
 {
@@ -132,11 +231,59 @@
         closesocket(newsock);
         printf("Done, press any key to repeat\n");
         getchar();
-//        printf("\x1B[2J");    //VT100 erase screen
-//        printf("\x1B[H");     //VT100 home
     }
 } 
 
+int getTCPIP( char a1, char a2, char a3, char a4, int port)
+{
+    long temp;
+    //socket descriptor 
+    long sock;
+    char msg1[10] = "Hello";
+    //destination address
+    sockaddr destAddr;
+    //num of bytes received
+    long numofbytes = 0;
+    //data buffer
+
+    memset(&destAddr, 0, 8);
+    destAddr.sa_family = AF_INET;
+    destAddr.sa_data[0] = (port >> 8) & 0xff;
+    destAddr.sa_data[1] = port & 0xff;  
+    destAddr.sa_data[2] = a1;   
+    destAddr.sa_data[3] = a2;   
+    destAddr.sa_data[4] = a3;       
+    destAddr.sa_data[5] = a4;   
+    //open socket
+    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+    while(sock == -1) sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_TCP);
+    hci_unsolicited_event_handler();
+    printf("Client attempting connection\n");
+    if(connect(sock, &destAddr, sizeof(destAddr)) < 0) return(-1);
+    printf("Connected\n");
+    //receive TCP data
+    temp = 0;
+    hci_unsolicited_event_handler();
+    send(sock, &msg1, strlen(msg1), 0);
+    printf("Receiving Data\n");
+    //printf("Input = %s\n", buf);
+    while(1)
+    {
+        numofbytes = recv(sock, &axis6, 100,0);
+        //printf("R %d\n", numofbytes);
+        newData = 1;    
+        if(numofbytes != -1)
+        { 
+            closesocket(sock);
+            printf("Done %d\n", temp);
+            hci_unsolicited_event_handler();
+            return(1);
+        }
+        temp++;
+    }
+    return(0); // We'll never get here
+}
+
 void initTCPIP(void)
 {
     int t;  
@@ -185,9 +332,23 @@
         LED_D2_OFF;
         printf("\n\nStarting TCP/IP Server\n");
         initTCPIP();
-        sendPython(TCPIP_PORT);
+//        sendPython(TCPIP_PORT);
+        sendTCPIP(TCPIP_PORT);
     }   
 }
+
+void runTCPIPclient(int a1, int a2, int a3, int a4)
+{
+    while(1)
+    {
+        LED_D3_OFF;
+        LED_D2_OFF;
+        printf("\n\nStarting TCP/IP Client connection\n");
+        initTCPIP();
+        getTCPIP( a1, a2, a3, a4, 80); // IP Address and Port of server
+    }   
+}
+
     
 unsigned char checkWiFiConnected(void)
 {
@@ -245,7 +406,7 @@
 void do_FTC(void)
 {
     printf("Running First Time Configuration\n");
-//    server_running = 1;
+    server_running = 1;
     runSmartConfig = 1;
     initTCPIP();
     RED_OFF;
@@ -261,3 +422,4 @@
 
 
 
+
--- a/doTCPIP.h	Sun Aug 18 07:06:20 2013 +0000
+++ b/doTCPIP.h	Sat Sep 07 15:41:49 2013 +0000
@@ -37,6 +37,7 @@
 #define DOTCPIP_H
 
 #include "cc3000.h"
+#include "Wi-Go_eCompass_Lib_V3.h"
 
 /** TCP/IP Functions
 *
@@ -54,7 +55,9 @@
 #endif
 
 #define SMART_CONFIG_SET 0x55
-#define TCPIP_PORT 15000
+// SMTP Specific
+#define HTTP_PORT     80
+#define TCPIP_PORT    15000
 
 #define USE_DHCP      1
 #define USE_STATIC_IP 2
@@ -69,8 +72,8 @@
 //#define IP_ALLOC_METHOD USE_STATIC_IP // for static IP address
 
 // Default SSID Settings
-//#define WPA2_KEY       "this-is-a-test"
-//#define AP_SECURITY     WPA2            // WPA2 must be enabled for use with iPhone or Android phone hotspot!
+//#define AP_KEY         "thisthis" 
+//#define AP_SECURITY    WPA2          // WPA2 must be enabled for use with iPhone or Android phone hotspot!
 #define SSID           "iot"
 #define AP_SECURITY    NONE          // no security but will connect quicker!  
 #define STATIC_IP_OCT1 192
@@ -95,21 +98,28 @@
 extern userFS_t userFS;
 
 extern unsigned long ulSmartConfigFinished,ulCC3000DHCP, OkToDoShutDown, ulCC3000DHCP_configured;
-//extern int server_running;
+extern int server_running;
 extern volatile unsigned char newData;
 extern unsigned char ForceFixedSSID;
 extern char runSmartConfig;
 extern char requestBuffer[];
 extern unsigned char myMAC[8];
 extern unsigned char SmartConfigProfilestored;
+extern int do_mDNS;
+extern axis6_t axis6;
+extern int HsecondFlag;
+extern unsigned int seconds;
+extern volatile int ms5Flag;
 
 extern void StartSmartConfig(void);
 
 
-
+int sendTCPIP(int port);
 void sendPython(int port);
 void initTCPIP(void);
 void runTCPIPserver(void);
+int getTCPIP( char a1, char a2, char a3, char a4, int port);
+void runTCPIPclient(int a1, int a2, int a3, int a4);
 
 /** Checks if WiFi is still connected.
 * @param  None
--- a/main.cpp	Sun Aug 18 07:06:20 2013 +0000
+++ b/main.cpp	Sat Sep 07 15:41:49 2013 +0000
@@ -1,94 +1,390 @@
-#include "mbed.h"
-#include "doTCPIP.h"
-
-
-// Serial USB port
-Serial pc(USBTX, USBRX);
-
-//Wi-Go battery charger control
-DigitalOut PWR_EN1(PTB2);
-DigitalOut PWR_EN2(PTB3);
-
-int main()
-{
-    char c;
-    // set current to 500mA since we're turning on the Wi-Fi
-    PWR_EN1 = 0;
-    PWR_EN2 = 1; 
-
-    //Set baudrate to 115200 instead of the default 9600
-    pc.baud (115200);
-    
-    initLEDs();
-    Init_HostDriver();
-    runSmartConfig = 0;
-    ulSmartConfigFinished = 0;
-//    server_running = 1;
-    newData = 0;    
-    socket_active_status = 0xFFFF;
-    ForceFixedSSID = 0;
-    
-    GREEN_ON;
-
-    // Trigger a WLAN device
-    wlan_start(0);
-    nvmem_read( NVMEM_USER_FILE_1_FILEID, sizeof(userFS), 0, (unsigned char *) &userFS);
-    nvmem_get_mac_address(myMAC);
-    printf("\x1B[2J");    //VT100 erase screen
-    printf("\x1B[H");     //VT100 home
-    printf("CC3000 Python demo.\n");
-    print_mac();
-    wlan_stop();
-    printf("FTC        %i\n",userFS.FTC);
-    printf("PP_version %i.%i\n",userFS.PP_version[0], userFS.PP_version[1]);
-    printf("SERV_PACK  %i.%i\n",userFS.SERV_PACK[0], userFS.SERV_PACK[1]);
-    printf("DRV_VER    %i.%i.%i\n",userFS.DRV_VER[0], userFS.DRV_VER[1], userFS.DRV_VER[2]);
-    printf("FW_VER     %i.%i.%i\n",userFS.FW_VER[0], userFS.FW_VER[1], userFS.FW_VER[2]);
-
-    printf("\n<0> Normal run. SmartConfig will\n    start if no valid connection exists.\n");
-    printf("<1> Connect using fixed SSID : %s\n", SSID);
-    printf("<2> SmartConfig.\n");
-    c = getchar();
-    switch (c)
-    {
-        case '0':
-            ForceFixedSSID = 0;
-            if(!userFS.FTC)
-            {
-                do_FTC();
-                wlan_stop();
-                printf("\nPress any key to run the socket demo...\n");
-                getchar();
-            }
-            break;
-        case '1':
-            ForceFixedSSID = 1;
-            break;
-        case '2':
-            ForceFixedSSID = 0;
-//            server_running = 1;
-            runSmartConfig = 1;
-            initTCPIP();
-//            server_running = 1;
-            RED_OFF;
-            GREEN_OFF;
-            BLUE_OFF;
-            printf("Press the reset button on your board........\n");
-            while(1)
-            {
-                GREEN_ON;
-                wait_ms(500);
-                GREEN_OFF;
-                wait_ms(500);
-            }
-        default:
-            printf("Wrong selection.\n");
-            printf("Reset the board and try again.\n");
-    }
-//    server_running = 0;
-    SmartConfigProfilestored = SMART_CONFIG_SET;
-    RED_OFF;
-    GREEN_OFF;
-    BLUE_OFF; 
-    runTCPIPserver();    // Run TCP/IP Connection to host
-}
+#include "mbed.h"
+#include "doTCPIP.h"
+#include "TSISensor.h"
+#include "TEMT6200.h"
+#include "WiGo_BattCharger.h"
+#include "MMA8451Q.h"
+#include "MAG3110.h"
+#include "MPL3115A2.h"
+#include "demo.h"
+#include "run_exosite.h"
+
+#define FCOUNTSPERG  4096.0F // sensor specific: MMA8451 provide 4096 counts / g in 2g mode
+#define FCOUNTSPERUT   10.0F // sensor specific: MAG3110 provide 10 counts / uT
+
+// Serial USB port
+Serial pc(USBTX, USBRX);
+
+// Slide sensor
+TSISensor tsi;
+
+// Systick
+Ticker systick;
+
+// Ambient light sensor : PTD5 = enable, PTB0 = analog input
+TEMT6200 ambi(PTD5, PTB0);
+
+//Wi-Go battery charger control
+WiGo_BattCharger Batt(CHRG_EN1, CHRG_EN2, CHRG_SNS_EN, CHRG_SNS, CHRG_POK, CHRG_CHG);
+
+// Accelerometer
+#define MMA8451_I2C_ADDRESS (0x1d<<1)
+MMA8451Q acc(PTE25, PTE24, MMA8451_I2C_ADDRESS);
+
+// Magnetometer
+MAG3110 mag(PTE0, PTE1);
+
+// altimeter-Pressure-Temperature (apt)
+#define MPL3115A2_I2C_ADDRESS (0x60<<1)
+MPL3115A2 apt( PTE0, PTE1, MPL3115A2_I2C_ADDRESS);
+
+
+volatile int ms5Flag;
+int secondFlag;
+int HsecondFlag;
+unsigned int seconds;
+unsigned int compass_type;
+unsigned short adc_sample3;
+float fcountperg = 1.0F / FCOUNTSPERG;
+float fcountperut = 1.0F / FCOUNTSPERUT;
+
+void accel_read(void)
+{
+    signed short resultx, resulty, resultz;
+    if(acc.isDataAvailable())
+    {
+        acc.getAccRawX(&resultx);
+        acc.getAccRawY(&resulty);
+        acc.getAccRawZ(&resultz);
+        if(compass_type == NED_COMPASS)
+        {
+            axis6.acc_x = resultx;
+            axis6.acc_y = -1 * resulty; // multiple by -1 to compensate for PCB layout
+            axis6.acc_z = resultz;
+        }
+        if(compass_type == ANDROID_COMPASS)
+        {
+            axis6.acc_x = resulty; // 
+            axis6.acc_y = -1 * resultx;
+            axis6.acc_z = resultz;
+        }
+        if(compass_type == WINDOWS_COMPASS)
+        {
+            axis6.acc_x = -1 * resulty; // 
+            axis6.acc_y = resultx;
+            axis6.acc_z = resultz;
+        }
+        axis6.fax = axis6.acc_x;
+        axis6.fay = axis6.acc_y;
+        axis6.faz = axis6.acc_z;
+        axis6.fGax = axis6.fax * fcountperg;
+        axis6.fGay = axis6.fay * fcountperg;
+        axis6.fGaz = axis6.faz * fcountperg;                    
+    }
+}        
+
+void readTempAlt(void) // We don't use the fractional data
+{
+    unsigned char raw_data[5];
+    if(apt.getAllDataRaw(&raw_data[0]))
+    {
+        axis6.temp = raw_data[3];
+        axis6.alt = ((raw_data[0] << 8) | raw_data[1]);
+
+    }
+}
+
+void readCompass( void )
+{
+    if(compass_type == NED_COMPASS)
+    {
+        axis6.mag_y = mag.readVal(MAG_OUT_X_MSB);      // x & y swapped to compenste for PCB layout
+        axis6.mag_x = mag.readVal(MAG_OUT_Y_MSB);      // 
+        axis6.mag_z = mag.readVal(MAG_OUT_Z_MSB);      //
+    }
+    if(compass_type == ANDROID_COMPASS)
+    {
+        axis6.mag_x = mag.readVal(MAG_OUT_X_MSB);      //
+        axis6.mag_y = mag.readVal(MAG_OUT_Y_MSB);      // 
+        axis6.mag_z = -1 * mag.readVal(MAG_OUT_Z_MSB); // negate to reverse axis of Z to conform to Android coordinate system
+    }
+    if(compass_type == WINDOWS_COMPASS)
+    {
+        axis6.mag_x = mag.readVal(MAG_OUT_X_MSB);      //
+        axis6.mag_y = mag.readVal(MAG_OUT_Y_MSB);      // 
+        axis6.mag_z = -1 * mag.readVal(MAG_OUT_Z_MSB); //
+    }
+    axis6.fmx = axis6.mag_x;
+    axis6.fmy = axis6.mag_y;
+    axis6.fmz = axis6.mag_z;
+    axis6.fUTmx = axis6.fmx * fcountperut;
+    axis6.fUTmy = axis6.fmy * fcountperut;
+    axis6.fUTmz = axis6.fmz * fcountperut;
+}   
+
+void set_dir_LED(void)
+{
+    GREEN_OFF;
+    RED_OFF;
+    BLUE_OFF;
+    
+    if((axis6.compass >= 353) || (axis6.compass <= 7))
+    {
+        GREEN_ON;
+    }
+    else
+    {
+        GREEN_OFF;
+    }
+    if(((axis6.compass >= 348) && (axis6.compass <= 357)) || ((axis6.compass >= 3) && (axis6.compass <= 12)))
+    {
+        BLUE_ON;
+    }
+    else
+    {
+        BLUE_OFF;
+    }
+    if((axis6.compass >= 348) || (axis6.compass <= 12)) return;
+    if(((axis6.compass >= 268) && (axis6.compass <= 272)) || ((axis6.compass >= 88) && (axis6.compass <= 92)))
+    {
+        RED_ON;
+        return;
+    }
+    if((axis6.compass >= 178) && (axis6.compass <= 182))
+    {
+        BLUE_ON;
+        RED_ON;
+        return;
+    }
+}
+
+void SysTick_Handler(void)
+{
+    static unsigned int ttt = 1;
+    int ts;
+    ms5Flag = 1;
+    ts = ttt & 0x3;
+    if(ts == 2) readCompass();
+    if(ts == 1) accel_read();
+    if(ts == 3)
+    {
+        run_eCompass();
+        newData = 1; // a general purpose flag for things that need to synch to the ISR
+        axis6.timestamp++;
+        if(!server_running) set_dir_LED(); // Set the LEDs based on direction when nothing else is usng them
+    }
+    if(ttt == 100)
+    {
+        LED_D1_ON;
+        if(seconds && (seconds < 15)) calibrate_eCompass();
+        readTempAlt();
+        axis6.light = ambi.readRaw(); // Light Sensor    
+        HsecondFlag = 1; // A general purpose flag for things that need to happen every 500ms   
+    }
+    if(ttt >= 200)
+    {
+        LED_D1_OFF;
+        ttt = 1;  
+        calibrate_eCompass();
+        Batt.sense_en(1);
+        adc_sample3 = Batt.level(); 
+        Batt.sense_en(0);
+        secondFlag = 1; // A general purpose flag for things that need to happen once a second
+        HsecondFlag = 1;
+        seconds++;
+        if(!(seconds & 0x1F)) do_mDNS = 1;          
+    } else ttt++;
+}
+
+int main()
+{
+    int loop;
+    int temp;
+    initLEDs();
+    Init_HostDriver();
+
+    // set current to 500mA since we're turning on the Wi-Fi
+    Batt.init(CHRG_500MA);
+
+    // Set MPL3115 to altimeter mode - oversample rate = 128
+    apt.Oversample_Ratio(OVERSAMPLE_RATIO_128);
+    apt.Altimeter_Mode();
+    
+    //Set baudrate to 115200 instead of the default 9600
+    pc.baud (115200);
+
+    printf("\n\n\nWi-Go Master V3.3\n");
+    printf("Firmware build version:  %s,  %s\n", __DATE__, __TIME__);
+    // Initalize global variables
+    axis6.packet_id = 1;
+    axis6.timestamp = 0;
+    axis6.acc_x = 0;
+    axis6.acc_y = 0;
+    axis6.acc_z = 0;
+    axis6.mag_x = 0;
+    axis6.mag_y = 0;
+    axis6.mag_z = 0;
+    axis6.roll = 0;
+    axis6.pitch = 0;
+    axis6.yaw = 0;
+    axis6.compass = 0;      
+    axis6.alt = 0;
+    axis6.temp = 0;
+    axis6.light = 0;
+    compass_type = ANDROID_COMPASS;
+    seconds = 0;
+    runSmartConfig = 0;
+    ulSmartConfigFinished = 0;
+    server_running = 1;
+    newData = 0;    
+    secondFlag = 0;
+    HsecondFlag = 0;
+    socket_active_status = 0xFFFF;
+    socket_active_status = SOCKET_STATUS_INIT_VAL;
+    ForceFixedSSID = 0;
+    GREEN_ON;
+
+    // Read the Magnetometer a couple of times to initalize
+    for(loop=0 ; loop < 5 ; loop++)
+    {
+        while(!(mag.readReg(MAG_DR_STATUS) && 0x08));
+        readCompass();
+    }
+
+    init_eCompass();
+
+    // Start 5ms Ticker
+    systick.attach(&SysTick_Handler, 0.005);
+
+    runSmartConfig = 0;
+    ulSmartConfigFinished = 0;
+    server_running = 1;
+    newData = 0;    
+    socket_active_status = SOCKET_STATUS_INIT_VAL;
+    ForceFixedSSID = 0;
+    
+    GREEN_ON;
+
+    // Trigger a WLAN device
+    wlan_start(0);
+    nvmem_read( NVMEM_USER_FILE_1_FILEID, sizeof(userFS), 0, (unsigned char *) &userFS);
+    nvmem_get_mac_address(myMAC);
+    print_mac();
+    wlan_stop();
+    printf("FTC        %i\n",userFS.FTC);
+    printf("PP_version %i.%i\n",userFS.PP_version[0], userFS.PP_version[1]);
+    printf("SERV_PACK  %i.%i\n",userFS.SERV_PACK[0], userFS.SERV_PACK[1]);
+    printf("DRV_VER    %i.%i.%i\n",userFS.DRV_VER[0], userFS.DRV_VER[1], userFS.DRV_VER[2]);
+    printf("FW_VER     %i.%i.%i\n",userFS.FW_VER[0], userFS.FW_VER[1], userFS.FW_VER[2]);
+
+    if(!userFS.FTC && !ForceFixedSSID)
+    {
+        do_FTC(); // Call First Time Configuration if SmartConfig has not been run, and fixed SSID is not enabled
+        wlan_stop();
+    }
+    server_running = 1;
+
+    // Wait for slider touch
+    printf("\nUse the slider to start an application.\nThe RGB LED indicates the selection:\n");
+    printf("PURPLE - Force SmartConfig.\n");
+    printf("BLUE   - Webserver displaying live sensor data.\n");
+    printf("RED    - Exosite data client.\n");
+    printf("GREEN  - Android sensor fusion app.\n");
+    while( tsi.readPercentage() == 0 )
+    {
+        RED_ON;
+        wait(0.2);
+        RED_OFF;
+        wait(0.2);
+    }
+    RED_OFF
+
+    seconds = 0;
+    loop = 100;
+    temp = 0;
+    // Read slider as long as it is touched.
+    // If released for more than 5 seconds, exit
+    while((loop != 0) || (seconds < 5))
+    {
+        loop = tsi.readPercentage() * 100;
+        if(loop != 0)
+        {
+            seconds = 0;
+            temp = loop;
+        }
+        if(temp > 75)
+        {
+            BLUE_ON;
+            RED_ON;
+            GREEN_OFF;
+        }
+        else if(temp > 50)
+        {
+            BLUE_ON;
+            GREEN_OFF;
+            RED_OFF;
+        }
+        else if(temp > 25)
+        {
+            BLUE_OFF;   
+            GREEN_OFF;
+            RED_ON;
+        }
+        else
+        {
+            BLUE_OFF;
+            GREEN_ON;
+            RED_OFF;
+        }
+    }
+    BLUE_OFF;
+    GREEN_OFF;
+    RED_OFF;
+
+    server_running = 0;
+    // Execute the user selected application
+    if(temp > 75)
+    { // Force SmartCOnfig
+        server_running = 1;
+        runSmartConfig = 1;
+        initTCPIP();
+        server_running = 1;
+        RED_OFF;
+        GREEN_OFF;
+        BLUE_OFF;
+        while(1)
+        {
+            printf("Reset system\n");
+            GREEN_ON;
+            secondFlag = 0;
+            while(!secondFlag);
+            secondFlag = 0;
+            GREEN_OFF;
+            while(!secondFlag);
+        }
+    } else SmartConfigProfilestored = SMART_CONFIG_SET; 
+
+    RED_OFF;
+    GREEN_OFF;
+    BLUE_OFF; 
+        
+    // Start the selected application
+    if(temp > 50)
+    {
+        compass_type = NED_COMPASS;
+        init_eCompass();
+        seconds = 0;
+        demo_wifi_main();           // Run Webserver
+    }
+    if(temp > 25)
+    {
+        compass_type = NED_COMPASS;
+        init_eCompass();
+        seconds = 0;
+        run_exosite();           // Send data to Exosite
+    }
+    init_eCompass();
+    seconds = 0;
+    runTCPIPserver();                                   // Run TCP/IP Connection to host
+}
+