CC3200 examples



http-client source code



Toying with a "cloud" application.

GET method


Recently I have started tinkering with the http_client_demo CC3200 example project. The code demonstrates different HTTP methods, like GET, POST, PUT, and DELETE. To test the GET method I have created and uploaded /get.php PHP file to my website (www.cnktechlabs.com/get.php).

get.php

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

<body>

	<?php
		echo "Hello CC3200, reading GET page \n\r";//Shows up on the UART terminal
		//https://www.caveofprogramming.com/php-tutorial/php-get-and-post-getting-url-parameters-and-form-data-in-php.html
		// Show all URL parameters (and all form data submitted via the 'get' method)
		foreach($_GET as $key=>$value){
    		echo $key, ' => ', $value;
    		echo"\n\r";
		}

		// Show a particular value.
		$id = $_GET['id'];
		echo"\n\r";
		
		if($id) {
    		echo '<p/>ID: ', $id, "<br/>n";
    		echo"\n\r";
		}
		else {
    		echo '<p>No ID parameter.</p>';
		}
		//http://cnktechlabs.com/get.php?id=goodbye&mode=run 
		//https://www.caveofprogramming.com/php-tutorial/php-get-and-post-getting-url-parameters-and-form-data-in-php.html
	?>

</body>

</html>

To get responce from the php code shown above I send the following string (CC3200 - http_client_demo):

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


Request to www.cnktechlabs.com/get.php:
GET(parameters)----------------------->www.cnktechlabs.com/get.php?id=goodbye&mode=run"
Responce www.cnktechlabs.com/get.php:
CC3200 (serial interface)<-------------www.cnktechlabs.com/get.php

Responce from the server printed on a serial terminal:

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

<body>

	Hello CC3200, reading GET page 

id => goodbye

mode => run

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

</body>

</html>n

</body>

Using the GET method from the http_client_demo 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.


POST method


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 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
    
    /*
     * 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, POST_DATA, (sizeof(POST_DATA)-1));
    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";   		
    		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.



Project Source Code