meteo4J_ 2.08 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#!/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)