#!/bin/bash
# Description : A simple bash script to monitor or log the temp sensors
# Author : Brendan Horan

SLEEP=$2
LOG=$3

function ds1820_mon {
  echo Polling DS1820 every $SLEEP seconds.
    for (( ; ; ))
    do
      echo Temperature is :
      cat /sys/bus/w1/devices/10-0008027e34ca/w1_slave  | grep t= | cut -c 30-31
      sleep $SLEEP
    done
}

function dht11_mon {
  echo Polling DHT11 every $SLEEP seconds.
    for (( ; ; ))
    do
      echo Temperature and humidity is :
      ./Adafruit_DHT 11 17 | grep Temp | tr "," "\n"
      sleep $SLEEP
    done
}

function ds1820_log {
  echo Logging DS1820 to file every $SLEEP seconds. >> $LOG
    for (( ; ; ))
    do
      echo Temperature is : >> $LOG
      cat /sys/bus/w1/devices/10-0008027e34ca/w1_slave  | grep t= | cut -c 30-31 >> $LOG
      sleep $SLEEP
    done
}

function dht11_log {
  echo Logging DHT11 to file every $SLEEP seconds. >> $LOG
    for (( ; ; ))
    do
      echo Temperature and humidity is : >> $LOG
      ./Adafruit_DHT 11 17 | grep Temp | tr "," "\n" >> $LOG
      sleep $SLEEP
    done
}


case $1 in

  dht11_mon)
    dht11_mon
  ;;

  ds1820_mon)
    ds1820_mon
  ;;
  dht11_log)
    dht11_log
  ;;
  ds1820_log)
    ds1820_log
  ;;

  *)
    echo --------------------------------------------------------------------------------------------
    echo
    echo  DHT11/DS1820 tool syntax.
    echo  The tool has two modes, monitor and log.
    echo  Monitor will print to screen and log will log to a file.
    echo  Script assums the Adafruit_DHT tool is in the same directory.
    echo --------------------------------------------------------------------------------------------
    echo   -- Monitor Mode -- 
    echo  Monitor mode accepts two variables the name of the sensor and the polling time in seconds.
    echo  To poll the ds1820 every 5 seconds the syntax would be :
    echo  "./sensor.sh ds1820_mon 5"
    echo 
    echo  To poll the DHT11 every 5 seconds the syntax would be :
    echo  "./sensor.sh dht11_mon 5"
    echo --------------------------------------------------------------------------------------------
    echo   -- Log Mode --
    echo  Log mode accepts three variables the name of the sensor, polling time and the log file name.
    echo  To log the ds1820 every 5 seconds to the syntax would be :
    echo  "./sensor.sh ds1820_log 5 /var/log/ds1820_temp &"
    echo 
    echo  To log the DHT11 every 5 seconds the syntax would be :
    echo  "./sensor.sh dht11_log 5 /var/log/dht11_log &"
    echo --------------------------------------------------------------------------------------------
  ;;
esac
 
# END

