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