Fix sensor validation, MySQL retries, and chart query bugs.
Reject implausible readings, close DB connections on retry, and return chart data in chronological order. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
+43
-24
@@ -2,34 +2,53 @@
|
||||
##
|
||||
## Script to read the last temperature and humidity readings from a MySQL database
|
||||
##
|
||||
import sys
|
||||
import time
|
||||
import MySQLdb
|
||||
|
||||
NO_PREVIOUS = ('NULL', 'NULL')
|
||||
|
||||
|
||||
def main(host, db, user, passwd, logging, sql_retries, sql_timeout):
|
||||
logging.debug('Reading MySQL database next ...')
|
||||
connection = MySQLdb.connect(host,user,passwd,db)
|
||||
cursor=connection.cursor()
|
||||
sql = """SELECT Temperature, Humidity FROM TempHumid ORDER BY ComputerTime DESC LIMIT 1"""
|
||||
success = False
|
||||
attempts = 0
|
||||
while attempts < sql_retries and not success:
|
||||
|
||||
sql = (
|
||||
'SELECT Temperature, Humidity FROM TempHumid '
|
||||
'ORDER BY ComputerTime DESC LIMIT 1'
|
||||
)
|
||||
|
||||
for attempt in range(sql_retries):
|
||||
connection = None
|
||||
try:
|
||||
connection = MySQLdb.connect(host, user, passwd, db)
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(sql)
|
||||
data = cursor.fetchall()
|
||||
for row in data :
|
||||
temp = row[0]
|
||||
humid = row[1]
|
||||
oldtemp = float(temp)
|
||||
oldhumid = float(humid)
|
||||
logging.debug('The MySQL database was successfully read.')
|
||||
connection.commit()
|
||||
row = cursor.fetchone()
|
||||
cursor.close()
|
||||
logging.debug('The previous temperature was: {0}C and the previous humidity was {1}%'.format(oldtemp, oldhumid))
|
||||
success = True
|
||||
except MySQLdb.Error, e:
|
||||
logging.warn('The MySQL database could not be read and returned the following error %d: %s', (e.args[0], e.args[1]))
|
||||
attempts += 1
|
||||
if attempts == sql_retries:
|
||||
logging.error('All configured attempts to read the MySQL database have failed. We are going to skip this attempt.')
|
||||
time.sleep(sql_interval)
|
||||
return oldtemp, oldhumid
|
||||
|
||||
if row is None:
|
||||
logging.info('No previous readings found in database.')
|
||||
return NO_PREVIOUS
|
||||
|
||||
oldtemp = float(row[0])
|
||||
oldhumid = float(row[1])
|
||||
logging.debug(
|
||||
'Previous temperature: %sC, previous humidity: %s%%',
|
||||
oldtemp, oldhumid,
|
||||
)
|
||||
return oldtemp, oldhumid
|
||||
except MySQLdb.Error as e:
|
||||
logging.warn(
|
||||
'MySQL read failed (attempt %d/%d): %d: %s',
|
||||
attempt + 1, sql_retries, e.args[0], e.args[1],
|
||||
)
|
||||
if attempt + 1 >= sql_retries:
|
||||
logging.error(
|
||||
'All configured attempts to read the MySQL database have failed.'
|
||||
)
|
||||
return NO_PREVIOUS
|
||||
time.sleep(sql_timeout)
|
||||
finally:
|
||||
if connection is not None:
|
||||
connection.close()
|
||||
|
||||
return NO_PREVIOUS
|
||||
|
||||
Reference in New Issue
Block a user