57 Commits
Author SHA1 Message Date
jonnyandCursor 9493e58c29 Install liblgpio from source when apt packages are missing.
Bookworm does not ship python3-lgpio; the pip module needs liblgpio.so.1. Build Joan's lg library during install and look on system dist-packages at runtime.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 23:32:15 +08:00
jonnyandCursor 7da6ced1c4 Read the DHT sensor with lgpio instead of Adafruit bitbang.
Userspace pulse timing misses DHT22 edges on Raspberry Pi OS, which produced empty readings. Log the real failure reason and clarify that PIN is BCM GPIO numbering.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:58:30 +08:00
jonnyandCursor f061673880 Avoid Adafruit PulseIn hangs when claiming the DHT GPIO pin.
libgpiod_pulsein fails with "Unable to set line N to input" on Raspberry Pi OS, so read via bitbang and release the pin after a single-shot run.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:25:17 +08:00
jonnyandCursor 85f4107938 Default database table to TempHumid when missing from config.
Preserves compatibility with existing /etc/thMonitor.conf files created before the table option was added.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:09:04 +08:00
jonnyandCursor 2d1e319160 Make the MySQL table name configurable instead of hardcoding TempHumid.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 11:44:18 +08:00
jonnyandCursor 8010cd9045 Require --install and print help when install.sh is run with no arguments.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-14 23:18:34 +08:00
jonny 6c73f3e706 Add setup/install script 2026-08-14 23:08:28 +08:00
jonnyandCursor adb8573833 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>
2026-08-14 19:53:00 +08:00
jonnyandCursor 6f12d2c459 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>
2026-08-14 19:40:49 +08:00
Jonny Ervine c6616bd855 Merge branch 'master' of ssh://github.com/jervine/rpi-temp-humid-monitor 2015-07-21 10:22:41 +08:00
Jonny Ervine 82bc49ad72 new file: th.conf 2015-07-21 10:22:08 +08:00
Jonny Ervine e2d56bf2b4 Update README.md 2015-07-17 10:53:46 +08:00
Jonny Ervine e5253600f2 new file: readMysql.py 2015-07-10 19:35:28 +08:00
Jonny Ervine df055d4521 modified: temp-humid-read-single.py 2015-07-10 19:35:04 +08:00
Jonny Ervine c2857e4b77 modified: TODO 2015-07-09 19:41:47 +08:00
Jonny Ervine 1f5baacdcc modified: README.md 2015-06-24 10:53:33 +08:00
Jonny Ervine a4233dcea2 modified: README.md 2015-06-24 10:13:45 +08:00
Jonny Ervine 5fd2fc3b9b modified: temp-humid-read-loop.py
modified:   temp-humid-read-single.py
2015-06-24 10:12:48 +08:00
Jonny Ervine 6b4d6251eb modified: README.md
modified:   TODO
2015-06-23 07:10:32 +08:00
Jonny Ervine edf7161665 modified: python_code/temp-humid-read-loop.py
modified:   python_code/temp-humid-read-single.py
2015-06-23 07:08:25 +08:00
Jonny Ervine aeb3325817 modified: README.md 2015-06-19 15:17:17 +08:00
Jonny Ervine 3c4b73a171 modified: temp-humid-read-loop.py
modified:   temp-humid-read-single.py
	modified:   temphumid.conf
	modified:   updateMysql.py
2015-06-19 14:30:10 +08:00
Jonny Ervine 16bca797d2 Create thMonitord 2015-06-18 11:36:00 +08:00
Jonny Ervine 329171e0e7 Merge branch 'master' of ssh://github.com/jervine/rpi-temp-humid-monitor 2015-06-18 11:14:30 +08:00
Jonny Ervine c364505278 modified: TODO 2015-06-18 11:13:57 +08:00
Jonny Ervine db813d928d Update README.md 2015-06-18 10:34:08 +08:00
Jonny Ervine 2dec016b71 modified: README.md 2015-06-18 10:30:14 +08:00
Jonny Ervine 05431d1b63 modified: python_code/temp-humid-read-loop.py
new file:   python_code/temp-humid-read-single.py
	modified:   python_code/updateMysql.py
2015-06-18 10:20:47 +08:00
Jonny Ervine 3810ccb1b6 modified: python_code/temp-humid-read-loop.py 2015-06-18 09:30:01 +08:00
Jonny Ervine 56d37bd71e modified: TODO 2015-06-17 12:58:28 +08:00
Jonny Ervine bfec843124 Merge branch 'master' of ssh://github.com/jervine/rpi-temp-humid-monitor 2015-06-17 12:40:06 +08:00
Jonny Ervine 3bcbc18e44 renamed: Makefile -> c_code/Makefile
deleted:    dhtreader.so
	deleted:    temp-humid-read-loop.py
	deleted:    temphumid.conf
	deleted:    th.c
	deleted:    th.c-NOTES
	deleted:    thd
	deleted:    updateMysql.py
2015-06-17 12:39:30 +08:00
Jonny Ervine da5cba1220 Delete updateMysql.py 2015-06-17 12:37:04 +08:00
Jonny Ervine b6315e1c35 Delete thd 2015-06-17 12:36:51 +08:00
Jonny Ervine 2ea0012b7e Delete th.c-NOTES 2015-06-17 12:36:36 +08:00
Jonny Ervine 4e895ba80c Delete th.c 2015-06-17 12:36:23 +08:00
Jonny Ervine 4db054f131 Delete temphumid.conf 2015-06-17 12:36:10 +08:00
Jonny Ervine 0e045fc8b7 Delete temp-humid-read-loop.py 2015-06-17 12:35:47 +08:00
Jonny Ervine 02f78682db Delete dhtreader.so 2015-06-17 12:35:32 +08:00
Jonny Ervine a772eaeeb6 new file: c_code/th
new file:   c_code/th.c
	new file:   c_code/th.c-NOTES
	new file:   c_code/thd
	new file:   python_code/dhtreader.so
	new file:   python_code/temp-humid-read-loop.py
	new file:   python_code/temphumid.conf
	new file:   python_code/updateMysql.py
	deleted:    dhtreader.so
	deleted:    temp-humid-read-loop.py
	deleted:    temphumid.conf
	deleted:    th.c
	deleted:    th.c-NOTES
	deleted:    thd
	deleted:    updateMysql.py
2015-06-17 12:34:27 +08:00
Jonny Ervine 2a2b02ed6c Create TODO 2015-06-17 12:32:12 +08:00
Jonny Ervine 3aa44950de Update README.md 2015-06-17 12:29:39 +08:00
Jonny Ervine a5930acaf8 modified: README.md
modified:   th.c
2015-06-17 12:26:47 +08:00
Jonny Ervine d290c2a094 new file: dhtreader.so
new file:   temp-humid-read-loop.py
	new file:   temphumid.conf
	new file:   updateMysql.py
	modified:   th.c
2015-06-17 12:20:54 +08:00
Jonny Ervine 05f04bc740 modified: th.c 2015-06-11 12:34:26 +08:00
Jonny Ervine eff1a8321d modified: Makefile 2015-06-11 12:33:04 +08:00
Jonny Ervine 7bb0f38bc9 modified: th.c 2015-06-11 12:19:44 +08:00
Jonny Ervine 9a54608649 new file: Makefile
modified:   th.c
2015-06-11 12:18:18 +08:00
Jonny Ervine 09175a7e3d Create th.c-NOTES 2015-06-10 22:57:45 +08:00
Jonny Ervine 9bf9c49320 Update th.c 2015-06-10 22:54:51 +08:00
Jonny Ervine 83ebcbc029 Update thd 2015-06-10 22:52:47 +08:00
Jonny Ervine c350e87672 Create th.c
The username and password for the MySQL connection are hardcoded. This should be altered at some point.
2015-06-03 11:47:21 +08:00
Jonny Ervine bfddcd42e2 Create getData.php
The PHP file that will retrieve the data from the database. Currently hardcoded to the last 360 entries. This will be altered at some point.
2015-06-03 11:26:58 +08:00
Jonny Ervine ad14c93895 Create temp-humid-chart.html
Graph HTML file using Google Chart. Note that it calls getData.php to read the data from MySQL and return it to this HTML file in JSON format.
2015-06-03 11:25:14 +08:00
Jonny Ervine 9edd470dfc Create thd
My initial attempt at an init script for th - using the vsftpd init script heavily as a tempate for this.
2015-06-03 11:23:52 +08:00
Jonny Ervine 60dd0a823b Create README.md 2015-06-03 11:17:05 +08:00
Jonny Ervine a42838f6f5 Initial commit 2015-06-03 11:10:19 +08:00
16 changed files with 1385 additions and 427 deletions
+31 -127
View File
@@ -1,131 +1,35 @@
# ---> Python # Built application files
# Byte-compiled / optimized / DLL files *.apk
*.ap_
# Files for the Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
# Gradle files
.gradle/
build/
/*/build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Python
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
*$py.class *.pyo
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version .python-version
.venv/
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/ venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
+71 -1
View File
@@ -1,6 +1,76 @@
# 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 require Python 3 and use `adafruit-circuitpython-dht`
instead of the legacy Python 2 `dhtreader.so` extension.
### Recommended install (venv + systemd)
From a clone of this repository on the Raspberry Pi:
```bash
cd rpi-temp-humid-monitor
./install.sh # show help
sudo ./install.sh --install
```
This will:
- install required system packages (`python3-venv`, `default-libmysqlclient-dev`, etc.)
- create a virtual environment at `/usr/local/lib/thmonitor/venv`
- install Python dependencies into that venv (not system-wide)
- install app files to `/usr/local/lib/thmonitor`
- install `/etc/thMonitor.conf` if it does not already exist
- install command wrappers: `thmonitor-single`, `thmonitor-loop`
- enable and start the `thmonitor` systemd service (loop daemon)
Edit `/etc/thMonitor.conf` after install (GPIO pin, MySQL credentials, limits).
Useful commands:
```bash
sudo systemctl status thmonitor
sudo systemctl restart thmonitor
tail -f /var/log/th-python.log
thmonitor-single # one-off read (uses venv)
```
Cron-based single-shot mode instead of the loop daemon:
```bash
sudo ./install.sh --install --cron
```
Install without starting the service:
```bash
sudo ./install.sh --install --no-start
```
Uninstall:
```bash
sudo ./install.sh --uninstall
```
### Manual install (legacy)
If you prefer not to use the installer:
```bash
sudo apt install python3 python3-pip python3-dev python3-venv default-libmysqlclient-dev build-essential
python3 -m venv /usr/local/lib/thmonitor/venv
sudo /usr/local/lib/thmonitor/venv/bin/pip install -r python_code/requirements.txt
sudo cp python_code/temphumid.conf /etc/thMonitor.conf # edit credentials and GPIO pin
# copy python_code/*.py to your chosen install directory and point systemd/cron at the venv python
```
Do not copy or keep `dhtreader.so`; use `dhtreader.py` instead.
---
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 +111,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)
+1 -2
View File
@@ -1,4 +1,3 @@
## TO DO LIST ## 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. - Externalize getData.php database credentials into a config file outside the web root.
+26 -21
View File
@@ -4,42 +4,47 @@ $username = "USERNAME";
$password = "PASSWORD"; $password = "PASSWORD";
$dbname = "Monitoring"; $dbname = "Monitoring";
$rows = array();
$table = array(); $table = array();
$table['cols'] = array( $table['cols'] = array(
// Labels for your chart, these represent the column titles
array('label' => 'Date and Time', 'type' => 'number'), array('label' => 'Date and Time', 'type' => 'number'),
array('label' => 'Temperature', 'type' => 'number'), array('label' => 'Temperature', 'type' => 'number'),
array('label' => 'Humidity', 'type' => 'number') array('label' => 'Humidity', 'type' => 'number')
); );
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
$conn = mysqli_connect($servername, $username, $password, $dbname); $conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection if (!$conn) {
if ($conn->connect_error) { header('HTTP/1.1 500 Internal Server Error');
die("Connection failed: " . $conn->connect_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"; $sql = "SELECT ComputerTime, Temperature, Humidity FROM ("
$result = mysqli_query($conn,$sql); . "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) { $rows = array();
// output data of each row if ($result) {
while($row = mysqli_fetch_array($result)) { while ($row = mysqli_fetch_array($result)) {
$temp = array(); $temp = array();
// $datetime = date('d/m/Y H:i', $row[0]); $temp[] = array('v' => (float)$row[0]);
// $temp[] = array('v' => $datetime); $temp[] = array('v' => (float)$row[1]);
$temp[] = array('v' => $row[0]); $temp[] = array('v' => (float)$row[2]);
$temp[] = array('v' => $row[1]);
$temp[] = array('v' => $row[2]);
$rows[] = array('c' => $temp); $rows[] = array('c' => $temp);
} }
//} else { mysqli_free_result($result);
// echo "No current temperature - ERROR?"; } 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; $table['rows'] = $rows;
header('Content-type: application/json'); header('Content-type: application/json');
echo json_encode($table); echo json_encode($table);
$conn->close(); mysqli_close($conn);
?> ?>
Executable
+473
View File
@@ -0,0 +1,473 @@
#!/bin/bash
#
# Install rpi-temp-humid-monitor as a system app with a Python venv.
#
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PYTHON_CODE="${REPO_ROOT}/python_code"
SERVICE_TEMPLATE="${REPO_ROOT}/systemd/thmonitor.service.in"
INSTALL_ROOT="${INSTALL_ROOT:-/usr/local/lib/thmonitor}"
CONFIG_FILE="${CONFIG_FILE:-/etc/thMonitor.conf}"
LOG_FILE="${LOG_FILE:-/var/log/th-python.log}"
BIN_SINGLE="${BIN_SINGLE:-/usr/local/bin/thmonitor-single}"
BIN_LOOP="${BIN_LOOP:-/usr/local/bin/thmonitor-loop}"
SYSTEMD_UNIT="${SYSTEMD_UNIT:-/etc/systemd/system/thmonitor.service}"
CRON_FILE="${CRON_FILE:-/etc/cron.d/thmonitor}"
LEGACY_DIR="/usr/local/bin/thMonitor"
RUN_MODE="systemd"
DO_START=1
DO_INSTALL=0
DO_UNINSTALL=0
APT_PACKAGES=(
python3
python3-venv
python3-dev
python3-pip
python3-setuptools
swig
unzip
wget
default-libmysqlclient-dev
build-essential
)
PYTHON_MODULES=(
dhtreader.py
readMysql.py
temp-humid-read-loop.py
temp-humid-read-single.py
thmonitor_common.py
updateMysql.py
)
usage() {
local cmd
cmd="$(basename "$0")"
cat <<EOF
Install rpi-temp-humid-monitor as a system app with a Python venv.
Usage:
sudo ./$cmd --install [options]
sudo ./$cmd --uninstall
./$cmd --help
Actions:
--install Install the monitor (venv, app files, wrappers, systemd by default)
--uninstall Remove installed app files, wrappers, and services
-h, --help Show this help
Install options:
--cron Use a cron job for single-shot reads instead of the systemd loop
--no-start Install files and unit, but do not enable or start the service
Environment overrides:
INSTALL_ROOT Install directory (default: ${INSTALL_ROOT})
CONFIG_FILE Config file path (default: ${CONFIG_FILE})
LOG_FILE Log file path (default: ${LOG_FILE})
Examples:
sudo ./$cmd --install
sudo ./$cmd --install --cron
sudo ./$cmd --install --no-start
sudo ./$cmd --uninstall
EOF
}
log() {
printf '==> %s\n' "$*"
}
die() {
printf 'ERROR: %s\n' "$*" >&2
exit 1
}
need_root() {
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
die "Run this script as root (e.g. sudo $0)"
fi
}
parse_args() {
if [[ $# -eq 0 ]]; then
usage
exit 0
fi
while [[ $# -gt 0 ]]; do
case "$1" in
--install)
DO_INSTALL=1
shift
;;
--cron)
RUN_MODE="cron"
shift
;;
--no-start)
DO_START=0
shift
;;
--uninstall)
DO_UNINSTALL=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
die "Unknown option: $1 (try --help)"
;;
esac
done
if [[ "$DO_INSTALL" -eq 1 && "$DO_UNINSTALL" -eq 1 ]]; then
die "Choose either --install or --uninstall"
fi
if [[ "$DO_UNINSTALL" -eq 1 ]]; then
if [[ "$RUN_MODE" == "cron" || "$DO_START" -eq 0 ]]; then
die "--cron and --no-start apply only with --install"
fi
return
fi
if [[ "$DO_INSTALL" -ne 1 ]]; then
die "Specify --install or --uninstall (try --help)"
fi
}
install_apt_deps() {
local missing=()
local pkg
for pkg in "${APT_PACKAGES[@]}"; do
if ! dpkg -s "$pkg" >/dev/null 2>&1; then
missing+=("$pkg")
fi
done
if ((${#missing[@]} == 0)); then
log "System packages already installed"
return
fi
log "Installing system packages: ${missing[*]}"
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y "${missing[@]}"
}
install_optional_lgpio_packages() {
local pkg
local available=()
for pkg in python3-lgpio liblgpio1 liblgpio-dev; do
if apt-cache show "$pkg" >/dev/null 2>&1; then
available+=("$pkg")
fi
done
if ((${#available[@]} == 0)); then
log "No apt lgpio packages in this distro (normal on Bookworm)"
return
fi
log "Installing apt lgpio packages: ${available[*]}"
DEBIAN_FRONTEND=noninteractive apt-get install -y "${available[@]}"
}
liblgpio_present() {
ldconfig -p 2>/dev/null | grep -q 'liblgpio\.so\.1'
}
install_liblgpio_from_source() {
local builddir
if liblgpio_present; then
log "liblgpio.so.1 already present"
return
fi
log "Building liblgpio from source (https://github.com/joan2937/lg)"
builddir="$(mktemp -d)"
(
cd "$builddir"
wget -q -O lg.zip https://github.com/joan2937/lg/archive/master.zip
unzip -q lg.zip
cd lg-master
make
make install
)
rm -rf "$builddir"
ldconfig
if ! liblgpio_present; then
die "liblgpio.so.1 is still missing after building joan2937/lg"
fi
}
remove_legacy_install() {
if [[ -d "$LEGACY_DIR" ]]; then
log "Removing legacy install directory ${LEGACY_DIR}"
rm -rf "$LEGACY_DIR"
fi
if [[ -f /etc/init.d/thMonitor ]]; then
if command -v invoke-rc.d >/dev/null 2>&1; then
invoke-rc.d thMonitor stop >/dev/null 2>&1 || true
fi
if command -v update-rc.d >/dev/null 2>&1; then
update-rc.d thMonitor remove >/dev/null 2>&1 || true
fi
rm -f /etc/init.d/thMonitor
fi
find "$INSTALL_ROOT" "$LEGACY_DIR" -name 'dhtreader.so' -delete 2>/dev/null || true
}
install_app_files() {
local module
log "Installing application to ${INSTALL_ROOT}"
install -d -m 755 "$INSTALL_ROOT"
for module in "${PYTHON_MODULES[@]}"; do
install -m 644 "${PYTHON_CODE}/${module}" "${INSTALL_ROOT}/${module}"
done
install -m 644 "${PYTHON_CODE}/requirements.txt" "${INSTALL_ROOT}/requirements.txt"
rm -f "${INSTALL_ROOT}/dhtreader.so"
}
create_venv() {
local venv_python="${INSTALL_ROOT}/venv/bin/python"
local venv_pip="${INSTALL_ROOT}/venv/bin/pip"
local pyvenv_cfg="${INSTALL_ROOT}/venv/pyvenv.cfg"
log "Creating Python virtual environment"
if [[ ! -x "$venv_python" ]]; then
python3 -m venv "${INSTALL_ROOT}/venv"
fi
# apt python3-lgpio lives in system dist-packages; the venv must see it
# if pip cannot build Joan's lgpio module.
if [[ -f "$pyvenv_cfg" ]]; then
sed -i 's/^include-system-site-packages = .*/include-system-site-packages = true/' "$pyvenv_cfg"
fi
# Also expose apt dist-packages via a .pth so lgpio imports even if the
# venv was originally created without system site packages.
local pyver
pyver="$("$venv_python" -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
local site_packages="${INSTALL_ROOT}/venv/lib/python${pyver}/site-packages"
if [[ -d "$site_packages" ]]; then
printf '%s\n' '/usr/lib/python3/dist-packages' >"${site_packages}/system-dist-packages.pth"
fi
log "Installing Python dependencies into venv"
"$venv_pip" install --upgrade pip
"$venv_pip" install -r "${PYTHON_CODE}/requirements.txt"
if ! "$venv_python" -c 'import lgpio' >/dev/null 2>&1; then
log "lgpio not importable yet; retrying pip install"
"$venv_pip" install lgpio || true
fi
if "$venv_python" -c 'import lgpio' >/dev/null 2>&1; then
log "lgpio is available"
else
log "WARNING: lgpio is not importable; DHT reads will fall back to Adafruit bitbang"
fi
}
install_config() {
install -d -m 755 "$(dirname "$LOG_FILE")"
touch "$LOG_FILE"
chmod 644 "$LOG_FILE"
if [[ -f "$CONFIG_FILE" ]]; then
log "Keeping existing config ${CONFIG_FILE}"
return
fi
log "Installing sample config ${CONFIG_FILE}"
install -m 640 "${PYTHON_CODE}/temphumid.conf" "$CONFIG_FILE"
}
install_bin_wrappers() {
local venv_python="${INSTALL_ROOT}/venv/bin/python"
log "Installing command wrappers"
cat >"$BIN_SINGLE" <<EOF
#!/bin/sh
exec "${venv_python}" "${INSTALL_ROOT}/temp-humid-read-single.py" "\$@"
EOF
cat >"$BIN_LOOP" <<EOF
#!/bin/sh
exec "${venv_python}" "${INSTALL_ROOT}/temp-humid-read-loop.py" "\$@"
EOF
chmod 755 "$BIN_SINGLE" "$BIN_LOOP"
}
install_systemd_service() {
local venv_python="${INSTALL_ROOT}/venv/bin/python"
if [[ ! -f "$SERVICE_TEMPLATE" ]]; then
die "Missing systemd template: ${SERVICE_TEMPLATE}"
fi
log "Installing systemd unit ${SYSTEMD_UNIT}"
sed \
-e "s|@INSTALL_ROOT@|${INSTALL_ROOT}|g" \
-e "s|@VENV_PYTHON@|${venv_python}|g" \
"$SERVICE_TEMPLATE" >"$SYSTEMD_UNIT"
chmod 644 "$SYSTEMD_UNIT"
if command -v systemctl >/dev/null 2>&1; then
systemctl daemon-reload
else
log "systemctl not found; systemd unit installed but not loaded"
fi
}
install_cron_job() {
log "Installing cron job ${CRON_FILE}"
cat >"$CRON_FILE" <<EOF
# rpi-temp-humid-monitor: run a single sensor read every minute
* * * * * root ${BIN_SINGLE} >/dev/null 2>&1
EOF
chmod 644 "$CRON_FILE"
}
disable_systemd_service() {
if command -v systemctl >/dev/null 2>&1 && [[ -f "$SYSTEMD_UNIT" ]]; then
systemctl disable --now thmonitor.service >/dev/null 2>&1 || true
fi
}
enable_systemd_service() {
if [[ "$DO_START" -ne 1 ]]; then
log "Skipping service start (--no-start)"
return
fi
if ! command -v systemctl >/dev/null 2>&1; then
log "systemctl not available; start the loop manually with ${BIN_LOOP}"
return
fi
log "Enabling and starting thmonitor.service"
systemctl enable thmonitor.service
systemctl restart thmonitor.service
systemctl --no-pager --full status thmonitor.service || true
}
remove_cron_job() {
rm -f "$CRON_FILE"
}
do_install() {
need_root
[[ -d "$PYTHON_CODE" ]] || die "Missing python_code directory: ${PYTHON_CODE}"
install_apt_deps
install_optional_lgpio_packages
install_liblgpio_from_source
remove_legacy_install
install_app_files
create_venv
install_config
install_bin_wrappers
case "$RUN_MODE" in
systemd)
remove_cron_job
install_systemd_service
enable_systemd_service
;;
cron)
disable_systemd_service
install_cron_job
;;
*)
die "Unknown run mode: ${RUN_MODE}"
;;
esac
cat <<EOF
Installation complete.
App directory : ${INSTALL_ROOT}
Virtual env : ${INSTALL_ROOT}/venv
Config file : ${CONFIG_FILE}
Log file : ${LOG_FILE}
Run once : ${BIN_SINGLE}
Run loop : ${BIN_LOOP}
Next steps:
1. Edit ${CONFIG_FILE} (GPIO pin, MySQL credentials, limits).
2. If the DHT data wire is on GPIO 4 (physical pin 7), disable 1-Wire
(raspi-config → Interface Options → 1-Wire) and reboot.
3. Ensure the configured table (default: bedRoomTempHumid) exists in your MySQL database.
EOF
if [[ "$RUN_MODE" == "systemd" ]]; then
cat <<EOF
4. Check service status: systemctl status thmonitor
5. Follow logs: tail -f ${LOG_FILE}
EOF
else
cat <<EOF
4. Cron runs ${BIN_SINGLE} every minute.
5. Follow logs: tail -f ${LOG_FILE}
EOF
fi
}
do_uninstall() {
need_root
log "Uninstalling thmonitor"
disable_systemd_service
remove_cron_job
rm -f "$SYSTEMD_UNIT" "$BIN_SINGLE" "$BIN_LOOP"
rm -rf "$INSTALL_ROOT"
remove_legacy_install
if command -v systemctl >/dev/null 2>&1; then
systemctl daemon-reload
fi
cat <<EOF
Uninstall complete.
Removed:
${INSTALL_ROOT}
${SYSTEMD_UNIT}
${BIN_SINGLE}
${BIN_LOOP}
${CRON_FILE}
Kept (not removed):
${CONFIG_FILE}
${LOG_FILE}
EOF
}
parse_args "$@"
if [[ "$DO_UNINSTALL" -eq 1 ]]; then
do_uninstall
elif [[ "$DO_INSTALL" -eq 1 ]]; then
do_install
else
usage
exit 0
fi
+363
View File
@@ -0,0 +1,363 @@
"""DHT sensor reader with the same API as the legacy dhtreader.so extension."""
import logging
import os
import time
DHT11 = 11
DHT22 = 22
_DHT_GOOD = 0
_DHT_BAD_CHECKSUM = 1
_DHT_BAD_DATA = 2
_DHT_TIMEOUT = 3
_STATUS_NAMES = {
_DHT_GOOD: 'good',
_DHT_BAD_CHECKSUM: 'bad checksum',
_DHT_BAD_DATA: 'bad data',
_DHT_TIMEOUT: 'timeout',
}
_chip = None
_sensors = {}
_adafruit_devices = {}
_backend = None
_one_wire_warned = False
def init():
"""Initialize the DHT reader backend."""
return None
def close():
"""Release cached DHT devices and their GPIO lines."""
global _chip, _backend, _one_wire_warned
for sensor in _sensors.values():
try:
sensor.cancel()
except Exception:
pass
_sensors.clear()
if _chip is not None:
try:
lgpio = _import_lgpio()
if lgpio is not None:
lgpio.gpiochip_close(_chip)
except Exception:
pass
_chip = None
for device in _adafruit_devices.values():
try:
device.exit()
except Exception:
pass
_adafruit_devices.clear()
_backend = None
_one_wire_warned = False
def read(dev_type, pin):
"""
Read temperature (C) and humidity (%).
Returns (temperature, humidity) on success, or (None, None) on failure.
"""
pin = int(pin)
_warn_if_one_wire_conflict(pin)
backend = _select_backend()
if backend == 'lgpio':
return _read_lgpio(dev_type, pin)
return _read_adafruit(dev_type, pin)
def _select_backend():
global _backend
if _backend:
return _backend
if _open_gpiochip() is not None:
_backend = 'lgpio'
logging.info('DHT backend: lgpio')
return _backend
_backend = 'adafruit'
logging.info('DHT backend: adafruit bitbang')
return _backend
def _warn_if_one_wire_conflict(pin):
global _one_wire_warned
if _one_wire_warned or pin != 4:
return
if os.path.isdir('/sys/bus/w1/devices'):
logging.error(
'1-Wire is enabled and PIN is 4 (physical pin 7). '
'The kernel owns GPIO 4, so the DHT sensor cannot be read. '
'Disable 1-Wire (raspi-config → Interface Options → 1-Wire) and reboot, '
'or move the data wire and set PIN to that BCM GPIO.'
)
_one_wire_warned = True
def _import_lgpio():
"""Import lgpio, including the Raspberry Pi OS system package if needed."""
try:
import lgpio
return lgpio
except ImportError:
pass
import glob
import sys
extra_paths = ['/usr/lib/python3/dist-packages']
extra_paths.extend(sorted(glob.glob('/usr/lib/python3.*/dist-packages')))
for path in extra_paths:
if os.path.isdir(path) and path not in sys.path:
sys.path.append(path)
try:
import lgpio
logging.info('Loaded lgpio from system dist-packages')
return lgpio
except ImportError as err:
logging.warning(
'lgpio is not installed (%s). On Bookworm install liblgpio from '
'https://github.com/joan2937/lg (wget the zip, make, sudo make install, '
'sudo ldconfig). Trixie can use: sudo apt install python3-lgpio liblgpio1',
err,
)
return None
def _open_gpiochip():
global _chip
if _chip is not None:
return _chip
lgpio = _import_lgpio()
if lgpio is None:
return None
last_err = None
preferred = None
fallback = None
for chip_id in range(8):
try:
handle = lgpio.gpiochip_open(chip_id)
except Exception as err:
last_err = err
continue
label = _chip_label(lgpio, handle)
logging.debug('Found gpiochip %s (%s)', chip_id, label)
text = label.lower()
if any(token in text for token in ('rp1', 'bcm', 'pinctrl', 'raspberry')):
if fallback is not None:
try:
lgpio.gpiochip_close(fallback)
except Exception:
pass
preferred = handle
break
if fallback is None:
fallback = handle
else:
try:
lgpio.gpiochip_close(handle)
except Exception:
pass
_chip = preferred or fallback
if _chip is None:
logging.debug('Unable to open a gpiochip: %s', last_err)
return _chip
def _chip_label(lgpio, handle):
try:
info = lgpio.gpiochip_info(handle)
except Exception:
return ''
if isinstance(info, (tuple, list)):
parts = [str(part) for part in info[:3]]
return ' '.join(parts)
name = getattr(info, 'name', '') or ''
label = getattr(info, 'label', '') or ''
return f'{name} {label}'.strip()
def _read_lgpio(dev_type, pin):
try:
sensor = _get_lgpio_sensor(dev_type, pin)
_timestamp, _gpio, status, temperature, humidity = sensor.read()
except Exception as err:
logging.warning('lgpio DHT read failed: %s', err)
return None, None
if status != _DHT_GOOD:
logging.warning(
'DHT read failed (%s) on BCM GPIO %d',
_STATUS_NAMES.get(status, status), pin,
)
return None, None
return float(temperature), float(humidity)
def _get_lgpio_sensor(dev_type, pin):
key = (dev_type, pin)
if key not in _sensors:
_sensors[key] = _LgpioDHT(_chip, pin, dev_type)
return _sensors[key]
def _read_adafruit(dev_type, pin):
device = _get_adafruit_device(dev_type, pin)
try:
temperature = device.temperature
humidity = device.humidity
except RuntimeError as err:
logging.warning('DHT read failed: %s', err)
return None, None
if temperature is None or humidity is None:
logging.warning('DHT returned no temperature/humidity values')
return None, None
return float(temperature), float(humidity)
def _get_adafruit_device(dev_type, pin):
import adafruit_dht
import board
key = (dev_type, pin)
if key not in _adafruit_devices:
pin_name = f'D{pin}'
if not hasattr(board, pin_name):
raise ValueError(f'Unknown BCM GPIO name {pin_name}')
gpio = getattr(board, pin_name)
# PulseIn/libgpiod_pulsein hangs on Raspberry Pi OS after
# "Unable to set line N to input". Bitbang is the Adafruit fallback.
if dev_type == DHT11:
_adafruit_devices[key] = adafruit_dht.DHT11(gpio, use_pulseio=False)
else:
_adafruit_devices[key] = adafruit_dht.DHT22(gpio, use_pulseio=False)
return _adafruit_devices[key]
class _LgpioDHT:
"""
DHT11/DHT22 reader using lgpio edge callbacks.
Timing is based on Joan's public-domain DHT.py:
http://abyz.me.uk/lg/py_lgpio.html
"""
def __init__(self, chip, gpio, dev_type):
sbc = _import_lgpio()
if sbc is None:
raise ImportError('lgpio is not installed')
self._sbc = sbc
self._chip = chip
self._gpio = gpio
self._dhtxx = dev_type != DHT11
self._new_data = False
self._bits = 0
self._code = 0
self._last_edge_tick = 0
self._timestamp = time.time()
self._status = _DHT_TIMEOUT
self._temperature = 0.0
self._humidity = 0.0
sbc.gpio_set_watchdog_micros(chip, gpio, 1000)
self._cb = sbc.callback(chip, gpio, sbc.RISING_EDGE, self._rising_edge)
def _datum(self):
return (
self._timestamp, self._gpio, self._status,
self._temperature, self._humidity,
)
def _validate_dht11(self, b1, b2, b3, b4):
temperature = b2
humidity = b4
valid = b1 == 0 and b3 == 0 and temperature <= 60 and 9 <= humidity <= 90
return valid, temperature, humidity
def _validate_dhtxx(self, b1, b2, b3, b4):
divisor = -10.0 if b2 & 128 else 10.0
temperature = float(((b2 & 127) << 8) + b1) / divisor
humidity = float((b4 << 8) + b3) / 10.0
valid = humidity <= 110.0 and -50.0 <= temperature <= 135.0
return valid, temperature, humidity
def _decode(self):
checksum = self._code & 0xff
b1 = (self._code >> 8) & 0xff
b2 = (self._code >> 16) & 0xff
b3 = (self._code >> 24) & 0xff
b4 = (self._code >> 32) & 0xff
if ((b1 + b2 + b3 + b4) & 0xFF) != checksum:
self._status = _DHT_BAD_CHECKSUM
self._new_data = True
return
if self._dhtxx:
valid, temperature, humidity = self._validate_dhtxx(b1, b2, b3, b4)
else:
valid, temperature, humidity = self._validate_dht11(b1, b2, b3, b4)
if valid:
self._timestamp = time.time()
self._temperature = temperature
self._humidity = humidity
self._status = _DHT_GOOD
else:
self._status = _DHT_BAD_DATA
self._new_data = True
def _rising_edge(self, chip, gpio, level, tick):
if level != self._sbc.TIMEOUT:
edge_len = tick - self._last_edge_tick
self._last_edge_tick = tick
if edge_len > 2e8:
self._bits = 0
self._code = 0
else:
self._code <<= 1
if edge_len > 1e5:
self._code |= 1
self._bits += 1
elif self._bits >= 30:
self._decode()
def _trigger(self):
sbc = self._sbc
sbc.gpio_claim_output(self._chip, self._gpio, 0)
time.sleep(0.001 if self._dhtxx else 0.015)
self._bits = 0
self._code = 0
sbc.gpio_claim_alert(self._chip, self._gpio, sbc.RISING_EDGE)
def cancel(self):
if self._cb is not None:
self._cb.cancel()
self._cb = None
def read(self):
self._new_data = False
self._status = _DHT_TIMEOUT
self._trigger()
for _ in range(20):
time.sleep(0.05)
if self._new_data:
break
return self._datum()
+45 -25
View File
@@ -1,35 +1,55 @@
#!/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 sys import time
import MySQLdb import MySQLdb
def main(host, db, user, passwd, logging, sql_retries, sql_timeout): NO_PREVIOUS = ('NULL', 'NULL')
def main(host, db, table, user, passwd, logging, sql_retries, sql_timeout):
logging.debug('Reading MySQL database next ...') logging.debug('Reading MySQL database next ...')
connection = MySQLdb.connect(host,user,passwd,db)
cursor=connection.cursor() sql = (
sql = """SELECT Temperature, Humidity FROM TempHumid ORDER BY ComputerTime DESC LIMIT 1""" f'SELECT Temperature, Humidity FROM `{table}` '
success = False 'ORDER BY ComputerTime DESC LIMIT 1'
attempts = 0 )
while attempts < sql_retries and not success:
for attempt in range(sql_retries):
connection = None
try: try:
connection = MySQLdb.connect(host, user, passwd, db)
cursor = connection.cursor()
cursor.execute(sql) cursor.execute(sql)
data = cursor.fetchall() row = cursor.fetchone()
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()
cursor.close() cursor.close()
logging.debug('The previous temperature was: {0}C and the previous humidity was {1}%'.format(oldtemp, oldhumid))
success = True if row is None:
except MySQLdb.Error, e: logging.info('No previous readings found in database.')
logging.warn('The MySQL database could not be read and returned the following error %d: %s', (e.args[0], e.args[1])) return NO_PREVIOUS
attempts += 1
if attempts == sql_retries: oldtemp = float(row[0])
logging.error('All configured attempts to read the MySQL database have failed. We are going to skip this attempt.') oldhumid = float(row[1])
time.sleep(sql_interval) logging.debug(
'Previous temperature: %sC, previous humidity: %s%%',
oldtemp, oldhumid,
)
return oldtemp, oldhumid return oldtemp, oldhumid
except MySQLdb.Error as e:
logging.warning(
'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
+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" or platform_machine == "armv6l"
mysqlclient>=2.2.0
+83 -122
View File
@@ -1,141 +1,102 @@
#/usr/bin/env python #!/usr/bin/env python3
# -*- coding:utf-8 -*- # -*- coding: utf-8 -*-
import logging
import time
import sys
import dhtreader import dhtreader
import updateMysql import updateMysql
import ConfigParser import thmonitor_common as common
import time
from time import strftime
from threading import Timer,Thread,Event
import logging
from datetime import datetime
from datetime import timedelta
oldtemp = "NULL" oldtemp = 'NULL'
oldhumid = "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): def sensor_read(cfg, dev_type, dhtpin):
global oldtemp """Read sensor, validate, and store a single measurement."""
global oldhumid global oldtemp, oldhumid
startTime=datetime.now()
logging.debug('This round of results started at {0}'.format(startTime)) start = time.time()
for num in range(retries): 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: try:
t, h = dhtreader.read(dev_type, dhtpin) t, h = dhtreader.read(dev_type, dhtpin)
except: except Exception as err:
if ((num + 1) < retries): if num + 1 < cfg['retries']:
logging.warning('Exception detected! We will retry. Loop number: %d', num) logging.warning(
time.sleep(timeout) 'Exception during sensor read; retry %d/%d: %s',
num + 1, cfg['retries'], err,
)
time.sleep(cfg['timeout'])
else: else:
logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.') logging.error(
else: 'Sensor read failed after %d attempts; skipping this cycle.',
if t and h: cfg['retries'],
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)) continue
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) if t is None or h is None:
logging.debug('Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s', oldhumid) logging.warning('Sensor returned empty reading; retrying.')
if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid): if num + 1 < cfg['retries']:
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)) time.sleep(cfg['timeout'])
updateMysql.main(t, h, host, db, username, password, logging, sql_retries, sql_timeout) continue
oldtemp=t
oldhumid=h 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['table'],
cfg['username'], cfg['password'],
logging, cfg['sql_retries'], cfg['sql_timeout'],
)
oldtemp = t
oldhumid = h
break break
else:
logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h)) if num + 1 < cfg['retries']:
else: time.sleep(cfg['timeout'])
logging.warning('Failed to read from sensor, maybe try again?')
endTime=datetime.now() duration = time.time() - start
logging.debug('This round of results ended at {0}'.format(endTime)) logging.debug('Sensor read cycle took %.2f seconds', duration)
duration = endTime - startTime
logging.debug('This round of results took {0} to complete'.format(duration))
return duration return duration
DHT11 = 11
DHT22 = 22
AM2302 = 22
config = ConfigParser.ConfigParser() def run_loop(cfg, dev_type, dhtpin):
config.read('/etc/thMonitor.conf') """Run sensor reads on a fixed interval, accounting for read duration."""
hwtype=config.get('hardware', 'DHT') interval = cfg['interval']
pin=config.get('hardware', 'PIN') logging.debug('Reading sensor every %d seconds', interval)
retries=int(config.get('software', 'retries'))
timeout=int(config.get('software', 'timeout')) while True:
interval=int(config.get('software', 'interval')) start = time.time()
maxtemp=int(config.get('software', 'maxtemp')) sensor_read(cfg, dev_type, dhtpin)
mintemp=int(config.get('software', 'mintemp')) elapsed = time.time() - start
tempdiff=int(config.get('software', 'tempdiff')) sleep_for = max(0, interval - elapsed)
maxhumid=int(config.get('software', 'maxhumid')) logging.debug('Sleeping %.2f seconds until next reading', sleep_for)
minhumid=int(config.get('software', 'minhumid')) time.sleep(sleep_for)
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'))
if loglevel == "debug": def main():
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG) cfg = common.load_config()
elif loglevel == "info": common.setup_logging(cfg['logfile'], cfg['loglevel'])
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)
dhtreader.init() dhtreader.init()
dev_type = common.resolve_dht_type(cfg['hwtype'])
dhtpin = common.validate_pin(cfg['pin'])
dev_type = None logging.info(
if hwtype == "11": 'Multiple (infinite loop) temperature and humidity reading '
dev_type = DHT11 '[version: 2.0, Python 3]'
logging.info('Configured to use DHT11 device') )
elif hwtype == "22": run_loop(cfg, dev_type, dhtpin)
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)
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)) if __name__ == '__main__':
logging.info('Multiple (infinte looped) run temperature and humidity reading. [version: 1.0, Jonathan Ervine, 2015-06-17]') main()
logging.debug("About to enter infinite loop")
exec_every_n_seconds(60,sensorRead,hwtype,pin,retries,timeout,maxtemp,mintemp,tempdiff,maxhumid,minhumid,humiddiff)
+75 -94
View File
@@ -1,111 +1,92 @@
#!/usr/bin/env python #!/usr/bin/env python3
# -*- coding:utf-8 -*- # -*- coding: utf-8 -*-
import sys
import dhtreader
import updateMysql
import readMysql
import ConfigParser
import logging import logging
import time import time
from time import strftime
from datetime import datetime
from datetime import timedelta
oldtemp = "NULL" import dhtreader
oldhumid = "NULL" import readMysql
import updateMysql
import thmonitor_common as common
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, tempdiff, maxhumid, minhumid, humiddiff):
global oldtemp def sensor_read(cfg, dev_type, dhtpin):
global oldhumid """Perform a single sensor read using the last DB values for validation."""
oldtemp, oldhumid = readMysql.main(host, db, username, password, logging, sql_retries, sql_timeout) oldtemp, oldhumid = readMysql.main(
logging.debug('We have returned the following previous temperature {0} and humidity {1} values.'.format(oldtemp, oldhumid)) cfg['host'], cfg['db'], cfg['table'],
for num in range(retries): 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: try:
t, h = dhtreader.read(dev_type, dhtpin) t, h = dhtreader.read(dev_type, dhtpin)
except: except Exception as err:
if ((num + 1) < retries): if num + 1 < cfg['retries']:
logging.warning('Exception detected! We will retry. Loop number: %d', num) logging.warning(
time.sleep(timeout) 'Exception during sensor read; retry %d/%d: %s',
num + 1, cfg['retries'], err,
)
time.sleep(cfg['timeout'])
else: else:
logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.') logging.error(
else: 'Sensor read failed after %d attempts; giving up.',
if t and h: cfg['retries'],
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)): continue
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 is None or h is None:
if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid): logging.warning('Sensor returned empty reading; retrying.')
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)) if num + 1 < cfg['retries']:
updateMysql.main(t, h, host, db, username, password, logging, sql_retries, sql_timeout) time.sleep(cfg['timeout'])
oldtemp=t continue
oldhumid=h
break logging.debug('Temperature and humidity read as %s and %s', t, h)
else: if common.reading_is_plausible(t, h, oldtemp, oldhumid, limits):
logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h)) updateMysql.main(
else: t, h,
logging.warning('Failed to read from sensor, maybe try again?') cfg['host'], cfg['db'], cfg['table'],
cfg['username'], cfg['password'],
logging, cfg['sql_retries'], cfg['sql_timeout'],
)
return 0 return 0
DHT11 = 11 if num + 1 < cfg['retries']:
DHT22 = 22 time.sleep(cfg['timeout'])
AM2302 = 22
config = ConfigParser.ConfigParser() return 1
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'))
if loglevel == "debug": def main():
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG) cfg = common.load_config()
elif loglevel == "info": common.setup_logging(cfg['logfile'], cfg['loglevel'])
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)
dhtreader.init() dhtreader.init()
dev_type = common.resolve_dht_type(cfg['hwtype'])
dhtpin = common.validate_pin(cfg['pin'])
dev_type = None logging.info(
if hwtype == "11": 'Single run temperature and humidity reading '
dev_type = DHT11 '[version: 2.0, Python 3]'
logging.info('Configured to use DHT11 device') )
elif hwtype == "22": try:
dev_type = DHT22 return sensor_read(cfg, dev_type, dhtpin)
logging.info('Configured to use DHT22 device') finally:
elif hwtype == "2302": dhtreader.close()
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)
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)) if __name__ == '__main__':
logging.info('Single run temperature and humidity reading. [version: 1.0, Jonathan Ervine, 2015-06-17]') raise SystemExit(main())
sensorRead(hwtype,pin,retries,timeout,maxtemp,mintemp,tempdiff,maxhumid,minhumid,humiddiff)
+6 -1
View File
@@ -3,7 +3,9 @@
# The hardware type - valid values are: 11 (DHT11 sensor), 22 (DHT22 sensor), and 2302 (AM2302 sensor) # The hardware type - valid values are: 11 (DHT11 sensor), 22 (DHT22 sensor), and 2302 (AM2302 sensor)
DHT=22 DHT=22
# The pin number used on the Raspberry Pi board # BCM GPIO number for the DHT data wire (not the physical header pin number).
# GPIO 4 is physical pin 7, the same pin as the original C code (wiringPi pin 7).
# GPIO 4 is also the Pi's default 1-Wire pin; disable 1-Wire or use another GPIO if it conflicts.
PIN=4 PIN=4
[software] [software]
@@ -48,6 +50,9 @@ host=localhost
# The name of the database # The name of the database
db=Monitoring db=Monitoring
# The table used for temperature/humidity readings (INSERT and SELECT)
table=bedRoomTempHumid
# The username to us to connect to MySQL (should have INSERT rights on the database) # The username to us to connect to MySQL (should have INSERT rights on the database)
username=USRENAME username=USRENAME
+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 $?
;; ;;
*) *)
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Shared configuration, logging, and sensor validation for thMonitor scripts."""
import re
import sys
import logging
import configparser
DHT11 = 11
DHT22 = 22
AM2302 = 22
DEFAULT_CONFIG = '/etc/thMonitor.conf'
_TABLE_NAME_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
def validate_table_name(name):
"""Return table name if it is a safe SQL identifier, else exit."""
if not _TABLE_NAME_RE.match(name):
print(
f'ERROR: invalid database table name {name!r} '
'(use letters, digits, and underscores only)',
file=sys.stderr,
)
sys.exit(1)
return name
def load_config(path=DEFAULT_CONFIG):
"""Load and return thMonitor configuration as a dict."""
config = configparser.ConfigParser()
if not config.read(path):
print(f'ERROR: configuration file not found: {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'),
'table': validate_table_name(
config.get('database', 'table', fallback='TempHumid'),
),
'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.warning(
'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.warning('Invalid GPIO pin number: %s', pin)
sys.exit(3)
logging.info('using BCM GPIO 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
+37 -22
View File
@@ -1,34 +1,49 @@
#!/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 sys import time
import MySQLdb 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 def main(temp, humid, host, db, table, user, passwd, logging, sql_retries, sql_timeout):
attempts = 0 logging.debug('Temp = %s *C, Hum = %s %%', temp, humid)
while attempts < sql_retries and not success: logging.debug('Updating MySQL database next ...')
sql = (
f'INSERT INTO `{table}` (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 MySQL table %s',
args[0], args[1], table,
)
for attempt in range(sql_retries):
connection = None
try: try:
connection = MySQLdb.connect(host, user, passwd, db)
cursor = connection.cursor()
cursor.execute(sql, args) cursor.execute(sql, args)
connection.commit() connection.commit()
cursor.close() cursor.close()
success = True
logging.debug('The MySQL database was successfully updated.') 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.warning(
'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
+15
View File
@@ -0,0 +1,15 @@
[Unit]
Description=Raspberry Pi Temperature and Humidity Monitor
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=root
WorkingDirectory=@INSTALL_ROOT@
ExecStart=@VENV_PYTHON@ @INSTALL_ROOT@/temp-humid-read-loop.py
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
-1
View File
@@ -49,7 +49,6 @@
</script> </script>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript"> <script type="text/javascript">
$(document).ready(function(){ $(document).ready(function(){
// First load the chart once // First load the chart once