]> mj.ucw.cz Git - home-hw.git/blob - auto/burrow-auto
Power daemon: A new daemon for relaying power meter data to MQTT
[home-hw.git] / auto / burrow-auto
1 #!/usr/bin/python
2
3 import getopt
4 import paho.mqtt.client as mqtt
5 import sys
6 import time
7
8 debug_mode = False
9
10 def debug(msg):
11     if debug_mode:
12         print msg
13
14 class State:
15     def __init__(self):
16         self.attrs = {}
17
18     def update(self):
19         self.now = time.time()
20         tm = time.localtime(self.now)
21         self.year = tm.tm_year
22         self.month = tm.tm_mon
23         self.day = tm.tm_mday
24         self.hour = tm.tm_hour
25         self.min = tm.tm_min
26         self.wday = tm.tm_wday
27
28     def get_sensor(self, key):
29         topic = "burrow/" + key
30         if topic in self.attrs:
31             s = self.attrs[topic].split(" ")
32             if len(s) >= 2 and s[1] < self.now - 120:
33                 return None
34             return float(s[0])
35         else:
36             return None
37
38     def set(self, key, val):
39         global mq
40         topic = "burrow/" + key
41         debug("Setting {} to {}".format(topic, val))
42         mq.publish(topic, val, qos=1, retain=True)
43
44 st = State()
45
46 def on_connect(mq, userdata, flags, rc):
47     mq.subscribe("burrow/#")
48
49 def on_message(mq, userdata, msg):
50     global st
51     debug("Message {}: {}".format(msg.topic, msg.payload))
52     st.attrs[msg.topic] = msg.payload
53
54 def auto_loft_fan():
55     global st
56     lt = st.get_sensor("temp/loft")
57     if lt is not None and lt >= 30:
58         fs = 3
59     elif st.hour in range(10, 20):
60         fs = 2
61     else:
62         fs = 1
63     st.set("loft/fan", fs)
64
65 def auto_circ():
66     global st
67     if st.hour in range(19, 23):
68         c = 1
69     else:
70         c = 0;
71     st.set("loft/circulation", c)
72
73 opts, args = getopt.gnu_getopt(sys.argv[1:], "", ["debug"])
74 for opt in opts:
75     o, arg = opt
76     if o == "--debug":
77         debug_mode = True
78
79 mq = mqtt.Client()
80 mq.on_connect = on_connect
81 mq.on_message = on_message
82 mq.will_set("status/auto", "failed", retain=True)
83 mq.connect("127.0.0.1")
84 mq.publish("status/auto", "ok", retain=True)
85 mq.loop_start()
86
87 while True:
88     st.update()
89     auto_loft_fan()
90     auto_circ()
91     time.sleep(10)