MySQL for the Internet of Things

(Steven Felgate) #1
Chapter 4 ■ Data transformation

While this example shows how to save the sensor name with the data, it would be equally easy to add
more text on the end of the line of output by simply appending the string. For example, you could add a note
at the end of the string as follows. Here I’ve added a method, which returns the user’s input from a prompt
(or web form).


...
strData += ", Barometric sensor: ";
strData += read_sensor(2);
strData += " Notes: ";
strData += read_user_input();
log_file.println(strData);


To implement a similar annotation in Python, you would use code such as shown in Listing 4-2. Here, I
reproduce the results that the Arduino code generated. That is, I write the same data, but I use a completely
different method. To help understand some of the formatting, I include the entire code.


Listing 4-2. Simple Annotation (Python)


from random import random, randint
import string


def read_sensor(sensor_num):
if (sensor_num == 1):
return 90.125 + random()*10 # sensor #1
elif (sensor_num == 2):
return 14.512313 + random() # sensor #2
else:
if (randint(0,25) >= 5):
return randint(0,14)/10.00
else:
return -randint(0,14)/10.00


strData = "Temperature sensor: {0:.2f}, Barometric sensor: {1:.2f}\n"
file_log = open("data_log_python.txt", 'a')
file_log.write(strData.format(read_sensor(1), read_sensor(2)))
file_log.close()


Here you see an example of string formatting using the format() method. Notice how I use formatting
codes as presented in the string named strData to limit the output to two decimal points such as {0:.2f}
and {1:.2f}. These codes tell the format() method to substitute the first and second parameters (read_
sensor(1) and read_sensor(2)), formatting the data as a floating-point number with two decimal places.
While this example was basic and meant to be an example, most developers would likely not save the
name of the event or sensor with every row. What is more likely is you would write the name of the sensors
as a header line at the beginning of the file. This way, you always know what the columns of data mean. In
fact, this is precisely how you would use annotations like this in a database solution.


Database Considerations


Annotation with text is easy to do in the database. If we want to include the name or type of the sensor, we
can simply name the column of the table accordingly. In this way, the columns names describe the data. For
example, if we had a table to store the rows from the examples in this section, the table may look something

Free download pdf