CC3200 examples



http-client source code


Project on Hackaday



Toying with a "cloud" application.

http_client_demo project - remotely view your CC3200 data at www.cnktechlabs.com/data.html


The project is being developed with CC3200 wireless MCU LaunchPad development board. The LaunchPad development board has on-board a temperature sensor and an accelerometer. Both sensors use I2C bus for data transfer.

Recently I have started tinkering with the http_client_demo CC3200 example project. The code demonstrates different HTTP web services methods: like GET, POST, PUT, and DELETE. My goal is to write a code that will connect CC3200 wireless MCU board to my website and send temperature and accelerometer data over the internet. I am going to start with the GET method and then continue with the POST method.


GET method

The GET method sends URL page as well as data in a single string. The page and the encoded information are separated by the ? character.

http://www.cnktechlabs.com/get.php?name1=value1&name2=value2

The text that follows the ? is the query string.
The GET method is restricted to send upto 1024 characters only.

To test the GET method I have created and uploaded /get.php PHP file to my website (www.cnktechlabs.com/get.php).
String sent by CC3200 to www.cnktechlabs.com - "www.cnktechlabs.com/get.php?id=goodbye&mode=run"
Below is the php code for the get.php page.

get.php

<html>
<head><title>PHP Get Results</title></head>

<body>

	<?php
		echo "Hello CC3200, reading GET page \n\r"; //This message is echoed back to CC3200 board 
		// Show all URL parameters (and all form data submitted via the 'get' method)
		foreach($_GET as $key=>$value){
    			echo $key, ' => ', $value; //echo back "id => goodbye" and "mode => run"
    			echo"\n\r";//echo back new line
		}

		// Show a particular value.
		$id = $_GET['id'];//id=goodbye - sent from CC3200
		echo"\n\r";//echo back new line
		
		if($id) {
    			echo '<p/>ID: ', $id, "<br/>n"; //echo back "'<p/>ID: ', goodbye, "<br/>n"; "
    			echo"\n\r";//echo back new line
		}
		else {
    		echo '<p>No ID parameter.</p>';
		}
		//http://www.cnktechlabs.com/get.php?id=goodbye&mode=run 
	?>

</body>

</html>


To get responce from the php code shown above I send the following string (main.c):

#define GET_REQUEST_URI	"/get.php?id=goodbye&ampmode=run"	//the text that follows the ? is the query string
#define HOST_NAME	"cnktechlabs.com"



This is how I send request to www.cnktechlabs.com/get.php file:
GET(parameters)----------------------->www.cnktechlabs.com/get.php?id=goodbye&mode=run"

The get.php code receives data sent by the CC3200 development board and echoes it back.

Response from www.cnktechlabs.com/get.php file:
CC3200 (the response is printed on a serial interface)<----------www.cnktechlabs.com/get.php

Response from the server printed on a serial terminal:

<html>
<head><title>PHP Get Results</title>&lt;/head>

<body>

	Hello CC3200, reading GET page 

id => goodbye

mode => run

<p/>ID: goodbye<br/>n

</body>

</html>n

</body>

As you can see from the above printout the get.php page replies with page content that includes punctuation marks and html tags.


Using the GET method from the http_client_demo.c code example:

//*****************************************************************************
//
//! \brief HTTP GET Demonstration
//!
//! \param[in]  httpClient - Pointer to http client
//!
//! \return 0 on success else error code on failure
//!
//*****************************************************************************
static int HTTPGetMethod(HTTPCli_Handle httpClient)
{
  
    long lRetVal = 0;
    /*
     * GET /get.php HTTP/1.1
     * This line specifies an HTTP command, called a method, followed by the address of a
     * document and the version of the HTTP protocol being used. In this case, the request
     * is using the GET method to ask for the index.html document using HTTP 1.1. After
     * this initial line, the request can contain optional header information that gives the server
     * additional data about the request. For example:
     * User-Agent: Mozilla/5.0 (Windows 2000; U) Opera 6.0 [en]
     *
     */

    
    HTTPCli_Field fields[4] = {
                                {HTTPCli_FIELD_NAME_HOST, HOST_NAME},
                                {HTTPCli_FIELD_NAME_ACCEPT, "*/*"},	//Accept: image/gif, image/jpeg, text/*, */*
                                {HTTPCli_FIELD_NAME_CONTENT_LENGTH, "0"},
                                {NULL, NULL}
                            };
    bool        moreFlags;
    
    
    /* Set request header fields to be send for HTTP request. */
    HTTPCli_setRequestFields(httpClient, fields);

    /* Send GET method request. */
    /* Here we are setting moreFlags = 0 as there are no more header fields need to send
       at later stage. Please refer HTTP Library API documentaion @ HTTPCli_sendRequest
       for more information.
    */
    moreFlags = 0;

    lRetVal = HTTPCli_sendRequest(httpClient, HTTPCli_METHOD_GET, GET_REQUEST_URI, moreFlags);
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to send HTTP GET request.\n\r");
        return lRetVal;
    }


     lRetVal = readResponse(httpClient); //Currently returns all the text from get.php with text formatting (prints data to a serial port)

    return lRetVal;
}

The data is appended to the URL as a series of name/value pairs. After the URL web address has ended, we include a question mark (?) followed by the name/value pairs, each one separated by an ampersand (&).

Image below shows the image of the responce from the get.php webpage.

As you can see from above image the get.php responds with html tags and text inside the tags and text echoed from PHP.

POST method

A POST request passes parameters in the body of the HTTP request, leaving the URL untouched.


www.cnktechlabs.com/post.php

<html>
<head><title>PHP Post Method</title></head>

<body>

	<?php
		// The global $_POST variable allows you to access the data sent with the POST method by name
  		// To access the data sent with the GET method, you can use $_GET
  		//#define POST_DATA "say=Hi&to=Mom" ----> Hi Mom
  		$say = htmlspecialchars($_POST['say']);
  		$to  = htmlspecialchars($_POST['to']);

  		echo  $say, ' ', $to;
	?>

</body>

</html>


CC3200 Code

#define POST_DATA "say=Hi&to=Mom"
.....

//*****************************************************************************
//
//! \brief HTTP POST Demonstration
//!
//! \param[in]  httpClient - Pointer to http client
//!
//! \return 0 on success else error code on failure
//!
//*****************************************************************************
static int HTTPPostMethod(HTTPCli_Handle httpClient)
{
    bool moreFlags = 1;
    bool lastFlag = 1;
    char tmpBuf[4];
    long lRetVal = 0;
    //buf
    
    HTTPCli_Field fields[4] = {
                                    {HTTPCli_FIELD_NAME_HOST, HOST_NAME},
                                    {HTTPCli_FIELD_NAME_ACCEPT, "*/*"},
                                    {HTTPCli_FIELD_NAME_CONTENT_TYPE, "application/x-www-form-urlencoded"},
                                    {NULL, NULL}
                                };

    /* Set request header fields to be send for HTTP request. */
    HTTPCli_setRequestFields(httpClient, fields);

    /* Send POST method request. */
    /* Here we are setting moreFlags = 1 as there are some more header fields need to send
       other than setted in previous call HTTPCli_setRequestFields() at later stage.
       Please refer HTTP Library API documentaion @ref HTTPCli_sendRequest for more information.
    */
    moreFlags = 1;
    lRetVal = HTTPCli_sendRequest(httpClient, HTTPCli_METHOD_POST, POST_REQUEST_URI, moreFlags);
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to send HTTP POST request header.\n\r");
        return lRetVal;
    }

    sprintf((char *)tmpBuf, "%d", (sizeof(POST_DATA)-1));  // Size of POST data body

    /* Here we are setting lastFlag = 1 as it is last header field.
       Please refer HTTP Library API documentaion @ref HTTPCli_sendField for more information.
    */
    lastFlag = 1;
    lRetVal = HTTPCli_sendField(httpClient, HTTPCli_FIELD_NAME_CONTENT_LENGTH, (const char *)tmpBuf, lastFlag);
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to send HTTP POST request header.\n\r");
        return lRetVal;
    }


    /* Send POST data/body */
    lRetVal = HTTPCli_sendRequestBody(httpClient, POST_DATA, (sizeof(POST_DATA)-1));
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to send HTTP POST request body.\n\r");
        return lRetVal;
    }


    lRetVal = readResponse(httpClient);

    return lRetVal;
}


Server responce:
Hi Mom




The next step is to collect and send some data to a webpage. I have created post.php and data.html webpages to collect and display data. The Post.php file shown below is responsible for reading data from CC3200 board.

post.php page
	<?php
		$page = $_SERVER['PHP_SELF'];
		$sec = "10";
	?>

<html>
<head>
	<title>PHP Post Method</title>
	<meta http-equiv="refresh" content=";URL=''">
</head>

<body>

	<?php
		echo "Welcome to my PHP data page.";
		echo "<br>";
		echo "\n\r";
		echo "View your CC3200 data in real time."; // Echo back to CC3200
		echo "<br>";
		echo "\n\r";
  		 		
  		$acc = htmlspecialchars($_POST['acc']);		// Get accelerometer data
  		$accX = htmlspecialchars($_POST['accX']);	// Get accelerometer data X-axis
  		$accY = htmlspecialchars($_POST['accY']);	// Get accelerometer data Y-axis
  		$accZ = htmlspecialchars($_POST['accZ']);	// Get accelerometer data Z-axis
  		$sensortemp = htmlspecialchars($_POST['sensortemp']);	//Get temperature
		$loc = htmlspecialchars($_POST['loc']);
		  		
		//echo back to CC3200
  		echo  $acc, ' ', $accX, ' ', $accY, ' ', $accZ, ' ', $sensortemp, ' ', $loc;
  						
  		//The example below creates a new file called "data.html". 
  		//The file will be created in the same directory where the PHP code resides:
  		
  		$nl = "<br>";
  		$html_ = "<html>";
  		$body_ = "<body>";
  		$html_ = "<html>";
  		$html__ = "</html>";
  		$body__ = "</body>";
  		
  		$tmptr = "CC3200 Temperature inside the house: ";
  		$Accelerometer="CC3200 Accelerometer data:  ";
		
		//Local variables
  		$myloc = "My location is:  ";
		$head = "<head>";
		$head__ = "</head>";
		$close_html = "</div></div></div></body></html>";
		$paragraph = "<p>";
		$paragraph__ = "</p>";
  		 		
  		$myfile = fopen("data.html", "a+")or die("Unable to open file!");
  		
		fwrite($myfile, $nl);//<br>
		fwrite($myfile, $nl);//<br>

		fwrite($myfile, $paragraph);//"<p>"
		fwrite($myfile, $myloc);//"My location is:";
			
		fwrite($myfile, $loc);//Current Location 		
  		fwrite($myfile, $paragraph__);//"</p>		
  		
  		fwrite($myfile, $paragraph);//"<p>"
  		fwrite($myfile, $Accelerometer); 		
  		fwrite($myfile, $paragraph__);//"</p>"
 		
  		fwrite($myfile, $paragraph);//"<p>"
  		fwrite($myfile, $acc);  			
  		fwrite($myfile, $paragraph__);//"</p>"
  		
  		fwrite($myfile, $paragraph);//"<p>"
  		fwrite($myfile, $accX); 			
		fwrite($myfile, $paragraph__);//"</p>"
  		
  		fwrite($myfile, $paragraph);//"<p>"
  		fwrite($myfile, $accY);
  		fwrite($myfile, $paragraph__);//"</p>"
 		
  		fwrite($myfile, $paragraph);//"<p>"
  		fwrite($myfile, $accZ);  			
  		fwrite($myfile, $paragraph__);//"</p>"
  		
  		//Print temperature
  		fwrite($myfile, $paragraph);//"<p>"
  		fwrite($myfile, $tmptr);
  		//fwrite($myfile, &space);
  		fwrite($myfile, $sensortemp);
  		//fwrite($myfile, $nl);
  		fwrite($myfile, $paragraph__);//"</p>"
  		  		
  		
  		// Close file
  		fclose($myfile);
  		
	?>

	
</body>

</html>

 	

main.c:

while(1){
    	
	for (delay_cntr = 0; delay_cntr < 4; delay_cntr++){
		MAP_UtilsDelay(40000000);//2.5 sec delay
	}
	AccSample(); //Just do a single reading for now. TODO: Make Async.
	SetAccAvg(); //Read Acc

	TMP006DrvGetTemp(&sensorTemp);// Read temperature
   	
	//Read GPIO3: pin58 - Light Sensor
	GPIO_IF_GetPortNPin(SH_GPIO_3,&uiGPIOPort,&pucGPIOPin);
	Lght = GPIO_IF_Get(SH_GPIO_3,uiGPIOPort,pucGPIOPin);//Read light sensor
    	
	cx = snprintf(buf, 99, "acc=%.0f & accX=%.0f & accY=%.0f & accZ=%.0f & sensortemp=%.2f",
		g_accTotalAvg,
		g_accXAvg,
		g_accYAvg,
		g_accZAvg,
		sensorTemp );//cx is indice of the last buf[cx]
	if (cx>=0 && cx<99)	{// check returned value    		
		if (Lght == 0){
			strPtr1 = "& Light=Light is  ON";//74
		}
		else{
			strPtr1 = "& Light=Light is OFF";
		}

		strcpy ( &buf[(cx - 1)], strPtr1 );

		strPtr = " & loc=Los Angeles \0";	// Your location. (95)
		
		//Sring sent to the post.php page:
		//"acc=26 & accX=xx & accY=xx & accZ=xx & sensortemp=xx.xx & Light=Light is OXX & loc=xxxxxxxxxx \0"	
		strcpy ( &buf[(76)], strPtr );
	}

	UART_PRINT(buf);
	UART_PRINT("\n\r");

	for (delay_cntr = 0; delay_cntr < 4; delay_cntr++){
		MAP_UtilsDelay(40000000);//2.5 sec delay
	}

	lRetVal = HTTPPostMethod_data(&httpClient);
	UART_PRINT("\n\r");
	if(lRetVal < 0)
	{
		UART_PRINT("HTTP Post with Temperature and Accelerometer Data failed.\n\r");
	}
	//UART_PRINT("HTTP Post with Temperature and Accelerometer Data End:\n\r");

}



HTTPPostMethod_data function, shown below, will send temperature, accelerometer, and location data to the post.php file.

main.c file:
	
static int HTTPPostMethod_data(HTTPCli_Handle httpClient)
{
    bool moreFlags = 1;
    bool lastFlag = 1;
    char tmpBuf[4];
    long lRetVal = 0;
    
    HTTPCli_Field fields[4] = {
                                    {HTTPCli_FIELD_NAME_HOST, HOST_NAME},
                                    {HTTPCli_FIELD_NAME_ACCEPT, "*/*"},
                                    {HTTPCli_FIELD_NAME_CONTENT_TYPE, "application/x-www-form-urlencoded"},
                                    {NULL, NULL}
                                };

    /* Set request header fields to be send for HTTP request. */
    HTTPCli_setRequestFields(httpClient, fields);

    /* Send POST method request. */
    /* Here we are setting moreFlags = 1 as there are some more header fields need to send
       other than setted in previous call HTTPCli_setRequestFields() at later stage.
       Please refer HTTP Library API documentaion @ref HTTPCli_sendRequest for more information.
    */
    moreFlags = 1;
    lRetVal = HTTPCli_sendRequest(httpClient, HTTPCli_METHOD_POST, POST_REQUEST_URI, moreFlags);//POST & post.php
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to send HTTP POST request header.\n\r");
        return lRetVal;
    }
   
    sprintf((char *)tmpBuf, "%d", (sizeof(buf)-1));  // Size of POST data body - 99 bytes
    
    /*
     * Here we are setting lastFlag = 1 as it is last header field.
     * Please refer HTTP Library API documentaion @ref HTTPCli_sendField for more information.
     * Send the length of sent data
    */
    lastFlag = 1;
    lRetVal = HTTPCli_sendField(httpClient, HTTPCli_FIELD_NAME_CONTENT_LENGTH, (const char *)tmpBuf, lastFlag);
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to send HTTP POST request header.\n\r");
        return lRetVal;
    }


    /* Send POST data/body */
    lRetVal = HTTPCli_sendRequestBody(httpClient, buf, (sizeof(buf)-1)); // POST data body
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to send HTTP POST request body.\n\r");
        return lRetVal;
    }


    lRetVal = readResponse(httpClient);

    return lRetVal;
}	

int main()
{
    long lRetVal = -1;

    HTTPCli_Struct httpClient;
    //char c = 0;


    //
    // Board Initialization
    //
    BoardInit();

    //
    // Configure the pinmux settings for the peripherals exercised
    //
    PinMuxConfig();

    //
    // Configuring UART
    //
    InitTerm();

    //************************************************************************

    //
    // Display banner
    //
    DisplayBanner(APP_NAME);

    InitializeAppVariables();

    lRetVal = ConnectToAP();
    if(lRetVal < 0)
    {
    	LOOP_FOREVER();
    }

    lRetVal = ConnectToHTTPServer(&httpClient);
    if(lRetVal < 0)
    {
        LOOP_FOREVER();
    }


    //
    // I2C Init	I2C Init I2C Init I2C Init I2C Init I2C Init I2C Init
    //
    lRetVal = I2C_IF_Open(I2C_MASTER_MODE_FST);
    if(lRetVal < 0)
    {
    	ERR_PRINT(lRetVal);
        LOOP_FOREVER();
    }

    //Init Temprature Sensor Init Temprature Sensor Init Temprature Sensor
    lRetVal = TMP006DrvOpen();
    if(lRetVal < 0)
    {
    	ERR_PRINT(lRetVal);
        LOOP_FOREVER();
    }

    //Init Accelerometer Sensor Init Accelerometer Sensor Init Accelerometer Sensor
    lRetVal = BMA222Open();
    if(lRetVal < 0)
    {
    	ERR_PRINT(lRetVal);
    	LOOP_FOREVER();
    }

    float sensorTemp;

    AccSample(); // Just do a single reading for now. TODO: Make Async.
    SetAccAvg(); // g_accXAvg, g_accYAvg, g_accZAvg, g_accTotalAvg


    TMP006DrvGetTemp(&sensorTemp);
    
    snprintf(buf, 99, "acc=%.0f & accX=%.0f & accY=%.0f & accZ=%.0f & sensortemp=%.2f",
                        g_accTotalAvg,
                        g_accXAvg,
                        g_accYAvg,
                        g_accZAvg,
                        sensorTemp );
    UART_PRINT(buf);
	
	UART_PRINT("\n\r");
    UART_PRINT("HTTP Delete Begin:\n\r");
    lRetVal = HTTPDeleteMethod(&httpClient);

    if(lRetVal < 0)
    {
    	UART_PRINT("HTTP Delete failed.\n\r");
    }
    UART_PRINT("HTTP Delete End:\n\r");


    UART_PRINT("\n\r");
    UART_PRINT("HTTP Put Begin:\n\r");
    lRetVal = HTTPPutMethod(&httpClient);
    if(lRetVal < 0)
    {
    	UART_PRINT("HTTP Put failed.\n\r");
    }
    UART_PRINT("HTTP Put End:\n\r");

    UART_PRINT("\n\r");
    UART_PRINT("HTTP Get Begin:\n\r");
    lRetVal = HTTPGetMethod(&httpClient);
    if(lRetVal < 0)
    {
    	UART_PRINT("HTTP Post Get failed.\n\r");
    }
    UART_PRINT("HTTP Get End:\n\r");
    UART_PRINT("\n\r");

    int cx;
    const char *strPtr;
    while(1){

    	MAP_UtilsDelay(40000000);

    	AccSample(); // Just do a single reading for now. TODO: Make Async.
    	SetAccAvg(); // g_accXAvg, g_accYAvg, g_accZAvg, g_accTotalAvg

    	TMP006DrvGetTemp(&sensorTemp);
    	
    	cx = snprintf(buf, 99, "acc=%.0f & accX=%.0f & accY=%.0f & accZ=%.0f & sensortemp=%.2f",
    	    	 g_accTotalAvg,
    	    	 g_accXAvg,
    	    	 g_accYAvg,
    	    	 g_accZAvg,
    	    	 sensorTemp );//cx is indice of the last buf[cx]
    	if (cx>=0 && cx<99)	{// check returned value   		
    		strPtr = " & loc=Los Angeles \0";   		// Your location. 
    		strcpy ( &buf[(cx - 1)], strPtr );
    	}

    	UART_PRINT(buf);
    	UART_PRINT("\n\r");

    	MAP_UtilsDelay(40000000);
    	lRetVal = HTTPPostMethod_data(&httpClient);
    	UART_PRINT("\n\r");
    	
    	if(lRetVal < 0)
    	{
    		UART_PRINT("HTTP Post with Temperature and Accelerometer Data failed.\n\r");
    	 }
    	    //UART_PRINT("HTTP Post with Temperature and Accelerometer Data End:\n\r");

    }

    // Stop the CC3200 device

    //LOOP_FOREVER();
}	

	


Below is the result I can view on my data.html webpage.

Image of the serial print out on the Termite Terminal

Below is the result I can view on my data.html webpage.

A new hardware addition to the project - Light Sensor

Light Sensor senses ambient light and transmits messages to the web page. The data out, DO, pin of the sensor is connected to GPIO_03, PIN_58 on the development board.


Current Project Circuit Diagram


Project Source Code

Settings for the serial port: 115200, 8N1, no handshake.
Enter PASSWORD and SSID name in the "common.h" file
Change location (strPtr = " & loc=Los Angeles \0"; // Your location.) to your geographical location in the source code main file.
Flush the project into your CC3200 board, and view the results on the www.cnktechlabs.com/data.html. Connect CC3200 to a serial terminal on your PC.
Reset the board.
To enter password and SSID name either:
Press and hold SW2 and reset the board
On prompt "Enter Password" enter WiFi password
On prompt "SSID name" enter WiFi name.
Or just reset the board and the common.h credentials will be used.