]> mj.ucw.cz Git - home-hw.git/blob - auto/burrow-auto
4dba420893cf3d4c081d5c86f0afb616fb50d441
[home-hw.git] / auto / burrow-auto
1 #!/usr/bin/python3
2
3 import getopt
4 import paho.mqtt.client as mqtt
5 import sys
6 import time
7
8 debug_mode = False
9 indent = 0
10
11 def debug(msg):
12     if debug_mode:
13         print(("\t" * indent) + msg)
14
15 def diff(x, y):
16     if x is None or y is None:
17         return None
18     else:
19         return x - y
20
21 class State:
22     def __init__(self):
23         self.attrs = {}
24         self.hyst_state = {}
25         self.running_averages = {}
26
27     def update(self):
28         self.now = time.time()
29         tm = time.localtime(self.now)
30         self.year = tm.tm_year
31         self.month = tm.tm_mon
32         self.day = tm.tm_mday
33         self.hour = tm.tm_hour
34         self.min = tm.tm_min
35         self.wday = tm.tm_wday
36         debug("[{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d} wday={}]".format(
37             self.year, self.month, self.day,
38             self.hour, self.min, tm.tm_sec,
39             self.wday
40             ))
41
42     def get_sensor(self, key):
43         topic = "burrow/" + key
44         if topic in self.attrs:
45             s = self.attrs[topic].split(" ")
46             if len(s) >= 2 and int(s[1]) < self.now - 120:
47                 debug("< {} EXPIRED".format(key))
48                 return None
49             else:
50                 debug("< {} = {}".format(key, s[0]))
51                 return float(s[0])
52         else:
53             debug("< {} UNDEFINED".format(key))
54             return None
55
56     def set(self, key, val):
57         global mq
58         topic = "burrow/" + key
59         debug("> {} = {}".format(topic, val))
60         mq.publish(topic, val, qos=1, retain=True)
61
62     def auto_enabled(self, key):
63         topic = "burrow/auto/" + key
64         if topic in self.attrs:
65             return self.attrs[topic] != '0'
66         else:
67             return True
68
69     def hysteresis(self, key, value, low, high):
70         if key in self.hyst_state:
71             old_state = self.hyst_state[key]
72         else:
73             old_state = 0
74         if value is None:
75             new_state = 0
76         elif old_state <= 0:
77             if value >= high:
78                 new_state = 1
79             else:
80                 new_state = -1
81         else:
82             if value <= low:
83                 new_state = -1
84             else:
85                 new_state = 1
86         self.hyst_state[key] = new_state
87         return new_state
88
89     def update_average(self, key, window_seconds):
90         if key not in self.running_averages:
91             self.running_averages[key] = ([], 0, 0, None)
92         (history, sum, count, avg) = self.running_averages[key]
93
94         while len(history) > 0 and history[0][0] <= self.now - window_seconds:
95             if history[0][1] is not None:
96                 sum -= history[0][1]
97                 count -= 1
98             history.pop(0)
99
100         curr = self.get_sensor(key)
101         history.append((self.now, curr))
102         if curr is not None:
103             sum += curr
104             count += 1
105
106         if count > len(history) // 2:
107             avg = sum / count
108         else:
109             avg = None
110
111         self.running_averages[key] = (history, sum, count, avg)
112         debug("= avg {:.6} ({} samples, {} non-null)".format(avg, len(history), count))
113         if avg is not None:
114             self.set("avg/" + key, "{:.6} {}".format(avg, int(self.now)))
115
116     def get_sensor_avg(self, key):
117         val = self.running_averages[key][3]
118         debug("< {} = avg {:.6}".format(key, val))
119         return val
120
121 st = State()
122
123 def on_connect(mq, userdata, flags, rc):
124     mq.subscribe("burrow/#")
125
126 def on_message(mq, userdata, msg):
127     global st
128     # debug("Message {}: {}".format(msg.topic, msg.payload))
129     st.attrs[msg.topic] = msg.payload.decode('utf-8')
130
131 def auto_loft_fan():
132     global st
133     lt = st.get_sensor("temp/loft")
134     lt_high = st.hysteresis('lt_high', lt, 29, 30)
135     lt_mid = st.hysteresis('lt_mid', lt, 24, 25)
136     if lt_high > 0:
137             fs = 3
138     elif lt_mid > 0:
139         if st.hour in range(10, 20):
140                 fs = 3
141         else:
142             fs = 1
143     else:
144         if st.hour in range(8, 22):
145             if st.min % 30 in range(0, 5):
146                 fs = 3
147             else:
148                 fs = 0
149         else:
150             fs = 0
151     # FIXME: Disabled for now
152     fs = 0
153     st.set("loft/fan", fs)
154
155 def auto_circ():
156     global st
157     if st.hour in range(7, 24):
158         c = 1
159     else:
160         c = 0;
161     st.set("loft/circulation", c)
162
163 def auto_air():
164     global st
165     tii = st.get_sensor_avg('air/inside-intake')
166     tie = st.get_sensor_avg('air/inside-exhaust')
167     toi = st.get_sensor_avg('air/outside-intake')
168     tmix = st.get_sensor_avg('air/mixed')
169     house_warm = st.hysteresis('house_warm', tii, 23.5, 24.5)
170     house_hot = st.hysteresis('house_hot', tii, 24.5, 25)
171
172     # Is AC currently on (mixed air is significantly colder than inside exhaust)?
173     if tie is None or tmix is None:
174             ac_off = 1
175     else:
176         ac_off = st.hysteresis('ac_off', tmix, tie - 5, tie - 4)
177
178     # XXX: Temporarily disabled
179     house_warm = -1
180     house_hot = -1
181     ac_off = 1
182
183     # Do we want to bypass the heat exchanger?
184     outside_warmer = st.hysteresis('outside_warmer', diff(toi, tii), -0.5, 0.5)
185     if (house_warm > 0) and (outside_warmer > 0) or \
186        (house_warm < 0) and (outside_warmer < 0):
187         st.set('air/bypass', 0)
188     else:
189         st.set('air/bypass', 1)
190
191     # Is mixed air colder than air from the inside?
192     mixed_warmer = st.hysteresis('mixed_warmer', diff(tmix, tii), -1, 0)
193
194     # Do we want to boost heat exchanger fan?
195     if ac_off < 0 or (house_hot > 0 and mixed_warmer < 0):
196         st.set('air/exchanger-fan', 255)
197     else:
198         st.set('air/exchanger-fan', 0)
199
200     debug("Air: house_warm={} house_hot={} ac_off={} outside_warmer={} mixed_warmer={}".format(house_warm, house_hot, ac_off, outside_warmer, mixed_warmer))
201
202 opts, args = getopt.gnu_getopt(sys.argv[1:], "", ["debug"])
203 for opt in opts:
204     o, arg = opt
205     if o == "--debug":
206         debug_mode = True
207
208 mq = mqtt.Client()
209 mq.on_connect = on_connect
210 mq.on_message = on_message
211 mq.will_set("status/auto", "dead", retain=True)
212 mq.connect("127.0.0.1")
213 mq.publish("status/auto", "ok", retain=True)
214 mq.loop_start()
215
216 # Heuristic delay to get all attributes from MQTT
217 time.sleep(3)
218
219 checks = [
220     ('loft-fan', auto_loft_fan),
221     ('circ', auto_circ),
222     ('air', auto_air)
223 ]
224
225 while True:
226     st.update()
227
228     debug("averages")
229     indent += 1
230     st.update_average('air/outside-intake', 60)
231     st.update_average('air/inside-intake', 60)
232     st.update_average('air/inside-exhaust', 60)
233     st.update_average('air/mixed', 60)
234     indent -= 1
235
236     for name, func in checks:
237         if st.auto_enabled(name):
238             debug(name)
239             indent += 1
240             func()
241             indent -= 1
242         else:
243             debug("{} DISABLED".format(name))
244     debug("=" * 80)
245     time.sleep(10)