diff --git a/readSensor.sh b/readSensor.sh index 3a69693..f57bf2c 100755 --- a/readSensor.sh +++ b/readSensor.sh @@ -1,37 +1,79 @@ #!/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="${PWD}/external/Adafruit_Python_DHT/examples/AdafruitDHT.py" + +# 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 ${PWD}/external/Adafruit_Python_DHT/examples/AdafruitDHT.py" + +# Location where the readings should be stored OUTFILE="${PWD}/output" -touch "$OUTFILE" + +# +# no configuration/changes should be necessary below this line +# + +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 22 $GPIOPIN` + OUTPUT=`$CMD $SENSOR $GPIOPIN` T=`echo "$OUTPUT" | awk -F[=*%] '{print $2}'` H=`echo "$OUTPUT" | awk -F[=*%] '{print $4}'` CNT=$(($CNT+1)) - echo "$CNT" } + function check_output () { if [[ $OUTPUT =~ Fail ]] || [[ ! $OUTPUT =~ Temp ]] || [[ ! $OUTPUT =~ Humidity ]] || [ ${T%.*} -lt $MINTEMP ] || [ ${T%.*} -gt $MAXTEMP ]; then - if [ $CNT -le 3 ]; then - sleep 5 + if [ $CNT -le $RETRY ]; then + sleep $DELAY read_sensor check_output else echo "Error" > "$OUTFILE" - exit 0 + exit 1 fi fi } +function write_results () { + echo `date +%s` > "$OUTFILE" + echo "${T}" >> "$OUTFILE" + echo "${H}" >> "$OUTFILE" +} + read_sensor check_output - -echo `date +%s` > "$OUTFILE" -echo "${T}" >> "$OUTFILE" -echo "${H}" >> "$OUTFILE" +write_results