Files
Zabbix-DHT/readSensor
2018-11-27 17:32:15 +01:00

81 lines
2.0 KiB
Bash
Executable File

#!/bin/bash
#
# Copyright (c) 2018 leopold@shdx.org
# Author: Der_Leopold
#
# This script tries to read temperature and humidity from a DHT11 or DHT22 sensor
# and writes the results and a timestamp to a file. It is intended to be executed
# periodically, for example via crontab.
#
# Type of sensor; '11' for DHT11 or '22' for DHT22
SENSOR=22
# Change this to the number of the GPIO pin the sensor is connected to
GPIOPIN=4
# Retry up to n times if the reading fails
RETRY=3
# Number of seconds to wait between retries
DELAY=2
# Specify the temperature range where you expect the sensor will be operating
# This is simply used as a safeguard to detect implausible sensor readings
MINTEMP=-30
MAXTEMP=40
# CMD should point to the compiled Adafruit binary that does the acutal reading from the sensor
# See https://github.com/adafruit/Adafruit_Python_DHT for details
# The 'sudo' is not needed if the user executing the script is member of the group 'gpio'
CMD="sudo ./external/Adafruit_Python_DHT/examples/AdafruitDHT.py"
# Location where the readings should be stored
OUTFILE="output"
#
# no configuration/changes should be necessary below this line
#
cd "$(dirname "$0")";
touch "$OUTFILE" 2> /dev/null
if [ ! -w $OUTFILE ]; then
echo "Error: output file '$OUTFILE' not writeable"
exit 1
fi
CNT=0
function read_sensor () {
OUTPUT=`$CMD $SENSOR $GPIOPIN`
T=`echo "$OUTPUT" | awk -F[=*%] '{print $2}'`
H=`echo "$OUTPUT" | awk -F[=*%] '{print $4}'`
CNT=$(($CNT+1))
}
function check_output () {
if [[ $OUTPUT =~ Fail ]] || [[ ! $OUTPUT =~ Temp ]] || [[ ! $OUTPUT =~ Humidity ]] || [ ${T%.*} -lt $MINTEMP ] || [ ${T%.*} -gt $MAXTEMP ]; then
if [ $CNT -le $RETRY ]; then
sleep $DELAY
read_sensor
check_output
else
echo "Error" > "$OUTFILE"
exit 1
fi
fi
}
function write_results () {
echo "Timestamp="`date +%s` > "$OUTFILE"
echo "Temperature=${T}" >> "$OUTFILE"
echo "Humidity=${H}" >> "$OUTFILE"
}
read_sensor
check_output
write_results