From 6f12d2c4593ecf803a2f2a0f404101c0d9a66e65 Mon Sep 17 00:00:00 2001 From: Jonny Ervine Date: Fri, 14 Aug 2026 19:40:49 +0800 Subject: [PATCH] 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 --- TODO | 4 +- getData.php | 53 ++++--- python_code/readMysql.py | 67 ++++++--- python_code/temp-humid-read-loop.py | 203 ++++++++++---------------- python_code/temp-humid-read-single.py | 159 +++++++++----------- python_code/thmonitor_common.py | 128 ++++++++++++++++ python_code/updateMysql.py | 58 +++++--- temp-humid-chart.html | 1 - 8 files changed, 387 insertions(+), 286 deletions(-) create mode 100644 python_code/thmonitor_common.py diff --git a/TODO b/TODO index e96223f..0f37c20 100644 --- a/TODO +++ b/TODO @@ -1,4 +1,6 @@ ## TO DO LIST - - Update the single run python script so that it reads the MySQL database for the previous values of temperature and humidity, as it doesn't loop and therefore doesn't maintain the previous readings. + - Consider migrating from the legacy Python 2 / dhtreader.so stack to a maintained + DHT library (e.g. Adafruit CircuitPython or lgpio-based driver) for current Pi OS releases. + - Externalize getData.php database credentials into a config file outside the web root. diff --git a/getData.php b/getData.php index 92beb51..3d000d0 100644 --- a/getData.php +++ b/getData.php @@ -4,42 +4,47 @@ $username = "USERNAME"; $password = "PASSWORD"; $dbname = "Monitoring"; -$rows = array(); $table = array(); $table['cols'] = array( - // Labels for your chart, these represent the column titles array('label' => 'Date and Time', 'type' => 'number'), array('label' => 'Temperature', 'type' => 'number'), array('label' => 'Humidity', 'type' => 'number') -); +); -// Create connection -//$conn = new mysqli($servername, $username, $password, $dbname); $conn = mysqli_connect($servername, $username, $password, $dbname); -// Check connection -if ($conn->connect_error) { - die("Connection failed: " . $conn->connect_error); +if (!$conn) { + header('HTTP/1.1 500 Internal Server Error'); + header('Content-type: application/json'); + echo json_encode(array('error' => 'Connection failed: ' . mysqli_connect_error())); + exit; } -$sql = "SELECT ComputerTime, Temperature, Humidity from TempHumid ORDER BY id DESC LIMIT 360"; -$result = mysqli_query($conn,$sql); +$sql = "SELECT ComputerTime, Temperature, Humidity FROM (" + . "SELECT ComputerTime, Temperature, Humidity FROM TempHumid " + . "ORDER BY id DESC LIMIT 360" + . ") AS recent ORDER BY ComputerTime ASC"; +$result = mysqli_query($conn, $sql); -//if ($result->num_rows > 0) { - // output data of each row - while($row = mysqli_fetch_array($result)) { - $temp = array(); -// $datetime = date('d/m/Y H:i', $row[0]); -// $temp[] = array('v' => $datetime); - $temp[] = array('v' => $row[0]); - $temp[] = array('v' => $row[1]); - $temp[] = array('v' => $row[2]); - $rows[] = array('c' => $temp); +$rows = array(); +if ($result) { + while ($row = mysqli_fetch_array($result)) { + $temp = array(); + $temp[] = array('v' => (float)$row[0]); + $temp[] = array('v' => (float)$row[1]); + $temp[] = array('v' => (float)$row[2]); + $rows[] = array('c' => $temp); } -//} else { -// echo "No current temperature - ERROR?"; -//} + mysqli_free_result($result); +} else { + header('HTTP/1.1 500 Internal Server Error'); + header('Content-type: application/json'); + echo json_encode(array('error' => 'Query failed: ' . mysqli_error($conn))); + mysqli_close($conn); + exit; +} + $table['rows'] = $rows; header('Content-type: application/json'); echo json_encode($table); -$conn->close(); +mysqli_close($conn); ?> diff --git a/python_code/readMysql.py b/python_code/readMysql.py index e7a7484..23802ce 100644 --- a/python_code/readMysql.py +++ b/python_code/readMysql.py @@ -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 diff --git a/python_code/temp-humid-read-loop.py b/python_code/temp-humid-read-loop.py index 0faff1f..53faf35 100755 --- a/python_code/temp-humid-read-loop.py +++ b/python_code/temp-humid-read-loop.py @@ -1,141 +1,100 @@ -#/usr/bin/env python +#!/usr/bin/env python # -*- coding:utf-8 -*- -import sys +import time +import logging import dhtreader import updateMysql -import ConfigParser -import time -from time import strftime -from threading import Timer,Thread,Event -import logging -from datetime import datetime -from datetime import timedelta +import thmonitor_common as common -oldtemp = "NULL" -oldhumid = "NULL" +oldtemp = 'NULL' +oldhumid = 'NULL' -def exec_every_n_seconds(n,f,*args): - waitInterval = timedelta(seconds=n) - logging.debug('We should read the sensor every {0} seconds'.format(waitInterval)) - duration=f(*args) - offset = waitInterval - duration - logging.debug('Running the loop again in {0} seconds (printed as datetime)'.format(offset)) - offset2 = offset.total_seconds() - logging.debug('Running the loop again in {0} seconds (printed as float)'.format(offset2)) - while 1: - logging.debug('We are in the loop now ...') - initTime=time.time() - logging.debug('Start time is {0}'.format(initTime)) - #time.sleep(offset2) - logging.debug('We are about to run the sensor read again') - duration=f(*args) - offset2 = (60.0 - (time.time() - initTime)) - time.sleep(60.0 - ((time.time() - initTime) % 60.0)) - logging.debug('Duration of sequence was: {0}'.format(duration)) - offset = waitInterval - duration - logging.debug('Running the loop again in {0} seconds (printed as dateime)'.format(offset)) - #offset2 = offset.total_seconds() - logging.debug('Running the loop again in {0} seconds (printed as float)'.format(offset2)) -def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, tempdiff, maxhumid, minhumid, humiddiff): - global oldtemp - global oldhumid - startTime=datetime.now() - logging.debug('This round of results started at {0}'.format(startTime)) - for num in range(retries): +def sensor_read(cfg, dev_type, dhtpin): + """Read sensor, validate, and store a single measurement.""" + global oldtemp, oldhumid + + start = time.time() + limits = { + 'maxtemp': cfg['maxtemp'], + 'mintemp': cfg['mintemp'], + 'tempdiff': cfg['tempdiff'], + 'maxhumid': cfg['maxhumid'], + 'minhumid': cfg['minhumid'], + 'humiddiff': cfg['humiddiff'], + } + + for num in range(cfg['retries']): try: t, h = dhtreader.read(dev_type, dhtpin) - except: - if ((num + 1) < retries): - logging.warning('Exception detected! We will retry. Loop number: %d', num) - time.sleep(timeout) + except Exception: + if num + 1 < cfg['retries']: + logging.warning( + 'Exception during sensor read; retry %d/%d', + num + 1, cfg['retries'], + ) + time.sleep(cfg['timeout']) else: - logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.') - else: - if t and h: - logging.debug('Temperature and humidity read as {0} and {1}'.format(t, h)) - logging.debug('Temperature and Humidity differences allowed: {0} and {1}'.format(tempdiff, humiddiff)) - if (oldtemp != "NULL") and ((t - oldtemp < tempdiff) or (oldtemp - t < tempdiff)) and ((h - oldhumid < humiddiff) or (oldhumid - h < humiddiff)): - logging.debug('Current temperature close enough to previous temperature and previous temperature is not NULL, it is: %s', oldtemp) - logging.debug('Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s', oldhumid) - if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid): - logging.debug('Temperature is less than {0} and greater than {1}, humidity is less than {2} and greater than {3}'.format(maxtemp,mintemp,maxhumid,minhumid)) - updateMysql.main(t, h, host, db, username, password, logging, sql_retries, sql_timeout) - oldtemp=t - oldhumid=h - break - else: - logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h)) - else: - logging.warning('Failed to read from sensor, maybe try again?') - endTime=datetime.now() - logging.debug('This round of results ended at {0}'.format(endTime)) - duration = endTime - startTime - logging.debug('This round of results took {0} to complete'.format(duration)) + logging.error( + 'Sensor read failed after %d attempts; skipping this cycle.', + cfg['retries'], + ) + continue + + if not t or not h: + logging.warning('Sensor returned empty reading; retrying.') + if num + 1 < cfg['retries']: + time.sleep(cfg['timeout']) + continue + + logging.debug('Temperature and humidity read as %s and %s', t, h) + if common.reading_is_plausible(t, h, oldtemp, oldhumid, limits): + updateMysql.main( + t, h, + cfg['host'], cfg['db'], cfg['username'], cfg['password'], + logging, cfg['sql_retries'], cfg['sql_timeout'], + ) + oldtemp = t + oldhumid = h + break + + if num + 1 < cfg['retries']: + time.sleep(cfg['timeout']) + + duration = time.time() - start + logging.debug('Sensor read cycle took %.2f seconds', duration) return duration -DHT11 = 11 -DHT22 = 22 -AM2302 = 22 -config = ConfigParser.ConfigParser() -config.read('/etc/thMonitor.conf') -hwtype=config.get('hardware', 'DHT') -pin=config.get('hardware', 'PIN') -retries=int(config.get('software', 'retries')) -timeout=int(config.get('software', 'timeout')) -interval=int(config.get('software', 'interval')) -maxtemp=int(config.get('software', 'maxtemp')) -mintemp=int(config.get('software', 'mintemp')) -tempdiff=int(config.get('software', 'tempdiff')) -maxhumid=int(config.get('software', 'maxhumid')) -minhumid=int(config.get('software', 'minhumid')) -humiddiff=int(config.get('software', 'humiddiff')) -logfile=(config.get('software', 'logfile')) -loglevel=(config.get('software', 'loglevel')) -host=(config.get('database', 'host')) -db=(config.get('database', 'db')) -username=(config.get('database', 'username')) -password=(config.get('database', 'password')) -sql_retries=int((config.get('database', 'sql_retries'))) -sql_timeout=(config.get('database', 'sql_timeout')) +def run_loop(cfg, dev_type, dhtpin): + """Run sensor reads on a fixed interval, accounting for read duration.""" + interval = cfg['interval'] + logging.debug('Reading sensor every %d seconds', interval) + + while True: + start = time.time() + sensor_read(cfg, dev_type, dhtpin) + elapsed = time.time() - start + sleep_for = max(0, interval - elapsed) + logging.debug('Sleeping %.2f seconds until next reading', sleep_for) + time.sleep(sleep_for) -if loglevel == "debug": - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG) -elif loglevel == "info": - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) -elif loglevel == "warn": - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.WARNING) -elif loglevel == "error": - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.ERROR) -else: - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.CRITICAL) +def main(): + cfg = common.load_config() + common.setup_logging(cfg['logfile'], cfg['loglevel']) -dhtreader.init() + dhtreader.init() + dev_type = common.resolve_dht_type(cfg['hwtype']) + dhtpin = common.validate_pin(cfg['pin']) -dev_type = None -if hwtype == "11": - dev_type = DHT11 - logging.info('Configured to use DHT11 device') -elif hwtype == "22": - dev_type = DHT22 - logging.info('Configured to use DHT22 device') -elif hwtype == "2302": - dev_type = AM2302 - logging.info('Configured to use AM2303 device') -else: - logging.warn('Invalid hardware type, only DHT11, DHT22 and AM 2302 are supported for now.!') - sys.exit(3) + logging.info( + 'Multiple (infinite loop) temperature and humidity reading ' + '[version: 1.1, Jonathan Ervine, 2015-06-17]' + ) + run_loop(cfg, dev_type, dhtpin) -dhtpin = int(pin) -if dhtpin <= 0: - logging.warn("Invalid GPIO pin#, correct your configuration file") - sys.exit(3) -logging.info("using pin #{0}".format(dhtpin)) -logging.info('Multiple (infinte looped) run temperature and humidity reading. [version: 1.0, Jonathan Ervine, 2015-06-17]') - -logging.debug("About to enter infinite loop") -exec_every_n_seconds(60,sensorRead,hwtype,pin,retries,timeout,maxtemp,mintemp,tempdiff,maxhumid,minhumid,humiddiff) +if __name__ == '__main__': + main() diff --git a/python_code/temp-humid-read-single.py b/python_code/temp-humid-read-single.py index 71d549e..133ae94 100644 --- a/python_code/temp-humid-read-single.py +++ b/python_code/temp-humid-read-single.py @@ -1,111 +1,86 @@ #!/usr/bin/env python # -*- coding:utf-8 -*- -import sys +import logging +import time import dhtreader import updateMysql import readMysql -import ConfigParser -import logging -import time -from time import strftime -from datetime import datetime -from datetime import timedelta +import thmonitor_common as common -oldtemp = "NULL" -oldhumid = "NULL" -def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, tempdiff, maxhumid, minhumid, humiddiff): - global oldtemp - global oldhumid - oldtemp, oldhumid = readMysql.main(host, db, username, password, logging, sql_retries, sql_timeout) - logging.debug('We have returned the following previous temperature {0} and humidity {1} values.'.format(oldtemp, oldhumid)) - for num in range(retries): +def sensor_read(cfg, dev_type, dhtpin): + """Perform a single sensor read using the last DB values for validation.""" + oldtemp, oldhumid = readMysql.main( + cfg['host'], cfg['db'], cfg['username'], cfg['password'], + logging, cfg['sql_retries'], cfg['sql_timeout'], + ) + logging.debug( + 'Previous temperature %s and humidity %s loaded from database.', + oldtemp, oldhumid, + ) + + limits = { + 'maxtemp': cfg['maxtemp'], + 'mintemp': cfg['mintemp'], + 'tempdiff': cfg['tempdiff'], + 'maxhumid': cfg['maxhumid'], + 'minhumid': cfg['minhumid'], + 'humiddiff': cfg['humiddiff'], + } + + for num in range(cfg['retries']): try: t, h = dhtreader.read(dev_type, dhtpin) - except: - if ((num + 1) < retries): - logging.warning('Exception detected! We will retry. Loop number: %d', num) - time.sleep(timeout) + except Exception: + if num + 1 < cfg['retries']: + logging.warning( + 'Exception during sensor read; retry %d/%d', + num + 1, cfg['retries'], + ) + time.sleep(cfg['timeout']) else: - logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.') - else: - if t and h: - logging.debug('The temperature and humidity have been read as {0} and {1}'.format(t, h)) - if (oldtemp != "NULL") and ((t - oldtemp < tempdiff) or (oldtemp - t < tempdiff)) and ((h - oldhumid < humiddiff) or (oldhumid - h < humiddiff)): - logging.debug('Current temperature close enough to previous temperature and previous temperature is not NULL, it is: %s', oldtemp) - logging.debug('Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s', oldhumid) - if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid): - logging.debug('Temperature is less than {0} and greater than {1}, humidity is less than {2} and greater than {3}'.format(maxtemp,mintemp,maxhumid,minhumid)) - updateMysql.main(t, h, host, db, username, password, logging, sql_retries, sql_timeout) - oldtemp=t - oldhumid=h - break - else: - logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h)) - else: - logging.warning('Failed to read from sensor, maybe try again?') - return 0 + logging.error( + 'Sensor read failed after %d attempts; giving up.', + cfg['retries'], + ) + continue -DHT11 = 11 -DHT22 = 22 -AM2302 = 22 + if not t or not h: + logging.warning('Sensor returned empty reading; retrying.') + if num + 1 < cfg['retries']: + time.sleep(cfg['timeout']) + continue -config = ConfigParser.ConfigParser() -config.read('/etc/thMonitor.conf') -hwtype=config.get('hardware', 'DHT') -pin=config.get('hardware', 'PIN') -retries=int(config.get('software', 'retries')) -timeout=int(config.get('software', 'timeout')) -interval=int(config.get('software', 'interval')) -maxtemp=int(config.get('software', 'maxtemp')) -mintemp=int(config.get('software', 'mintemp')) -tempdiff=int(config.get('software', 'tempdiff')) -maxhumid=int(config.get('software', 'maxhumid')) -minhumid=int(config.get('software', 'minhumid')) -humiddiff=int(config.get('software', 'humiddiff')) -logfile=(config.get('software', 'logfile')) -loglevel=(config.get('software', 'loglevel')) -host=(config.get('database', 'host')) -db=(config.get('database', 'db')) -username=(config.get('database', 'username')) -password=(config.get('database', 'password')) -sql_retries=int((config.get('database', 'sql_retries'))) -sql_timeout=(config.get('database', 'sql_timeout')) + logging.debug('Temperature and humidity read as %s and %s', t, h) + if common.reading_is_plausible(t, h, oldtemp, oldhumid, limits): + updateMysql.main( + t, h, + cfg['host'], cfg['db'], cfg['username'], cfg['password'], + logging, cfg['sql_retries'], cfg['sql_timeout'], + ) + return 0 + + if num + 1 < cfg['retries']: + time.sleep(cfg['timeout']) + + return 1 -if loglevel == "debug": - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG) -elif loglevel == "info": - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) -elif loglevel == "warn": - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.WARNING) -elif loglevel == "error": - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.ERROR) -else: - logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.CRITICAL) +def main(): + cfg = common.load_config() + common.setup_logging(cfg['logfile'], cfg['loglevel']) -dhtreader.init() + dhtreader.init() + dev_type = common.resolve_dht_type(cfg['hwtype']) + dhtpin = common.validate_pin(cfg['pin']) -dev_type = None -if hwtype == "11": - dev_type = DHT11 - logging.info('Configured to use DHT11 device') -elif hwtype == "22": - dev_type = DHT22 - logging.info('Configured to use DHT22 device') -elif hwtype == "2302": - dev_type = AM2302 - logging.info('Configured to use AM2303 device') -else: - logging.warn('Invalid hardware type, only DHT11, DHT22 and AM 2302 are supported for now.!') - sys.exit(3) + logging.info( + 'Single run temperature and humidity reading ' + '[version: 1.1, Jonathan Ervine, 2015-06-17]' + ) + return sensor_read(cfg, dev_type, dhtpin) -dhtpin = int(pin) -if dhtpin <= 0: - logging.warn("Invalid GPIO pin#, correct your configuration file") - sys.exit(3) -logging.info("using pin #{0}".format(dhtpin)) -logging.info('Single run temperature and humidity reading. [version: 1.0, Jonathan Ervine, 2015-06-17]') -sensorRead(hwtype,pin,retries,timeout,maxtemp,mintemp,tempdiff,maxhumid,minhumid,humiddiff) +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/python_code/thmonitor_common.py b/python_code/thmonitor_common.py new file mode 100644 index 0000000..a92bcca --- /dev/null +++ b/python_code/thmonitor_common.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Shared configuration, logging, and sensor validation for thMonitor scripts.""" + +from __future__ import print_function + +import sys +import logging +import ConfigParser + +DHT11 = 11 +DHT22 = 22 +AM2302 = 22 + +DEFAULT_CONFIG = '/etc/thMonitor.conf' + + +def load_config(path=DEFAULT_CONFIG): + """Load and return thMonitor configuration as a dict.""" + config = ConfigParser.ConfigParser() + if not config.read(path): + print('ERROR: configuration file not found: {0}'.format(path), file=sys.stderr) + sys.exit(1) + + return { + 'config_path': path, + 'hwtype': config.get('hardware', 'DHT'), + 'pin': config.get('hardware', 'PIN'), + 'retries': config.getint('software', 'retries'), + 'timeout': config.getint('software', 'timeout'), + 'interval': config.getint('software', 'interval'), + 'maxtemp': config.getint('software', 'maxtemp'), + 'mintemp': config.getint('software', 'mintemp'), + 'tempdiff': config.getint('software', 'tempdiff'), + 'maxhumid': config.getint('software', 'maxhumid'), + 'minhumid': config.getint('software', 'minhumid'), + 'humiddiff': config.getint('software', 'humiddiff'), + 'logfile': config.get('software', 'logfile'), + 'loglevel': config.get('software', 'loglevel'), + 'host': config.get('database', 'host'), + 'db': config.get('database', 'db'), + 'username': config.get('database', 'username'), + 'password': config.get('database', 'password'), + 'sql_retries': config.getint('database', 'sql_retries'), + 'sql_timeout': config.getint('database', 'sql_timeout'), + } + + +def setup_logging(logfile, loglevel): + """Configure logging from config file settings.""" + levels = { + 'debug': logging.DEBUG, + 'info': logging.INFO, + 'warn': logging.WARNING, + 'error': logging.ERROR, + 'critical': logging.CRITICAL, + } + level = levels.get(loglevel.lower(), logging.CRITICAL) + logging.basicConfig( + filename=logfile, + format='%(asctime)s %(levelname)s:%(message)s', + datefmt='%Y-%m-%d %H:%M:%S', + level=level, + ) + + +def resolve_dht_type(hwtype): + """Map config hardware type string to dhtreader device constant.""" + types = { + '11': (DHT11, 'DHT11'), + '22': (DHT22, 'DHT22'), + '2302': (AM2302, 'AM2302'), + } + if hwtype not in types: + logging.warn( + 'Invalid hardware type %r; supported values are 11, 22, and 2302', + hwtype, + ) + sys.exit(3) + dev_type, name = types[hwtype] + logging.info('Configured to use %s device', name) + return dev_type + + +def validate_pin(pin): + """Return GPIO pin number or exit if invalid.""" + dhtpin = int(pin) + if dhtpin <= 0: + logging.warn('Invalid GPIO pin number: %s', pin) + sys.exit(3) + logging.info('using pin #%d', dhtpin) + return dhtpin + + +def reading_is_plausible(t, h, oldtemp, oldhumid, limits): + """ + Return True if reading is within configured bounds and not an abrupt jump + from the previous values. + """ + if not (limits['mintemp'] < t < limits['maxtemp']): + logging.error( + 'Temperature %s outside allowable range (%d, %d)', + t, limits['mintemp'], limits['maxtemp'], + ) + return False + + if not (limits['minhumid'] < h < limits['maxhumid']): + logging.error( + 'Humidity %s outside allowable range (%d, %d)', + h, limits['minhumid'], limits['maxhumid'], + ) + return False + + if oldtemp != 'NULL' and abs(t - oldtemp) >= limits['tempdiff']: + logging.warning( + 'Temperature jump too large: current=%s previous=%s (limit=%d)', + t, oldtemp, limits['tempdiff'], + ) + return False + + if oldhumid != 'NULL' and abs(h - oldhumid) >= limits['humiddiff']: + logging.warning( + 'Humidity jump too large: current=%s previous=%s (limit=%d)', + h, oldhumid, limits['humiddiff'], + ) + return False + + return True diff --git a/python_code/updateMysql.py b/python_code/updateMysql.py index f7d2be8..21c5f4e 100644 --- a/python_code/updateMysql.py +++ b/python_code/updateMysql.py @@ -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 diff --git a/temp-humid-chart.html b/temp-humid-chart.html index 1a6431b..7dacb3d 100644 --- a/temp-humid-chart.html +++ b/temp-humid-chart.html @@ -49,7 +49,6 @@ -