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, 25, 26) > 0:
150 if st.hysteresis('lf_loft_hotter_than_out', lt, out - 1, out + 1) > 0:
155 if st.min in range(10, 15):
160 st.set("loft/fan", fs)
165 if st.hour in range(7, 24):
169 st.set("loft/circulation", c)
173 # Heuristics to tell if AC is currently on
175 tie = st.get_sensor_avg('air/inside-exhaust')
176 tmix = st.get_sensor_avg('air/mixed')
177 if tie is None or tmix is None:
180 # Mixed air is significantly colder than inside exhaust
181 ac_on = -st.hysteresis('ac_off', tmix, tie - 5, tie - 4)
183 # FIXME: It might also mean that the loft is cold
190 tii = st.get_sensor_avg('air/inside-intake')
191 tie = st.get_sensor_avg('air/inside-exhaust')
192 toi = st.get_sensor_avg('air/outside-intake')
193 tmix = st.get_sensor_avg('air/mixed')
194 house_warm = st.hysteresis('house_warm', tii, 23.5, 24.5)
195 house_hot = st.hysteresis('house_hot', tii, 24.5, 25)
198 # XXX: Temporarily disabled
203 # Do we want to bypass the heat exchanger?
204 outside_warmer = st.hysteresis('outside_warmer', diff(toi, tii), -0.5, 0.5)
205 if (house_warm > 0) and (outside_warmer > 0) or \
206 (house_warm < 0) and (outside_warmer < 0):
207 st.set('air/bypass', 0)
209 st.set('air/bypass', 1)
211 # Is mixed air colder than air from the inside?
212 mixed_warmer = st.hysteresis('mixed_warmer', diff(tmix, tii), -1, 0)
214 # Do we want to boost heat exchanger fan?
215 if ac_on > 0 or (house_hot > 0 and mixed_warmer < 0):
216 st.set('air/exchanger-fan', 255)
218 st.set('air/exchanger-fan', 0)
220 debug("Air: house_warm={} house_hot={} ac_on={} outside_warmer={} mixed_warmer={}".format(house_warm, house_hot, ac_on, outside_warmer, mixed_warmer))
225 tii = st.get_sensor_avg('air/inside-intake')
226 tie = st.get_sensor_avg('air/inside-exhaust')
227 house_hot = st.hysteresis('ac_house_hot', tii, 23.5, 24)
228 outside_hot = st.hysteresis('ac_outside_hot', tie, 24, 25)
231 if house_hot > 0 and outside_hot > 0:
236 if not hasattr(st, 'last_ac_change'):
237 st.last_ac_change = st.now
238 need_wait = st.last_ac_change + 300 - st.now # FIXME: Increase
241 action = f"wait({need_wait:.0f})"
244 elif ac_on != want_ac:
246 st.send('air/aircon-remote', 'p')
247 st.last_ac_change = st.now
251 debug("AC: house_hot={} outside_hot={} ac_on={} want_ac={} action={}".format(house_hot, outside_hot, ac_on, want_ac, action))
254 def on_connect(mq, userdata, flags, rc):
255 mq.subscribe("burrow/#")
257 def on_message(mq, userdata, msg):
259 # debug("Message {}: {}".format(msg.topic, msg.payload))
260 st.attrs[msg.topic] = msg.payload.decode('utf-8')
262 opts, args = getopt.gnu_getopt(sys.argv[1:], "", ["debug"])
269 mq.on_connect = on_connect
270 mq.on_message = on_message
271 mq.will_set("status/auto", "dead", retain=True)
272 mq.connect("burrow-mqtt")
273 mq.publish("status/auto", "ok", retain=True)
276 # Heuristic delay to get all attributes from MQTT
280 ('loft-fan', auto_loft_fan),
283 ('aircon', auto_aircon),
291 st.update_average('air/outside-intake', 180)
292 st.update_average('air/inside-intake', 180)
293 st.update_average('air/inside-exhaust', 180)
294 st.update_average('air/mixed', 180)
295 st.update_average('temp/loft', 180)
298 for name, func in checks:
299 if st.auto_enabled(name):
305 debug("{} DISABLED".format(name))