Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 3 ■ COMMUNICATION PROTOCOLS

Data Publish


The third section of the code defines variables, constants, and functions that are going to
be used for sending data to the server using HTTP.
As provided in Listing 3-1 , you first define the address and port of server that
Arduino will connect to and send data. For the purposes of this project, you can publish
it to http://www.httpbin.org , which is an openly available test server that simply echoes all the
request information along with some additional information. In future projects, you will
use servers that process the request data.


Listing 3-1. Variables to Define the HTTP Server


char server[] = {"www.httpbin.org"};
int port = 80;


The doHttpGet() function provided in Listing 3-2 encapsulates all the details of
preparing the request for the GET method, connecting to the server and sending request.
Attempt to connect to the server using client.connect(server, port) in an IF
condition. If the connection is successful, then prepare the request.
In a request that uses the GET method, data is sent as part of the URL in a name/
value pair format, for example, http://www.httpbin.org/get?temperatureSensor=
85&metric=F. The example shows that two parameters will be sent, the first is the
temperatureSensor with a value of 85 and the second is metric with a value of F.
Finally, transmit the HTTP request to the server using the client.println()
method. This method will send the commands to the server over the network and then
receive any response from the server.


Listing 3-2. HTTP GET Request


void doHttpGet()
{
// Prepare data or parameters that need to be posted to server
String requestData = "requestVar=test";


// Check if a connection to server:port was made
if (client.connect(server, port))
{
Serial.println("[INFO] Server Connected - HTTP GET Started");


// Make HTTP GET request
client.println("GET /get?" + requestData + " HTTP/1.1");
client.println("Host: " + String(server));
client.println("Connection: close");
client.println();
Serial.println("[INFO] HTTP GET Completed");
}

Free download pdf