#!/bin/bash
# -*- bash -*-
# vim: ft=bash
#
# $Id$
#

: << =cut

=head1 NAME

fhem_max_ - plugin to graph temperature and desiredTemperature from ELV/EQ3 MAX devices

=head1 APPLICABLE SYSTEMS

FHEM must be installed and configured and reacheable via telnet (network or localhost).

Additionally the module 99_getstate.pm has to be enabled. Copy it from the contrib
directory to the FHEM directory and do a shutdown restart, ie:
cp /usr/share/fhem/contrib/getstate/99_getstate.pm /usr/share/fhem/FHEM/

You can test if your devices are able to be queried by submitting this line to FHEM (via telnet or web):
  getstate <device>
  i.e: getstate wz_thermostat1
  output should be something like this: [...] desiredTemperature:15.0 temperature:21.4 [...]

=head1 CONFIGURATION

fhem_max_ has to be linked to the device name, ie. fhem_max_wz_thermostat1

The following environment variables are available

  host - hostname of the fhem server (default: localhost)
  port - telnet port (default: 7072)

This is a typical configuration:

 [fht_max_*]
   env.host fritz.box
   env.port 7072

=head1 INTERPRETATION

Shows a graph with temperature and humidity

=head1 MAGIC MARKERS

 #%# family=auto
 #%# capabilities=autoconf

=head1 BUGS

None known.

=head1 AUTHOR

2014 Oliver Voelker <code@magenbrot.net>

=head1 LICENSE

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

=cut

NC=`which nc 2>/dev/null`
DEVICE=`echo $0 | sed -e 's/.*fhem_max_\(.*\)/\1/'`

HOST="localhost"
PORT="7072"

if [ "$host" ]; then HOST=$host; fi
if [ "$port" ]; then PORT=$port; fi

if [ "$1" = "autoconf" ]; then
  if [ -z "$NC" -o ! -x "$NC" ] ; then 
      echo "no (no nc executable)"
      exit 0
  fi
fi

if [ "$1" = "config" ]; then
  echo "graph_title FHEM sensor (${DEVICE})"
  echo "graph_vlabel temp/hum"
  echo "graph_category fhem"
  echo "temp.label temperature"
  echo "temp.colour 00FF00"
  echo "dtemp.label desiredTemperature"
  echo "dtemp.colour 0000FF"
  exit 0
fi

fhem=`echo -e "getstate ${DEVICE}\nquit" | ${NC} $HOST $PORT`
temp=`echo $fhem | awk '{split($0,a,"temperature:"); split(a[2],b," "); print b[1]}'`
dtemp=`echo $fhem | awk '{split($0,a,"desiredTemperature:"); split(a[2],b," "); print b[1]}'`

echo temp.value $temp
echo dtemp.value $dtemp
