MySQL for the Internet of Things

(Steven Felgate) #1

Chapter 4 ■ Data transformation


If you want to do something similar in Python and your platform has an RTC on board, the code is
rather easy. You simply add the date and time as shown in Listing 4-5. I include the entire code here so you
can see the supporting code for reading the date and time.


Listing 4-5. Date and Time Annotation (Python)


from datetime import datetime
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


def get_datetime():
return datetime.strftime(datetime.now(), "%m/%d/%Y %H:%M:%S")


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


Notice we used a method to get and format the date and time in a similar way as we did in the Arduino
code. However, Python has more advanced methods (borrowed from C, of course) that we can use to format
the date and time using a string containing format codes. Notice the get_datetime() method. We get use
the method from the datetime class named strftime() to create a string from the current date and time
from the datetime.now() method. The format string is then used by the strftime() method. The output of
this code is similar to the Arduino code.


Temperature sensor: 92.33, Barometric sensor: 15.23 Datetime: 11/07/2015 22:36:32
Temperature sensor: 90.72, Barometric sensor: 15.32 Datetime: 11/07/2015 22:36:48
Temperature sensor: 94.38, Barometric sensor: 15.13 Datetime: 11/07/2015 22:36:50
Temperature sensor: 96.74, Barometric sensor: 14.95 Datetime: 11/07/2015 22:36:50


If your low-cost computer board does not have an RTC, you may be able to add one if the board has an
I2C interface and sufficient support in the operating system for the RTC. For example, you can add an RTC
to the Raspberry Pi. Adafruit has an excellent tutorial for this at https://learn.adafruit.com/adding-
a-real-time-clock-to-raspberry-pi/overview. Once you have added the clock, your Python (or other
language) scripts will get the correct date and time from the operating system primitives.

Free download pdf