import numpy as np import serial import subprocess import time s = serial.Serial("/dev/ttyUSB0", 115200, timeout=10) q = queue.Queue() process = subprocess.Popen(["ssh", "shrooms@threefortiethofonehamster.com", "python", "/home/shrooms/go/src/shroom-server/shroom-pipe.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) # TODO run thread to process data from process's stdout def reset_serial(): s.close() s = serial.Serial("/dev/ttyUSB0", 115200, timeout = 10) time.sleep(10) class Humidifier: def __init__(self): self.on = False self.history = np.array(30) self.switch_timeout = 0 def update(self, volts): self.history[1:] = self.history[:-1] self.history[0] = volts avg = np.sum(self.history)/self.history.shape[0] if self.state: if avg < 0.2: self.on = False else: if avg > 2.6: self.on = True def toggle(self, s): if time.time() > self.switch_timeout: s.write(b"h") self.switch_timeout = time.time() + 7 humidifier = Humidifier() target_lower = 0.85 target_higher = 0.90 try: last_sample = 0 while True: now = time.time() if now - last_sample < 0.5: s.write(b"s") resp = s.read(120) if len(resp) == 0: reset_serial() time.sleep(5) continue parts = resp.split(b",") humidity = float(parts[0]) temp = float(parts[1]) volts = float(parts[2]) print(humidity, temp, volts) humidifier.update(volts) if humidity < target_lower and humidifier.off: humidifier.toggle(s) elif humidity > target_upper and humidifier.on: humidifier.toggle(s) # TODO check on the process else: time.sleep(0.5-(now - last_sample)) finally: # TODO kill ssh connection process. pass