Migrate monitoring scripts from Python 2 to Python 3.

Replace the dhtreader.so extension with adafruit-circuitpython-dht and run the daemon with python3.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-14 19:53:00 +08:00
co-authored by Cursor
parent 6f12d2c459
commit adb8573833
12 changed files with 113 additions and 28 deletions
+8
View File
@@ -25,3 +25,11 @@ proguard/
# Log Files # Log Files
*.log *.log
# Python
__pycache__/
*.py[cod]
*.pyo
.python-version
.venv/
venv/
+30 -1
View File
@@ -1,6 +1,35 @@
# rpi-temp-humid-monitor # rpi-temp-humid-monitor
Raspberry Pi temperature humidity monitor Raspberry Pi temperature humidity monitor
## Python 3 setup
The Python monitoring scripts now require Python 3 and use `adafruit-circuitpython-dht`
instead of the legacy Python 2 `dhtreader.so` extension.
On the Raspberry Pi:
```bash
sudo apt install python3 python3-pip python3-dev default-libmysqlclient-dev build-essential
cd python_code
sudo pip3 install -r requirements.txt
sudo cp temphumid.conf /etc/thMonitor.conf # edit credentials and GPIO pin
sudo cp temp-humid-read-loop.py temp-humid-read-single.py updateMysql.py readMysql.py thmonitor_common.py dhtreader.py /usr/local/bin/thMonitor/
sudo rm -f /usr/local/bin/thMonitor/dhtreader.so # remove legacy Python 2 extension if present
sudo cp thMonitord /etc/init.d/thMonitor
sudo update-rc.d thMonitor defaults
```
The loop daemon runs with `/usr/bin/python3 /usr/local/bin/thMonitor/temp-humid-read-loop.py`.
The single-run script is suitable for cron:
```cron
* * * * * /usr/bin/python3 /usr/local/bin/thMonitor/temp-humid-read-single.py
```
The legacy `dhtreader.so` binary is no longer used and can be removed after upgrading.
---
This is my implementation of making a Raspberry Pi powered temperature and humidity monitor. The original instructions that I followed were created by wpnsmith at [the instructables website](http://www.instructables.com/id/Raspberry-Pi-Temperature-Humidity-Network-Monitor/) This is my implementation of making a Raspberry Pi powered temperature and humidity monitor. The original instructions that I followed were created by wpnsmith at [the instructables website](http://www.instructables.com/id/Raspberry-Pi-Temperature-Humidity-Network-Monitor/)
In this repository are my copies of the th.c code, a thd init script, and two files for creating a Google Chart graph rather than the python based GraphTH.py using matplotlib that wpnsmith used. In this repository are my copies of the th.c code, a thd init script, and two files for creating a Google Chart graph rather than the python based GraphTH.py using matplotlib that wpnsmith used.
@@ -41,7 +70,7 @@ Looking to replace the C code with a python script that takes a configuration fi
- temphumid.conf - sample configuration file to be used with the python script - temphumid.conf - sample configuration file to be used with the python script
- dhtreader.so - binary shared object file. This has been created from [http://www.airspayce.com/mikem/bcm2835/](http://www.airspayce.com/mikem/bcm2835/) - dhtreader.py - pure Python DHT reader wrapper using adafruit-circuitpython-dht (replaces dhtreader.so)
###Please note this updated python code was heavily inspired by the work done by Adafruit here:### ###Please note this updated python code was heavily inspired by the work done by Adafruit here:###
[https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_DHT_Driver_Python](https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_DHT_Driver_Python) [https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_DHT_Driver_Python](https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_DHT_Driver_Python)
-3
View File
@@ -1,6 +1,3 @@
## TO DO LIST ## TO DO LIST
- 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. - Externalize getData.php database credentials into a config file outside the web root.
+44
View File
@@ -0,0 +1,44 @@
"""DHT sensor reader with the same API as the legacy dhtreader.so extension."""
DHT11 = 11
DHT22 = 22
_devices = {}
def init():
"""Initialize the DHT reader backend (no-op for adafruit_dht)."""
return None
def _get_device(dev_type, pin):
import adafruit_dht
from adafruit_blinka.microcontroller.bcm283x.pin import Pin
key = (dev_type, pin)
if key not in _devices:
gpio = Pin(pin)
if dev_type == DHT11:
_devices[key] = adafruit_dht.DHT11(gpio)
else:
_devices[key] = adafruit_dht.DHT22(gpio)
return _devices[key]
def read(dev_type, pin):
"""
Read temperature (C) and humidity (%).
Returns (temperature, humidity) on success, or (None, None) on failure.
"""
device = _get_device(dev_type, pin)
try:
temperature = device.temperature
humidity = device.humidity
except RuntimeError:
return None, None
if temperature is None or humidity is None:
return None, None
return float(temperature), float(humidity)
Binary file not shown.
+3 -2
View File
@@ -1,8 +1,9 @@
#!/usr/bin/python #!/usr/bin/env python3
## ##
## Script to read the last temperature and humidity readings from a MySQL database ## Script to read the last temperature and humidity readings from a MySQL database
## ##
import time import time
import MySQLdb import MySQLdb
NO_PREVIOUS = ('NULL', 'NULL') NO_PREVIOUS = ('NULL', 'NULL')
@@ -37,7 +38,7 @@ def main(host, db, user, passwd, logging, sql_retries, sql_timeout):
) )
return oldtemp, oldhumid return oldtemp, oldhumid
except MySQLdb.Error as e: except MySQLdb.Error as e:
logging.warn( logging.warning(
'MySQL read failed (attempt %d/%d): %d: %s', 'MySQL read failed (attempt %d/%d): %d: %s',
attempt + 1, sql_retries, e.args[0], e.args[1], attempt + 1, sql_retries, e.args[0], e.args[1],
) )
+4
View File
@@ -0,0 +1,4 @@
adafruit-blinka>=8.0.0
adafruit-circuitpython-dht>=4.0.0
lgpio>=0.2.2.0; platform_machine == "aarch64" or platform_machine == "armv7l"
mysqlclient>=2.2.0
+4 -3
View File
@@ -1,8 +1,9 @@
#!/usr/bin/env python #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import time
import logging import logging
import time
import dhtreader import dhtreader
import updateMysql import updateMysql
import thmonitor_common as common import thmonitor_common as common
@@ -91,7 +92,7 @@ def main():
logging.info( logging.info(
'Multiple (infinite loop) temperature and humidity reading ' 'Multiple (infinite loop) temperature and humidity reading '
'[version: 1.1, Jonathan Ervine, 2015-06-17]' '[version: 2.0, Python 3]'
) )
run_loop(cfg, dev_type, dhtpin) run_loop(cfg, dev_type, dhtpin)
+4 -3
View File
@@ -1,11 +1,12 @@
#!/usr/bin/env python #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import logging import logging
import time import time
import dhtreader import dhtreader
import updateMysql
import readMysql import readMysql
import updateMysql
import thmonitor_common as common import thmonitor_common as common
@@ -77,7 +78,7 @@ def main():
logging.info( logging.info(
'Single run temperature and humidity reading ' 'Single run temperature and humidity reading '
'[version: 1.1, Jonathan Ervine, 2015-06-17]' '[version: 2.0, Python 3]'
) )
return sensor_read(cfg, dev_type, dhtpin) return sensor_read(cfg, dev_type, dhtpin)
+5 -4
View File
@@ -10,9 +10,10 @@
# Description: Temperature and Humidity Monitoring daemon # Description: Temperature and Humidity Monitoring daemon
### END INIT INFO ### END INIT INFO
# Change the next 3 lines to suit where you install your script and what you want to call it # Change the next lines to suit where you install your script and what you want to call it
DIR=/usr/local/bin/thMonitor DIR=/usr/local/bin/thMonitor
DAEMON=$DIR/temp-humid-python-loop.py PYTHON=/usr/bin/python3
SCRIPT=$DIR/temp-humid-read-loop.py
DAEMON_NAME=thMonitor DAEMON_NAME=thMonitor
# Add any command line options for your daemon here # Add any command line options for your daemon here
@@ -29,7 +30,7 @@ PIDFILE=/var/run/$DAEMON_NAME.pid
do_start () { do_start () {
log_daemon_msg "Starting system $DAEMON_NAME daemon" log_daemon_msg "Starting system $DAEMON_NAME daemon"
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $PYTHON -- $SCRIPT $DAEMON_OPTS
log_end_msg $? log_end_msg $?
} }
do_stop () { do_stop () {
@@ -50,7 +51,7 @@ case "$1" in
;; ;;
status) status)
status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $? status_of_proc "$DAEMON_NAME" "$PYTHON" && exit 0 || exit $?
;; ;;
*) *)
+6 -8
View File
@@ -1,12 +1,10 @@
#!/usr/bin/env python #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""Shared configuration, logging, and sensor validation for thMonitor scripts.""" """Shared configuration, logging, and sensor validation for thMonitor scripts."""
from __future__ import print_function
import sys import sys
import logging import logging
import ConfigParser import configparser
DHT11 = 11 DHT11 = 11
DHT22 = 22 DHT22 = 22
@@ -17,9 +15,9 @@ DEFAULT_CONFIG = '/etc/thMonitor.conf'
def load_config(path=DEFAULT_CONFIG): def load_config(path=DEFAULT_CONFIG):
"""Load and return thMonitor configuration as a dict.""" """Load and return thMonitor configuration as a dict."""
config = ConfigParser.ConfigParser() config = configparser.ConfigParser()
if not config.read(path): if not config.read(path):
print('ERROR: configuration file not found: {0}'.format(path), file=sys.stderr) print(f'ERROR: configuration file not found: {path}', file=sys.stderr)
sys.exit(1) sys.exit(1)
return { return {
@@ -72,7 +70,7 @@ def resolve_dht_type(hwtype):
'2302': (AM2302, 'AM2302'), '2302': (AM2302, 'AM2302'),
} }
if hwtype not in types: if hwtype not in types:
logging.warn( logging.warning(
'Invalid hardware type %r; supported values are 11, 22, and 2302', 'Invalid hardware type %r; supported values are 11, 22, and 2302',
hwtype, hwtype,
) )
@@ -86,7 +84,7 @@ def validate_pin(pin):
"""Return GPIO pin number or exit if invalid.""" """Return GPIO pin number or exit if invalid."""
dhtpin = int(pin) dhtpin = int(pin)
if dhtpin <= 0: if dhtpin <= 0:
logging.warn('Invalid GPIO pin number: %s', pin) logging.warning('Invalid GPIO pin number: %s', pin)
sys.exit(3) sys.exit(3)
logging.info('using pin #%d', dhtpin) logging.info('using pin #%d', dhtpin)
return dhtpin return dhtpin
+3 -2
View File
@@ -1,8 +1,9 @@
#!/usr/bin/python #!/usr/bin/env python3
## ##
## Script to import the temperature and humidity into a MySQL database ## Script to import the temperature and humidity into a MySQL database
## ##
import time import time
import MySQLdb import MySQLdb
@@ -31,7 +32,7 @@ def main(temp, humid, host, db, user, passwd, logging, sql_retries, sql_timeout)
logging.debug('The MySQL database was successfully updated.') logging.debug('The MySQL database was successfully updated.')
return 0 return 0
except MySQLdb.Error as e: except MySQLdb.Error as e:
logging.warn( logging.warning(
'MySQL update failed (attempt %d/%d): %d: %s', 'MySQL update failed (attempt %d/%d): %d: %s',
attempt + 1, sql_retries, e.args[0], e.args[1], attempt + 1, sql_retries, e.args[0], e.args[1],
) )