temptodb.py – Interface to write temperatures to db


#! /usr/bin/python3

import pymysql
from datetime import datetime

#Read the temperatures from the files
#Since rpi-central has two sensors (upstairs and outside), it will write both temperatures in the same file
fliving = open('/tmp/192.168.0.101', 'r')
tliving = fliving.read()
fliving.close()

fupstairs = open('/tmp/192.168.0.100', 'r')
tupstairs = fupstairs.read()
fupstairs.close()

#Write 0 in the file to make sure sensors offline are noticed
fliving = open('/tmp/192.168.0.101', 'w')
fliving.write('0')
fliving.close()

fupstairs = open('/tmp/192.168.0.100', 'w')
fupstairs.write('0 0')
fupstairs.close()

print ("Temperature living:", tliving)
tup, tout = tupstairs.split()
print ("Temperature upstairs:", tup)
print ("Tempearture outside:", tout)

#Write temperatures to the database
con = pymysql.connect('localhost', '', '', '')
cur = con.cursor()
moment = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cur.execute("INSERT INTO temperatures VALUES (%s, %s, %s, %s)", (moment, tliving, tup, tout))
con.commit()

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>