So, you’ve got a shiny new arduino or cc3200 or atmel wifi board and now you’re wondering how to get your sensor data into the cloud using an HTTP POST packet?
You’re going to need 3 string buffers, One to hold your Sensor data (in POST format), one to hold the length of that buffer (in ASCII), and an arbitrarily large buffer to hold the entire outgoing HTTP packet. we’ll initialize them as follows:
unsigned char seBuffer; //Holds the full POST packet unsigned char sBuffer; //Holds out Sensor data in POST format unsigned char sBufferLen; //Holds the Sizeof sBuffer
Why did I use those buffer names? no idea. I just did. Call them whatever you want.
Now that we have our buffers, we need to get our sensor data into them. For that, we’ll use sprintf(), which does more or less the same thing the printf() does, but points the output to a string buffer. The first buffer we’ll fill holds our sensor data:
sprintf((char *)sBuffer, "command=%d&deviceid=%s&devicetype=%s&temperature=%d", 978,DeviceID,DeviceType,temperature);
Seems nice and easy, right? Next, we’ll get the string length of that buffer and store it in ASCII format, we’ll need it later:
sprintf((char *)sBufferLen, "%2d", (unsigned)strlen((char *)sBuffer));
Lastly, we piece it all together into a final assembled post packet in our largest buffer:
sprintf((char*) seBuffer, "POST %s HTTP/1.1\r\nHost: %s\r\n" "User-Agent: MyDeviceAgent/1.0\r\n" "Connection: close\r\n" "Content-Length: %s\r\n" "Content-Type: application/x-www-form-urlencoded\r\n\r\n" "%s\r\n\r\n", webappurl,servername,sBufferLen,sBuffer);
Now, load the entirety of seBuffer into your outgoing TCP socket. The full Packet looks like this:
POST /sensorheartbeat.html HTTP/1.1\r\nHost: mywebserver.com\r\n User-Agent: MyDeviceAgent/1.0\r\n Connection: close\r\n Content-Length: 59\r\n Content-Type: application/x-www-form-urlencoded\r\n\r\n command=978&deviceid=10001928&devicetype=15&temperature=235\r\n\r\n
Don’t forget to read back your values from the web server you’re hitting, that’s important information to let you know if your POST was successful.