MySQL for the Internet of Things

(Steven Felgate) #1
ChapTEr 8 ■ DEmonsTraTion of high availabiliTy TEChniquEs


  • Data saved to the local file should be written to the onboard SD card.

  • When the database is connected and there is data in the local file, read the data and
    insert it into the database.

  • Cached data should store the correct date and time for the sample collection.


Let’s examine each of these requirements and determine what the code should be for each. But first,
let’s consider a high-level algorithm we can use to encapsulate the mechanism. The following is a high-level
overview of the loop() method, that is, the “main” procedure that drives the sketch. We’ll see the setup
in Listing 8-7 later in this section. I find writing an algorithm like this helpful in organizing your sketch.
Not only does it help identify major methods needed, but by keeping the code at a high level, it provides a
template for the code in the loop() method that is easy to read and can help verify that the requirements are
identified in the code.


read_sample()
if then
cache_data() // save data to the file
else
dump_cache() // read data from file and insert into database
write_data() // save current sample
end if


So, now we see that we will need three major methods along with some means to detect whether the
database connection has failed. Let’s go through each of these and discuss them beginning with reading
the sample. Since we are using an analog sensor, we can read the sensor with the analogRead() method, as
shown here:


value = analogRead(sensorPin);


Next, let’s consider the requirement to detect when the connection to the database fails. One way to
do this is to use the connected() method in the Connector/Arduino library, but this will tell you only if the
connection opened previously is still open. It should be noted that even if the database server goes offline, it
could take some time for the connected() method to return false (connection lost).
A better mechanism is to attempt a connect() each time through the loop and then close() after the
data is saved. The connect() method returns much more quickly should the server be unreachable. Now
when we use the connected() method, it returns immediately that the database server is not connected.
The following shows an excerpt of how to set this up in the code:


// Attempt to connect to the database server
if (!conn.connected()) {
if (conn.connect(server_addr, 3306, user, password)) {
...
}
}
...
conn.close();


You have already seen an example of how to write data to a file on the SD card. Recall it requires the SD
library and code to open a file, write the data, and then close the file. The only tricky part is we must get the
date and time string and write that to the file, preserving when the sample was taken. You already saw how to
read date and time from the RTC, so that code is also familiar.

Free download pdf