]> mj.ucw.cz Git - home-hw.git/blob - auto/burrow-auto
Revert "Auto: Trying lower AC threshold"
[home-hw.git] / auto / burrow-auto
1 #!/usr/bin/python3
2
3 from collections import deque
4 import getopt
5 import os
6 import paho.mqtt.client as mqtt
7 import sys
8 import time
9
10 debug_mode = False
11 log_name = '/run/burrow-auto'
12 log_file = None
13 indent = 0
14
15 def debug(msg):
16     if debug_mode:
17         print(("\t" * indent) + msg, file=sys.stderr)
18     elif log_file is not None:
19         print(("\t" * indent) + msg, file=log_file)
20
21 def debug_open():
22     if not debug_mode:
23         global log_file
24         log_file = open(log_name + '.new', 'w')
25
26 def debug_close():
27     if debug_mode:
28         debug("=" * 80)
29     else:
30         global log_file
31         log_file.close()
32         log_file = None
33         os.rename(log_name + '.new', log_name)
34
35 def diff(x, y):
36     if x is None or y is None:
37         return None
38     else:
39         return x - y
40
41 class State:
42     def __init__(self):
43         self.attrs = {}
44         self.hyst_state = {}
45         self.running_averages = {}
46
47     def update(self):
48         self.now = time.time()
49         tm = time.localtime(self.now)
50         self.year = tm.tm_year
51         self.month = tm.tm_mon
52         self.day = tm.tm_mday
53         self.hour = tm.tm_hour
54         self.min = tm.tm_min
55         self.wday = tm.tm_wday
56         debug("[{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d} wday={}]".format(
57             self.year, self.month, self.day,
58             self.hour, self.min, tm.tm_sec,
59             self.wday
60             ))
61
62     def get_sensor(self, key):
63         topic = "burrow/" + key
64         if topic in self.attrs:
65             s = self.attrs[topic].split(" ")
66             if len(s) >= 2 and int(s[1]) < self.now - 120:
67                 debug("< {} EXPIRED".format(key))
68                 return None
69             else:
70                 debug("< {} = {}".format(key, s[0]))
71                 return float(s[0])
72         else:
73             debug("< {} UNDEFINED".format(key))
74             return None
75
76     def set(self, key, val):
77         global mq
78         topic = "burrow/" + key
79         debug("> {} = {}".format(topic, val))
80         mq.publish(topic, val, qos=1, retain=True)
81
82     def send(self, key, val):
83         global mq
84         topic = "burrow/" + key
85         debug("> {} := {}".format(topic, val))
86         mq.publish(topic, val, qos=1, retain=False)
87
88     def auto_enabled(self, key):
89         topic = "burrow/auto/" + key
90         if topic in self.attrs:
91             return self.attrs[topic] != '0'
92         else:
93             return True
94
95     def hysteresis(self, key, value, low, high):
96         old_state = self.hyst_state.get(key, 0)
97         if value is None:
98             new_state = 0
99         elif old_state <= 0:
100             if value >= high:
101                 new_state = 1
102             else:
103                 new_state = -1
104         else:
105             if value <= low:
106                 new_state = -1
107             else:
108                 new_state = 1
109         self.hyst_state[key] = new_state
110         return new_state
111
112     def update_average(self, key, window_seconds):
113         if key not in self.running_averages:
114             self.running_averages[key] = (deque(), 0, 0, None)
115         (history, sum, count, avg) = self.running_averages[key]
116
117         while len(history) > 0 and history[0][0] <= self.now - window_seconds:
118             if history[0][1] is not None:
119                 sum -= history[0][1]
120                 count -= 1
121             history.popleft()
122
123         curr = self.get_sensor(key)
124         history.append((self.now, curr))
125         if curr is not None:
126             sum += curr
127             count += 1
128
129         if count > len(history) // 2:
130             avg = sum / count
131         else:
132             avg = None
133
134         self.running_averages[key] = (history, sum, count, avg)
135         if avg is None:
136             debug("= avg NONE ({} samples, {} non-null)".format(len(history), count))
137         else:
138             debug("= avg {:.6} ({} samples, {} non-null)".format(avg, len(history), count))
139             self.set("avg/" + key, "{:.6} {}".format(avg, int(self.now)))
140
141     def get_sensor_avg(self, key):
142         val = self.running_averages[key][3]
143         if val is None:
144             debug("< {} = avg NONE".format(key))
145         else:
146             debug("< {} = avg {:.6}".format(key, val))
147         return val
148
149 st = State()
150
151
152 def auto_loft_fan():
153     global st
154     lt = st.get_sensor_avg("temp/loft")
155     out = st.get_sensor_avg('air/outside-intake')
156
157     if lt is None or out is None:
158         fs = 0
159     elif st.hysteresis('lf_out_cold', out, 5, 6) < 0:
160         fs = 0
161     elif st.hysteresis('lf_out_cool', out, 14, 15) < 0:
162         if st.min in range(10, 15):
163             fs = 2
164         else:
165             fs = 0
166     elif ac_is_on() > 0:
167         fs = 3
168     elif st.hysteresis('lf_loft_hot', lt, 25, 26) > 0:
169         if st.hysteresis('lf_loft_hotter_than_out', lt, out - 1, out + 1) > 0:
170             fs = 3
171         else:
172             fs = 1
173     else:
174         if st.min in range(10, 15):
175             fs = 2
176         else:
177             fs = 0
178
179     st.set("loft/fan", fs)
180
181
182 def auto_circ():
183     global st
184     if st.hour in range(7, 24):
185         c = 1
186     else:
187         c = 0;
188     st.set("loft/circulation", c)
189
190
191 def ac_is_on():
192     # Heuristics to tell if AC is currently on
193
194     tie = st.get_sensor_avg('air/inside-exhaust')
195     tmix = st.get_sensor_avg('air/mixed')
196     if tie is None or tmix is None:
197         return 0
198
199     # Mixed air is significantly colder than inside exhaust
200     ac_on = -st.hysteresis('ac_off', tmix, tie - 5, tie - 4)
201
202     # FIXME: It might also mean that the loft is cold
203
204     return ac_on
205
206
207 def auto_air():
208     global st
209     tii = st.get_sensor_avg('air/inside-intake')
210     tie = st.get_sensor_avg('air/inside-exhaust')
211     toi = st.get_sensor_avg('air/outside-intake')
212     tmix = st.get_sensor_avg('air/mixed')
213     house_warm = st.hysteresis('house_warm', tii, 23.5, 24.5)
214     house_hot = st.hysteresis('house_hot', tii, 24.5, 25)
215     ac_on = ac_is_on()
216
217     # XXX: Temporarily disabled
218     #house_warm = -1
219     #house_hot = -1
220     #ac_on = -1
221
222     # Do we want to bypass the heat exchanger?
223     outside_warmer = st.hysteresis('outside_warmer', diff(toi, tii), -0.5, 0.5)
224     if (house_warm > 0) and (outside_warmer > 0) or \
225        (house_warm < 0) and (outside_warmer < 0):
226         st.set('air/bypass', 0)
227     else:
228         st.set('air/bypass', 1)
229
230     # Is mixed air colder than air from the inside?
231     mixed_warmer = st.hysteresis('mixed_warmer', diff(tmix, tii), -1, 0)
232
233     # Do we want to boost heat exchanger fan?
234     if ac_on > 0 or (house_hot > 0 and mixed_warmer < 0):
235         st.set('air/exchanger-fan', 255)
236     else:
237         st.set('air/exchanger-fan', 0)
238
239     debug("Air: house_warm={} house_hot={} ac_on={} outside_warmer={} mixed_warmer={}".format(house_warm, house_hot, ac_on, outside_warmer, mixed_warmer))
240
241     if ac_on != 0:
242         st.set("air/ac-on", "{} {}".format(1 if ac_on > 0 else 0, int(st.now)))
243     else:
244         st.set("air/ac-on", "")
245
246
247 def auto_aircon():
248     global st
249     tii = st.get_sensor_avg('air/inside-intake')
250     tie = st.get_sensor_avg('air/inside-exhaust')
251     house_hot = st.hysteresis('ac_house_hot', tii, 23.5, 24)
252     outside_hot = st.hysteresis('ac_outside_hot', tie, 24, 25)
253     ac_on = ac_is_on()
254
255     if house_hot > 0 and outside_hot > 0:
256         want_ac = 1
257     else:
258         want_ac = -1
259
260     if not hasattr(st, 'last_ac_change'):
261         st.last_ac_change = st.now
262     need_wait = st.last_ac_change + 300 - st.now    # FIXME: Increase
263
264     if need_wait > 0:
265         action = f"wait({need_wait:.0f})"
266     elif ac_on == 0:
267         action = "need-data"
268     elif ac_on != want_ac:
269         action = "change"
270         st.send('air/aircon-remote', 'p')
271         st.last_ac_change = st.now
272     else:
273         action = "none"
274
275     debug("AC: house_hot={} outside_hot={} ac_on={} want_ac={} action={}".format(house_hot, outside_hot, ac_on, want_ac, action))
276
277
278 def on_connect(mq, userdata, flags, rc):
279     mq.subscribe("burrow/#")
280
281 def on_message(mq, userdata, msg):
282     global st
283     # debug("Message {}: {}".format(msg.topic, msg.payload))
284     st.attrs[msg.topic] = msg.payload.decode('utf-8')
285
286 opts, args = getopt.gnu_getopt(sys.argv[1:], "", ["debug"])
287 for opt in opts:
288     o, arg = opt
289     if o == "--debug":
290         debug_mode = True
291
292 mq = mqtt.Client()
293 mq.on_connect = on_connect
294 mq.on_message = on_message
295 mq.will_set("status/auto", "dead", retain=True)
296 mq.connect("burrow-mqtt")
297 mq.publish("status/auto", "ok", retain=True)
298 mq.loop_start()
299
300 # Heuristic delay to get all attributes from MQTT
301 time.sleep(3)
302
303 checks = [
304     ('loft-fan', auto_loft_fan),
305     ('circ', auto_circ),
306     ('air', auto_air),
307     ('aircon', auto_aircon),
308 ]
309
310 while True:
311     debug_open()
312     st.update()
313
314     debug("averages")
315     indent += 1
316     st.update_average('air/outside-intake', 180)
317     st.update_average('air/inside-intake', 180)
318     st.update_average('air/inside-exhaust', 180)
319     st.update_average('air/mixed', 180)
320     st.update_average('temp/loft', 180)
321     indent -= 1
322
323     for name, func in checks:
324         if st.auto_enabled(name):
325             debug(name)
326             indent += 1
327             func()
328             indent -= 1
329         else:
330             debug("{} DISABLED".format(name))
331
332     debug_close()
333     time.sleep(10)