3 from collections import deque
5 import paho.mqtt.client as mqtt
14 print(("\t" * indent) + msg, file=sys.stderr)
17 if x is None or y is None:
26 self.running_averages = {}
29 self.now = time.time()
30 tm = time.localtime(self.now)
31 self.year = tm.tm_year
32 self.month = tm.tm_mon
34 self.hour = tm.tm_hour
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,
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))
51 debug("< {} = {}".format(key, s[0]))
54 debug("< {} UNDEFINED".format(key))
57 def set(self, key, val):
59 topic = "burrow/" + key
60 debug("> {} = {}".format(topic, val))
61 mq.publish(topic, val, qos=1, retain=True)
63 def send(self, key, val):
65 topic = "burrow/" + key
66 debug("> {} := {}".format(topic, val))
67 mq.publish(topic, val, qos=1, retain=False)
69 def auto_enabled(self, key):
70 topic = "burrow/auto/" + key
71 if topic in self.attrs:
72 return self.attrs[topic] != '0'
76 def hysteresis(self, key, value, low, high):
77 old_state = self.hyst_state.get(key, 0)
90 self.hyst_state[key] = new_state
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]
98 while len(history) > 0 and history[0][0] <= self.now - window_seconds:
99 if history[0][1] is not None:
104 curr = self.get_sensor(key)
105 history.append((self.now, curr))
110 if count > len(history) // 2:
115 self.running_averages[key] = (history, sum, count, avg)
117 debug("= avg NONE ({} samples, {} non-null)".format(len(history), count))
119 debug("= avg {:.6} ({} samples, {} non-null)".format(avg, len(history), count))
120 self.set("avg/" + key, "{:.6} {}".format(avg, int(self.now)))
122 def get_sensor_avg(self, key):
123 val = self.running_averages[key][3]
125 debug("< {} = avg NONE".format(key))
127 debug("< {} = avg {:.6}".format(key, val))
135 lt = st.get_sensor_avg("temp/loft")
136 out = st.get_sensor_avg('air/outside-intake')
138 if lt is None or out is None:
140 elif st.hysteresis('lf_out_cold', out, 5, 6) < 0:
142 elif st.hysteresis('lf_out_cool', out, 14, 15) < 0:
143 if st.min in range(10, 15):
149 elif st.hysteresis('lf_loft_hot', lt, 23, 24) > 0:
150 if st.hysteresis('lf_loft_hotter_than_out', lt, out - 1, out + 1) > 0:
155 st.set("loft/fan", fs)
160 if st.hour in range(7, 24):
164 st.set("loft/circulation", c)
168 # Heuristics to tell if AC is currently on
170 tie = st.get_sensor_avg('air/inside-exhaust')
171 tmix = st.get_sensor_avg('air/mixed')
172 if tie is None or tmix is None:
175 # Mixed air is significantly colder than inside exhaust
176 ac_on = -st.hysteresis('ac_off', tmix, tie - 5, tie - 4)
178 # FIXME: It might also mean that the loft is cold
185 tii = st.get_sensor_avg('air/inside-intake')
186 tie = st.get_sensor_avg('air/inside-exhaust')
187 toi = st.get_sensor_avg('air/outside-intake')
188 tmix = st.get_sensor_avg('air/mixed')
189 house_warm = st.hysteresis('house_warm', tii, 23.5, 24.5)
190 house_hot = st.hysteresis('house_hot', tii, 24.5, 25)
193 # XXX: Temporarily disabled
198 # Do we want to bypass the heat exchanger?
199 outside_warmer = st.hysteresis('outside_warmer', diff(toi, tii), -0.5, 0.5)
200 if (house_warm > 0) and (outside_warmer > 0) or \
201 (house_warm < 0) and (outside_warmer < 0):
202 st.set('air/bypass', 0)
204 st.set('air/bypass', 1)
206 # Is mixed air colder than air from the inside?
207 mixed_warmer = st.hysteresis('mixed_warmer', diff(tmix, tii), -1, 0)
209 # Do we want to boost heat exchanger fan?
210 if ac_on > 0 or (house_hot > 0 and mixed_warmer < 0):
211 st.set('air/exchanger-fan', 255)
213 st.set('air/exchanger-fan', 0)
215 debug("Air: house_warm={} house_hot={} ac_on={} outside_warmer={} mixed_warmer={}".format(house_warm, house_hot, ac_on, outside_warmer, mixed_warmer))
220 tii = st.get_sensor_avg('air/inside-intake')
221 tie = st.get_sensor_avg('air/inside-exhaust')
222 house_hot = st.hysteresis('ac_house_hot', tii, 23.5, 24)
223 outside_hot = st.hysteresis('ac_outside_hot', tie, 24, 25)
226 if house_hot > 0 and outside_hot > 0:
231 if not hasattr(st, 'last_ac_change'):
232 st.last_ac_change = st.now
233 need_wait = st.last_ac_change + 300 - st.now # FIXME: Increase
236 action = f"wait({need_wait:.0f})"
239 elif ac_on != want_ac:
241 st.send('air/aircon-remote', 'p')
242 st.last_ac_change = st.now
246 debug("AC: house_hot={} outside_hot={} ac_on={} want_ac={} action={}".format(house_hot, outside_hot, ac_on, want_ac, action))
249 def on_connect(mq, userdata, flags, rc):
250 mq.subscribe("burrow/#")
252 def on_message(mq, userdata, msg):
254 # debug("Message {}: {}".format(msg.topic, msg.payload))
255 st.attrs[msg.topic] = msg.payload.decode('utf-8')
257 opts, args = getopt.gnu_getopt(sys.argv[1:], "", ["debug"])
264 mq.on_connect = on_connect
265 mq.on_message = on_message
266 mq.will_set("status/auto", "dead", retain=True)
267 mq.connect("burrow-mqtt")
268 mq.publish("status/auto", "ok", retain=True)
271 # Heuristic delay to get all attributes from MQTT
275 ('loft-fan', auto_loft_fan),
278 ('aircon', auto_aircon),
286 st.update_average('air/outside-intake', 180)
287 st.update_average('air/inside-intake', 180)
288 st.update_average('air/inside-exhaust', 180)
289 st.update_average('air/mixed', 180)
290 st.update_average('temp/loft', 180)
293 for name, func in checks:
294 if st.auto_enabled(name):
300 debug("{} DISABLED".format(name))