import numpy as np import time from utils import send_update class Humidifier: def __init__(self): self.off_threshold = 0.4 self.on_threshold = 1.9 self.toggle_cooldown = 16 self._on = False self.history = np.zeros(10) self.switch_timeout = 0 @property def on(self): return self._on @on.setter def on(self, nv): old_on = self._on self._on = nv if nv: print("send hum on") else: print("send hum off") send_update({"status": {"humidifier": nv}}) @property def off(self): return not self.on def update(self, volts): self.history[1:] = self.history[:-1] self.history[0] = volts #print(self.history) avg = np.sum(self.history)/self.history.shape[0] if self.on: if avg < self.off_threshold: self.on = False self.switch_timeout = time.time() + 1 else: if avg > self.on_threshold: self.on = True self.switch_timeout = time.time() + 1 def toggle(self, s): if time.time() > self.switch_timeout: s.write(b"h") s.flush() self.switch_timeout = time.time() + self.toggle_cooldown # the wiring's a little different so the thresholds for detecting on/off are inverted but hopefully a lot more reliable than the original class HumidifierV2: def __init__(self, toggle_cmd=b"i", humidifier_id="humidifier2"): self.on_threshold = 1.5 self.off_threshold = 2.5 self.toggle_cooldown = 7 self.toggle_command = toggle_cmd self._on = False self.history = np.zeros(10) self.switch_timeout = 0 self.humidifier_id = humidifier_id @property def on(self): return self._on @on.setter def on(self, nv): old_on = self._on self._on = nv if nv: print("send {} on".format(self.humidifier_id)) else: print("send {} off".format(self.humidifier_id)) send_update({"status": {self.humidifier_id: nv}}) @property def off(self): return not self.on def update(self, volts): self.history[1:] = self.history[:-1] self.history[0] = volts #print(self.history) avg = np.sum(self.history)/self.history.shape[0] if self.on: if avg > self.off_threshold: self.on = False self.switch_timeout = time.time() + 3 else: if avg < self.on_threshold: self.on = True self.switch_timeout = time.time() + 3 def toggle(self, s): if time.time() > self.switch_timeout: print("toggling {}".format(self.humidifier_id)) s.write(self.toggle_command) s.flush() self.switch_timeout = time.time() + self.toggle_cooldown