Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54cca78018 | ||
|
|
58573d9086 |
+127
-31
@@ -1,35 +1,131 @@
|
|||||||
# Built application files
|
# ---> Python
|
||||||
*.apk
|
# Byte-compiled / optimized / DLL files
|
||||||
*.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]
|
||||||
*.pyo
|
*$py.class
|
||||||
|
|
||||||
|
# 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/
|
||||||
|
|
||||||
|
|||||||
@@ -1,76 +1,6 @@
|
|||||||
# 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.
|
||||||
@@ -111,7 +41,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.py - pure Python DHT reader wrapper using adafruit-circuitpython-dht (replaces dhtreader.so)
|
- dhtreader.so - binary shared object file. This has been created from [http://www.airspayce.com/mikem/bcm2835/](http://www.airspayce.com/mikem/bcm2835/)
|
||||||
|
|
||||||
###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,3 +1,4 @@
|
|||||||
## TO DO LIST
|
## TO DO LIST
|
||||||
|
|
||||||
- Externalize getData.php database credentials into a config file outside the web root.
|
- 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.
|
||||||
|
|
||||||
|
|||||||
+21
-26
@@ -4,47 +4,42 @@ $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);
|
||||||
if (!$conn) {
|
// Check connection
|
||||||
header('HTTP/1.1 500 Internal Server Error');
|
if ($conn->connect_error) {
|
||||||
header('Content-type: application/json');
|
die("Connection failed: " . $conn->connect_error);
|
||||||
echo json_encode(array('error' => 'Connection failed: ' . mysqli_connect_error()));
|
|
||||||
exit;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$sql = "SELECT ComputerTime, Temperature, Humidity FROM ("
|
$sql = "SELECT ComputerTime, Temperature, Humidity from TempHumid ORDER BY id DESC LIMIT 360";
|
||||||
. "SELECT ComputerTime, Temperature, Humidity FROM TempHumid "
|
$result = mysqli_query($conn,$sql);
|
||||||
. "ORDER BY id DESC LIMIT 360"
|
|
||||||
. ") AS recent ORDER BY ComputerTime ASC";
|
|
||||||
$result = mysqli_query($conn, $sql);
|
|
||||||
|
|
||||||
$rows = array();
|
//if ($result->num_rows > 0) {
|
||||||
if ($result) {
|
// output data of each row
|
||||||
while ($row = mysqli_fetch_array($result)) {
|
while($row = mysqli_fetch_array($result)) {
|
||||||
$temp = array();
|
$temp = array();
|
||||||
$temp[] = array('v' => (float)$row[0]);
|
// $datetime = date('d/m/Y H:i', $row[0]);
|
||||||
$temp[] = array('v' => (float)$row[1]);
|
// $temp[] = array('v' => $datetime);
|
||||||
$temp[] = array('v' => (float)$row[2]);
|
$temp[] = array('v' => $row[0]);
|
||||||
|
$temp[] = array('v' => $row[1]);
|
||||||
|
$temp[] = array('v' => $row[2]);
|
||||||
$rows[] = array('c' => $temp);
|
$rows[] = array('c' => $temp);
|
||||||
}
|
}
|
||||||
mysqli_free_result($result);
|
//} else {
|
||||||
} else {
|
// echo "No current temperature - ERROR?";
|
||||||
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);
|
||||||
mysqli_close($conn);
|
$conn->close();
|
||||||
?>
|
?>
|
||||||
|
|||||||
-473
@@ -1,473 +0,0 @@
|
|||||||
#!/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
|
|
||||||
@@ -1,363 +0,0 @@
|
|||||||
"""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()
|
|
||||||
+25
-45
@@ -1,55 +1,35 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/python
|
||||||
##
|
##
|
||||||
## 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 sys
|
||||||
|
|
||||||
import MySQLdb
|
import MySQLdb
|
||||||
|
|
||||||
NO_PREVIOUS = ('NULL', 'NULL')
|
def main(host, db, user, passwd, logging, sql_retries, sql_timeout):
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
sql = (
|
cursor=connection.cursor()
|
||||||
f'SELECT Temperature, Humidity FROM `{table}` '
|
sql = """SELECT Temperature, Humidity FROM TempHumid ORDER BY ComputerTime DESC LIMIT 1"""
|
||||||
'ORDER BY ComputerTime DESC LIMIT 1'
|
success = False
|
||||||
)
|
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)
|
||||||
row = cursor.fetchone()
|
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()
|
||||||
cursor.close()
|
cursor.close()
|
||||||
|
logging.debug('The previous temperature was: {0}C and the previous humidity was {1}%'.format(oldtemp, oldhumid))
|
||||||
if row is None:
|
success = True
|
||||||
logging.info('No previous readings found in database.')
|
except MySQLdb.Error, e:
|
||||||
return NO_PREVIOUS
|
logging.warn('The MySQL database could not be read and returned the following error %d: %s', (e.args[0], e.args[1]))
|
||||||
|
attempts += 1
|
||||||
oldtemp = float(row[0])
|
if attempts == sql_retries:
|
||||||
oldhumid = float(row[1])
|
logging.error('All configured attempts to read the MySQL database have failed. We are going to skip this attempt.')
|
||||||
logging.debug(
|
time.sleep(sql_interval)
|
||||||
'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
|
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -1,102 +1,141 @@
|
|||||||
#!/usr/bin/env python3
|
#/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding:utf-8 -*-
|
||||||
|
|
||||||
import logging
|
|
||||||
import time
|
|
||||||
|
|
||||||
|
import sys
|
||||||
import dhtreader
|
import dhtreader
|
||||||
import updateMysql
|
import updateMysql
|
||||||
import thmonitor_common as common
|
import ConfigParser
|
||||||
|
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 sensor_read(cfg, dev_type, dhtpin):
|
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, tempdiff, maxhumid, minhumid, humiddiff):
|
||||||
"""Read sensor, validate, and store a single measurement."""
|
global oldtemp
|
||||||
global oldtemp, oldhumid
|
global oldhumid
|
||||||
|
startTime=datetime.now()
|
||||||
start = time.time()
|
logging.debug('This round of results started at {0}'.format(startTime))
|
||||||
limits = {
|
for num in range(retries):
|
||||||
'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 Exception as err:
|
except:
|
||||||
if num + 1 < cfg['retries']:
|
if ((num + 1) < retries):
|
||||||
logging.warning(
|
logging.warning('Exception detected! We will retry. Loop number: %d', num)
|
||||||
'Exception during sensor read; retry %d/%d: %s',
|
time.sleep(timeout)
|
||||||
num + 1, cfg['retries'], err,
|
|
||||||
)
|
|
||||||
time.sleep(cfg['timeout'])
|
|
||||||
else:
|
else:
|
||||||
logging.error(
|
logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.')
|
||||||
'Sensor read failed after %d attempts; skipping this cycle.',
|
else:
|
||||||
cfg['retries'],
|
if t and h:
|
||||||
)
|
logging.debug('Temperature and humidity read as {0} and {1}'.format(t, h))
|
||||||
continue
|
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)):
|
||||||
if t is None or h is None:
|
logging.debug('Current temperature close enough to previous temperature and previous temperature is not NULL, it is: %s', oldtemp)
|
||||||
logging.warning('Sensor returned empty reading; retrying.')
|
logging.debug('Current humidity close enough to previous humidity and previous humidity is not NULL, it is: %s', oldhumid)
|
||||||
if num + 1 < cfg['retries']:
|
if (t < maxtemp) and (t > mintemp) and (h < maxhumid) and (h > minhumid):
|
||||||
time.sleep(cfg['timeout'])
|
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))
|
||||||
continue
|
updateMysql.main(t, h, host, db, username, password, logging, sql_retries, sql_timeout)
|
||||||
|
oldtemp=t
|
||||||
logging.debug('Temperature and humidity read as %s and %s', t, h)
|
oldhumid=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:
|
||||||
if num + 1 < cfg['retries']:
|
logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h))
|
||||||
time.sleep(cfg['timeout'])
|
else:
|
||||||
|
logging.warning('Failed to read from sensor, maybe try again?')
|
||||||
duration = time.time() - start
|
endTime=datetime.now()
|
||||||
logging.debug('Sensor read cycle took %.2f seconds', duration)
|
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))
|
||||||
return duration
|
return duration
|
||||||
|
|
||||||
|
DHT11 = 11
|
||||||
|
DHT22 = 22
|
||||||
|
AM2302 = 22
|
||||||
|
|
||||||
def run_loop(cfg, dev_type, dhtpin):
|
config = ConfigParser.ConfigParser()
|
||||||
"""Run sensor reads on a fixed interval, accounting for read duration."""
|
config.read('/etc/thMonitor.conf')
|
||||||
interval = cfg['interval']
|
hwtype=config.get('hardware', 'DHT')
|
||||||
logging.debug('Reading sensor every %d seconds', interval)
|
pin=config.get('hardware', 'PIN')
|
||||||
|
retries=int(config.get('software', 'retries'))
|
||||||
while True:
|
timeout=int(config.get('software', 'timeout'))
|
||||||
start = time.time()
|
interval=int(config.get('software', 'interval'))
|
||||||
sensor_read(cfg, dev_type, dhtpin)
|
maxtemp=int(config.get('software', 'maxtemp'))
|
||||||
elapsed = time.time() - start
|
mintemp=int(config.get('software', 'mintemp'))
|
||||||
sleep_for = max(0, interval - elapsed)
|
tempdiff=int(config.get('software', 'tempdiff'))
|
||||||
logging.debug('Sleeping %.2f seconds until next reading', sleep_for)
|
maxhumid=int(config.get('software', 'maxhumid'))
|
||||||
time.sleep(sleep_for)
|
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 main():
|
if loglevel == "debug":
|
||||||
cfg = common.load_config()
|
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
|
||||||
common.setup_logging(cfg['logfile'], cfg['loglevel'])
|
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)
|
||||||
|
|
||||||
dhtreader.init()
|
dhtreader.init()
|
||||||
dev_type = common.resolve_dht_type(cfg['hwtype'])
|
|
||||||
dhtpin = common.validate_pin(cfg['pin'])
|
|
||||||
|
|
||||||
logging.info(
|
dev_type = None
|
||||||
'Multiple (infinite loop) temperature and humidity reading '
|
if hwtype == "11":
|
||||||
'[version: 2.0, Python 3]'
|
dev_type = DHT11
|
||||||
)
|
logging.info('Configured to use DHT11 device')
|
||||||
run_loop(cfg, dev_type, dhtpin)
|
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)
|
||||||
|
|
||||||
|
dhtpin = int(pin)
|
||||||
|
if dhtpin <= 0:
|
||||||
|
logging.warn("Invalid GPIO pin#, correct your configuration file")
|
||||||
|
sys.exit(3)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
logging.info("using pin #{0}".format(dhtpin))
|
||||||
main()
|
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)
|
||||||
|
|||||||
@@ -1,92 +1,111 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python
|
||||||
# -*- 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
|
||||||
|
|
||||||
import dhtreader
|
oldtemp = "NULL"
|
||||||
import readMysql
|
oldhumid = "NULL"
|
||||||
import updateMysql
|
|
||||||
import thmonitor_common as common
|
|
||||||
|
|
||||||
|
def sensorRead(hwtype, pin, retries, timeout, maxtemp, mintemp, tempdiff, maxhumid, minhumid, humiddiff):
|
||||||
def sensor_read(cfg, dev_type, dhtpin):
|
global oldtemp
|
||||||
"""Perform a single sensor read using the last DB values for validation."""
|
global oldhumid
|
||||||
oldtemp, oldhumid = readMysql.main(
|
oldtemp, oldhumid = readMysql.main(host, db, username, password, logging, sql_retries, sql_timeout)
|
||||||
cfg['host'], cfg['db'], cfg['table'],
|
logging.debug('We have returned the following previous temperature {0} and humidity {1} values.'.format(oldtemp, oldhumid))
|
||||||
cfg['username'], cfg['password'],
|
for num in range(retries):
|
||||||
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 Exception as err:
|
except:
|
||||||
if num + 1 < cfg['retries']:
|
if ((num + 1) < retries):
|
||||||
logging.warning(
|
logging.warning('Exception detected! We will retry. Loop number: %d', num)
|
||||||
'Exception during sensor read; retry %d/%d: %s',
|
time.sleep(timeout)
|
||||||
num + 1, cfg['retries'], err,
|
|
||||||
)
|
|
||||||
time.sleep(cfg['timeout'])
|
|
||||||
else:
|
else:
|
||||||
logging.error(
|
logging.error('Exception detected - we are out of retries. Skipping the measurement in this cycle.')
|
||||||
'Sensor read failed after %d attempts; giving up.',
|
else:
|
||||||
cfg['retries'],
|
if t and h:
|
||||||
)
|
logging.debug('The temperature and humidity have been read as {0} and {1}'.format(t, h))
|
||||||
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)
|
break
|
||||||
if common.reading_is_plausible(t, h, oldtemp, oldhumid, limits):
|
else:
|
||||||
updateMysql.main(
|
logging.error('Temperature {0} or humidity {1} is outside of allowable values - error! Check your configuration.'.format(t, h))
|
||||||
t, h,
|
else:
|
||||||
cfg['host'], cfg['db'], cfg['table'],
|
logging.warning('Failed to read from sensor, maybe try again?')
|
||||||
cfg['username'], cfg['password'],
|
|
||||||
logging, cfg['sql_retries'], cfg['sql_timeout'],
|
|
||||||
)
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
if num + 1 < cfg['retries']:
|
DHT11 = 11
|
||||||
time.sleep(cfg['timeout'])
|
DHT22 = 22
|
||||||
|
AM2302 = 22
|
||||||
|
|
||||||
return 1
|
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 main():
|
if loglevel == "debug":
|
||||||
cfg = common.load_config()
|
logging.basicConfig(filename = logfile, format='%(asctime)s %(levelname)s:%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.DEBUG)
|
||||||
common.setup_logging(cfg['logfile'], cfg['loglevel'])
|
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)
|
||||||
|
|
||||||
dhtreader.init()
|
dhtreader.init()
|
||||||
dev_type = common.resolve_dht_type(cfg['hwtype'])
|
|
||||||
dhtpin = common.validate_pin(cfg['pin'])
|
|
||||||
|
|
||||||
logging.info(
|
dev_type = None
|
||||||
'Single run temperature and humidity reading '
|
if hwtype == "11":
|
||||||
'[version: 2.0, Python 3]'
|
dev_type = DHT11
|
||||||
)
|
logging.info('Configured to use DHT11 device')
|
||||||
try:
|
elif hwtype == "22":
|
||||||
return sensor_read(cfg, dev_type, dhtpin)
|
dev_type = DHT22
|
||||||
finally:
|
logging.info('Configured to use DHT22 device')
|
||||||
dhtreader.close()
|
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)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
logging.info("using pin #{0}".format(dhtpin))
|
||||||
raise SystemExit(main())
|
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)
|
||||||
|
|||||||
@@ -3,9 +3,7 @@
|
|||||||
# 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
|
||||||
|
|
||||||
# BCM GPIO number for the DHT data wire (not the physical header pin number).
|
# The pin number used on the Raspberry Pi board
|
||||||
# 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]
|
||||||
@@ -50,9 +48,6 @@ 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
|
||||||
|
|
||||||
|
|||||||
@@ -10,10 +10,9 @@
|
|||||||
# Description: Temperature and Humidity Monitoring daemon
|
# Description: Temperature and Humidity Monitoring daemon
|
||||||
### END INIT INFO
|
### END INIT INFO
|
||||||
|
|
||||||
# Change the next lines to suit where you install your script and what you want to call it
|
# Change the next 3 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
|
||||||
PYTHON=/usr/bin/python3
|
DAEMON=$DIR/temp-humid-python-loop.py
|
||||||
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
|
||||||
@@ -30,7 +29,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 $PYTHON -- $SCRIPT $DAEMON_OPTS
|
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS
|
||||||
log_end_msg $?
|
log_end_msg $?
|
||||||
}
|
}
|
||||||
do_stop () {
|
do_stop () {
|
||||||
@@ -51,7 +50,7 @@ case "$1" in
|
|||||||
;;
|
;;
|
||||||
|
|
||||||
status)
|
status)
|
||||||
status_of_proc "$DAEMON_NAME" "$PYTHON" && exit 0 || exit $?
|
status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
|
||||||
;;
|
;;
|
||||||
|
|
||||||
*)
|
*)
|
||||||
|
|||||||
@@ -1,143 +0,0 @@
|
|||||||
#!/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
|
|
||||||
+21
-36
@@ -1,49 +1,34 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/python
|
||||||
##
|
##
|
||||||
## 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 sys
|
||||||
|
|
||||||
import MySQLdb
|
import MySQLdb
|
||||||
|
|
||||||
|
def main(temp, humid, host, db, user, passwd, logging, sql_retries, sql_timeout):
|
||||||
def main(temp, humid, host, db, table, user, passwd, logging, sql_retries, sql_timeout):
|
logging.debug('Temp = {0} *C, Hum = {1} %'.format(temp, humid))
|
||||||
logging.debug('Temp = %s *C, Hum = %s %%', temp, humid)
|
|
||||||
logging.debug('Updating MySQL database next ...')
|
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)
|
||||||
|
|
||||||
sql = (
|
success = False
|
||||||
f'INSERT INTO `{table}` (ComputerTime, Temperature, Humidity, id) '
|
attempts = 0
|
||||||
'VALUES (unix_timestamp(now()), %s, %s, NULL)'
|
while attempts < sql_retries and not success:
|
||||||
)
|
|
||||||
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
|
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
[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
|
|
||||||
@@ -49,6 +49,7 @@
|
|||||||
|
|
||||||
</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
|
||||||
|
|||||||
Reference in New Issue
Block a user