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:
2026-08-14 19:40:49 +08:00
co-authored by Cursor
parent c6616bd855
commit 6f12d2c459
8 changed files with 387 additions and 286 deletions
+36 -22
View File
@@ -2,33 +2,47 @@
##
## Script to import the temperature and humidity into a MySQL database
##
import sys
import time
import MySQLdb
def main(temp, humid, host, db, user, passwd, logging, sql_retries, sql_timeout):
logging.debug('Temp = {0} *C, Hum = {1} %'.format(temp, humid))
logging.debug('Updating MySQL database next ...')
connection = MySQLdb.connect(host,user,passwd,db)
cursor=connection.cursor()
sqltemp=format(temp, '5.1f')
sqlhumid=format(humid, '5.1f')
logging.info('Temperature: {0}*C Humidity: {1}% ... updating to MySQL database'.format(sqltemp, sqlhumid))
sql = """INSERT INTO TempHumid (ComputerTime, Temperature, Humidity, id) VALUES (unix_timestamp(now()), %s, %s, NULL)"""
args = (sqltemp, sqlhumid)
success = False
attempts = 0
while attempts < sql_retries and not success:
def main(temp, humid, host, db, user, passwd, logging, sql_retries, sql_timeout):
logging.debug('Temp = %s *C, Hum = %s %%', temp, humid)
logging.debug('Updating MySQL database next ...')
sql = (
'INSERT INTO TempHumid (ComputerTime, Temperature, Humidity, id) '
'VALUES (unix_timestamp(now()), %s, %s, NULL)'
)
args = (format(temp, '5.1f'), format(humid, '5.1f'))
logging.info(
'Temperature: %s*C Humidity: %s%% ... updating to MySQL database',
args[0], args[1],
)
for attempt in range(sql_retries):
connection = None
try:
connection = MySQLdb.connect(host, user, passwd, db)
cursor = connection.cursor()
cursor.execute(sql, args)
connection.commit()
cursor.close()
success = True
logging.debug('The MySQL database was successfully updated.')
except MySQLdb.Error, e:
logging.warn('The MySQL database could not be updated 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 update the MySQL database have failed. We are going to skip this attempt.')
time.sleep(sql_interval)
return 0
return 0
except MySQLdb.Error as e:
logging.warn(
'MySQL update 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 update the MySQL database have failed.'
)
return 1
time.sleep(sql_timeout)
finally:
if connection is not None:
connection.close()
return 1