#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import serial
import sys

re_fmt = "^%s[^:]*: (.+)$"
h_re = re.compile(re_fmt % "Humidity")
t_re = re.compile(re_fmt % "Temperature")
exprs = {"H": h_re, "T": t_re}
conv = {"T": lambda x: x / 10.}

lines_to_read = 2

def read_data(ser):
    data = {}

    while data == {}:
        ser.write("\n")
        for i in xrange(lines_to_read):
            line = ser.readline()
            for k, expr in exprs.items():
                m = expr.match(line)
                if m is not None:
                    data[k] = float(m.group(1))
                    if k in conv:
                        data[k] = conv[k](data[k])
    return data

def main_tty():
    ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)

    while True:
        data = read_data(ser)
        print data
        if raw_input("q to quit: ") == "q":
            break

    ser.close()

def main_munin():
    mode = None
    if len(sys.argv) > 1:
        mode = sys.argv[1]

    arg = sys.argv[0].rsplit("_", 1)[-1]
    if arg not in ["hygro", "temp"]:
        return 1

    if mode == "config":
        print "host_name mdr.crans.org"
        print "graph_category Environnement"
        
        if arg == "hygro":
            print "graph_title Hygrométrie 4J"
            print "graph_vlabel Humidité (%)"
            print "graph_args --lower-limit 0 --upper-limit 100 --rigid"
            print "hygro.label Humidité 4J"
        elif arg == "temp":
            print "graph_title Température 4J"
            print "graph_vlabel Température (°C)"
            print "temp.label Température 4J"
    else:
        ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
        data = read_data(ser)
        ser.close()

        if arg == "hygro":
            print "hygro.value %d" % data["H"]
        elif arg == "temp":
            print "temp.value %.1f" % data["T"]

    return 0

if __name__ == '__main__':
    if sys.argv[0].endswith(".py"):
        try:
            main_tty()
        except KeyboardInterrupt:
            print
    else:
        sts = main_munin()
        sys.exit(sts)

