#!/bin/bash
# Ce script lit les temp?ratures de capteurs ds18b20 connecter sur le bus 1 wire
# puis il sauvegarde les temp?ratures dans une base mysql
#
function string_to_int (){
LANG=C
d=${1##*.}
if [[ ${#1} -eq ${#d} ]]; then
d=0
fi
e=${1%.*}
e=${e//,/}
printf %.0f "$e.$d" 2>/dev/null
}
_TIMESTAMP=$( date +%s )
_DATE=$( date +%Y-%m-%d)
_HEURE=$(date +%H:%M:%S)
temperature=3.14
#echo $_TIMESTAMP
#echo $_DATE
#echo $_HEURE
index=0
# r?cup?re tous les devices qui appartiennent ? la famille '28'
FILES=`ls /sys/bus/w1/devices/w1_bus_master1/ | grep '^28'`
# iteration sur tous les devices
for file in $FILES
do
# r?cup?re les deux ligne de la r?ponse du device
#cat /sys/bus/w1/devices/w1_bus_master1/$file/w1_slave
GETDATA=`cat /sys/bus/w1/devices/w1_bus_master1/$file/w1_slave`
GETDATA1=`echo "$GETDATA" | grep crc`
GETDATA2=`echo "$GETDATA" | grep t=`
#echo $GETDATA1
#echo $GETDATA2
# get temperature
TEMP=`echo $GETDATA2 | sed -n 's/.*t=//;p'`
#
# test if crc is 'YES' and temperature is not -62 or +85
if [ `echo $GETDATA1 | sed 's/^.*\(...\)$/\1/'` == "YES" -a $TEMP != "-62" -a $TEMP != "85000" ]
then
# crc is 'YES' and temperature is not -62 or +85 - so save result
_mavar=0
#echo `date +"%Y-%m-%d %H:%M:%S "; echo $GETDATA2 | sed -n 's/.*t=//;p'`
else
# there was an error (crc not 'yes' or invalid temperature)
# try again after waiting 1 second
sleep 1
# get the 2 lines of the response from the device again
GETDATA=`cat /sys/bus/w1/devices/w1_bus_master1/$file/w1_slave`
GETDATA1=`echo "$GETDATA" | grep crc`
GETDATA2=`echo "$GETDATA" | grep t=`
# get the temperature from the new response
TEMP=`echo $GETDATA2 | sed -n 's/.*t=//;p'`
if [ `echo $GETDATA1 | sed 's/^.*\(...\)$/\1/'` == "YES" -a $TEMP != "-62" -a $TEMP != "85000" ]
then
# save result if crc is 'YES' and temperature is not -62 or +85 - if not, just miss it and move on
#echo `date +"%d-%m-%Y %H:%M:%S "; echo $GETDATA2 | sed -n 's/.*t=//;p'`
_mavar=0
fi
fi
tempe=`echo $GETDATA2 | sed -n 's/.*t=//;p'`
temperature=$(string_to_int $tempe)
temperature=`cat /sys/bus/w1/devices/$file/w1_slave | sed -n 's/^.*\(t=[^ ]*\).*/\1/p' | sed 's/t=//' | awk '{x=$1}END{printf("%.1f" , x/1000)}'`
tableau[index]=$temperature
#echo ${tableau[$index]}
index=$(($index + 1))
done
#echo $_TIMESTAMP $_DATE $_HEURE ${tableau[0]} ${tableau[1]}
mysql -uutilisateur -ppassword base<< EOF
insert into temperatures (timestamp,rec_date,rec_time,s1,s2) values ('$_TIMESTAMP','$_DATE','$_HEURE','${tableau[0]}','${tableau[1]}');
EOF
exit 0