Files
sensor-1wire/readSensor
2021-01-09 14:29:13 +01:00

90 lines
2.1 KiB
Bash
Executable File

#!/bin/bash
#
# Copyright (c) 2018 leopold@shdx.org
# Author: Der_Leopold
#
# This script tries to read sensor values from a 1wire bus and writes the results
# and a timestamp to a file. It is intended to be executed periodically, for
# example via crontab.
#
# 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 sensors will be operating
# This is simply used as a safeguard to detect implausible sensor readings
MINTEMP=-30
MAXTEMP=40
# Interface that is connected to the 1wire bus
USETTY=/dev/ttyUSB0
# Location of the digittemp config file with data about the sensors
DIGITEMPCONF="/etc/digitemp.conf"
# Command to use for reading the sensors
CMD="sudo /usr/bin/digitemp_DS9097"
CMDOPTS=" -q -s $USETTY -c $DIGITEMPCONF"
# Define sensors that should be queried
# Format: [<Label>]=<Id>
declare -A SENSORS=( [0]=LuftTemp [1]=WasserTemp [2]=BodenTemp )
# Location where the readings should be stored
OUTFILE="output"
RESULT=""
#
# 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
function read_sensor () {
OUTPUT=`$CMD $CMDOPTS -t $SENSORID`
VALUE=`echo "$OUTPUT" | awk -F "C: " '{print $2}' | awk -F " F:" '{print $1}'`
CNT=$(($CNT+1))
}
function check_output () {
if [[ $OUTPUT =~ fail ]] || [[ $OUTPUT =~ owAcquire ]] || [ ${VALUE%.*} -lt $MINTEMP ] || [ ${VALUE%.*} -gt $MAXTEMP ]; then
if [ $CNT -le $RETRY ]; then
sleep $DELAY
read_sensor
check_output
else
RESULT="$RESULT${SENSORS[$SENSORID]}=Error\n"
fi
fi
}
function store_result () {
RESULT="$RESULT${SENSORS[$SENSORID]}=${VALUE}\n"
}
function write_to_file () {
echo "Timestamp="`date +%s` > "$OUTFILE"
echo -e "$RESULT" >> "$OUTFILE"
}
for SENSORID in "${!SENSORS[@]}"
do
CNT=0
read_sensor
check_output
store_result
sleep $DELAY
done
write_to_file