Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 9 ■ IOT PATTERNS: LOCATION AWARE


Data Publish


The fourth section of code, as provided in Listing 9-7 , defines the variables, constants,
and functions that are going to be used for creating and sending an HTTP request to the
server. This code is a slightly modified version of the HTTP GET that you developed in
Chapter 3.
The main modification in this code is its ability to open and close a connection to
the server repeatedly. Apart from that, make sure to change the server and port values to
your PHP server’s values, requestData variables and the URL values.


Listing 9-7. HTTP Publish


//IP address of the server
char server[] = {"bookapps.codifythings.com"};
int port = 80;


unsigned long lastConnectionTime = 0;
const unsigned long postingInterval = 10L * 1000L;


void transmitSensorData(float latitude, float longitude)
{
// Read all incoming data (if any)
while (client.available())
{
char c = client.read();
}


if (millis() - lastConnectionTime > postingInterval)
{
client.stop();


Serial.println("[INFO] Connecting to Server");


String requestData = "clientID=Sheep1&latitude=" + String(latitude)



  • "&longitude=" + String(longitude);
    Serial.println("[INFO] Query String: " + requestData);


// Prepare data or parameters that need to be posted to server
if (client.connect(server, port))
{
Serial.println("[INFO] Server Connected - HTTP GET Started");


// Make a HTTP request:
client.println("GET /gpstracker/update.php?" + requestData +
" HTTP/1.1");
client.println("Host: " + String(server));

Free download pdf