Save before switching to new architecture

This commit is contained in:
Kelvin Ly 2025-02-10 23:09:55 -05:00
parent 5dd60e87e4
commit 36a7d28187
9 changed files with 1200 additions and 228 deletions

8
.gitignore vendored
View File

@ -2,5 +2,13 @@ shroom_server
shrooms.db
auth_secret
__pycache__/
target/
test_float_parse
# venv stuff
bin/
create/
lib/
lib64
pyvenv.cfg

View File

@ -1,73 +1,218 @@
import numpy as np
import time
import threading
from utils import send_update
from humidifier import Humidifier, HumidifierV2
from humidifier_v3 import HumidifierV3
class Controller:
def __init__(self, humidifiers):
self.target_lower = 83
self.target_upper = 87
self.feedforward_coeff = 50
self.last_toggle = 0
def __init__(self, ser):
# if there isn't a timeout we can get deadlocked in some situations
assert ser.timeout is not None
self._manual_mode = False
self.manual_on = False
self.manual_timeout = 0
self.manual_duration = 40
self.ser = ser
self.ser_lock = threading.Lock()
self.humidifier_history = np.zeros(50)
self.first_sample = False
self.humidifiers = humidifiers
self.callbacks = dict()
self.properties = dict()
self.last_status = None
@property
def manual_mode(self):
return self._manual_mode
# add callbacks to these to capture these events
self.on_status = []
self.on_fan_toggle = []
self.on_humd_toggle = []
@manual_mode.setter
def manual_mode(self, on):
self._manual_mode = on
send_update({"status": {"manual_mode": on}})
self.registerCallback(b"s:", lambda line: self._read_status(line))
self.registerCallback(b"h:", lambda line: self._toggle_cb(line))
self.registerCallback(b"f:", lambda line: self._toggle_cb(line))
def set_checked(self, s, humidifier, on):
if time.time() - self.last_toggle > 0.8:
print("setting {} to {}".format(humidifier, on))
if isinstance(humidifier, HumidifierV3):
humidifier.set(s, on)
elif isinstance(humidifier, Humidifier) or isinstance(humidifier, HumidifierV2):
humidifier.toggle(s)
self.last_toggle = time.time()
self.processing = True
self.process_thr = threading.Thread(target=self._process_loop)
self.process_thr.start()
def update(self, s, humidity):
if self.first_sample:
self.humidifier_history[:] = humidity
self.first_sample = False
else:
self.humidifier_history[:-1] = self.humidifier_history[1:]
self.humidifier_history[-1] = humidity
def stop(self):
self.processing = False
if self.process_thr is not None:
self.process_thr.join()
# compensate for the slow response time by adding a little feed forward
# using the slope of the humidifier data
slope = (self.humidifier_history[-1] - self.humidifier_history[0])/self.humidifier_history.shape[0]
comp_humidity = humidity + self.feedforward_coeff*slope
def restart(self):
self.stop()
if self.manual_mode and time.time() > self.manual_timeout:
self.manual_mode = False
self.processing = True
self.process_thr = threading.Thread(target=self._process_loop)
self.process_thr.start()
if self.manual_mode:
for humidifier in self.humidifiers:
if not humidifier.on and self.manual_on:
self.set_checked(s, humidifier, True)
elif not humidifier.off and not self.manual_on:
self.set_checked(s, humidifier, False)
else:
if comp_humidity < self.target_lower:
for humidifier in self.humidifiers:
if not humidifier.on:
self.set_checked(s, humidifier, True)
elif comp_humidity > self.target_upper:
for humidifier in self.humidifiers:
if not humidifier.off:
self.set_checked(s, humidifier, False)
def _read_status(self, line: bytes):
parts = line.split(b":")
if len(parts) < 5:
print("w: invalid status ", line)
return
self.last_status = {
"humd": float(parts[1]),
"temp": float(parts[2]),
"v": float(parts[3]),
"v2": float(parts[4]),
}
for cb in self.on_status:
cb(self.last_status)
def _toggle_cb(self, line: bytes):
parts = line.split(b":")
if len(parts) < 2:
print("w: invalid status ", line)
return
try:
ty = parts[0]
toggle_map = {
b"f": self.on_fan_toggle,
b"h": self.on_humd_toggle,
}
if ty not in toggle_map:
print("e: invalid toggle update ", line)
return
status = int(parts[1])
for cb in toggle_map[ty]:
cb(status)
except Exception as e:
print("e: bad toggle update ", line, repr(e))
def registerCallback(self, prefix, cb):
self.callbacks[prefix] = cb
def unregisterCallback(self, prefix):
del self.callbacks[prefix]
def _process_loop(self):
tmp = b""
try:
while self.processing:
line = self.ser.read_until(b"\n")
tmp += line
if len(tmp) == 0:
continue
if not tmp.endswith(b"\n"):
continue
if len(tmp) > 80:
print("w: ignoring long unterminated line ", tmp)
tmp = b""
continue
self._process_line(tmp.rstrip()) # strip off the newlines
tmp = b""
finally:
self.process_thr = None
def _process_line(self, line):
matching = []
for prefix in self.callbacks:
if line.startswith(prefix):
matching.append(prefix)
if len(matching) == 0:
print("w: uncaught line ", line)
for prefix in matching:
self.callbacks[prefix](line)
def _read(self, prop):
prefix = bytes("r:" + prop, "utf8")
result, me = None, self
ev = threading.Event()
def set_result(v):
nonlocal result, me, ev
if len(v) >= len(prefix):
result = v[len(prefix) + 1 :]
ev.set()
else:
print("e: invalid line found ", v)
me.unregisterCallback(prefix)
self.registerCallback(prefix, set_result)
self.ser.write(prefix + b"\n")
ev.wait(timeout=1.0)
return result
def _write(self, prop, val):
prefix = bytes("w:" + prop, "utf8")
full_msg = prefix + bytes(":{}\n".format(val), "utf8")
success, me = False, self
ev = threading.Event()
def set_result(_):
nonlocal success, me, ev
success = True
ev.set()
me.unregisterCallback(prefix)
self.registerCallback(prefix, set_result)
self.ser.write(full_msg)
ev.wait(timeout=1.0)
return success
def enumerate(self):
done, line_added, me = threading.Event(), False, self
def add_property(line: bytes):
nonlocal me, done, line_added
parts = line.split(b":")
if len(parts) >= 3:
ty_map = {b"i": int, b"f": float, b"b": lambda x: bool(int(x))}
if parts[2] in ty_map:
me.properties[parts[1].decode("utf8")] = ty_map[parts[2]]
line_added = True
else:
print("w: unknown property {} found: {}".format(parts[1], line))
elif line.startswith(b"d:done"):
done.set()
self.registerCallback(b"d:", add_property)
self.ser.write(b"d\n")
done.wait(timeout=1.0)
def queryStatus(self):
self.ser.write(b"s\n")
# callbacks should handle everything else
def getProp(self, prop: str):
if prop not in self.properties:
raise ValueError("invalid property {}".format(prop))
for _ in range(5):
result = self._read(prop)
if result is not None:
try:
return self.properties[prop](result)
except Exception as e:
print("e: unable to convert result ", result, repr(e))
raise RuntimeError("unable to read prop {}".format(prop))
def setProp(self, prop: str, val):
if prop not in self.properties:
raise ValueError("invalid property {}".format(prop))
for _ in range(5):
result = self._write(prop, val)
if result is not None:
try:
return self.properties[prop](result)
except Exception as e:
print("e: unable to convert result ", result, repr(e))
raise RuntimeError("unable to write prop {} {}".format(prop, val))
def humidifier(self, enable):
if enable:
self.ser.write(b"H\n")
else:
self.ser.write(b"h\n")
def fan(self, enable):
if enable:
self.ser.write(b"F\n")
else:
self.ser.write(b"f\n")
def manualMode(self, enable):
if enable:
self.ser.write(b"M\n")
else:
self.ser.write(b"m\n")

3
humidifier_controller/build.sh Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/bash
arduino-cli compile -e

View File

@ -163,11 +163,11 @@ void setup()
void printStatus() {
Serial.print(F("s:"));
Serial.print(cur.humd);
Serial.print(F(","));
Serial.print(F(":"));
Serial.print(cur.temp);
Serial.print(F(","));
Serial.print(F(":"));
Serial.print(cur.volt1);
Serial.print(F(","));
Serial.print(F(":"));
Serial.print(cur.volt2);
Serial.println(F(""));
}
@ -421,18 +421,19 @@ void dumpIntrospect() {
void loop()
{
unsigned long now = millis();
if ((now - cur.last_sample_time) > cur.sample_time_millis) {
if (now > (cur.manual_mode_ts_millis + cur.manual_mode_timeout_millis)) {
cur.manual_mode = false;
}
if ((now - cur.last_sample_time) >= cur.sample_time_millis) {
cur.last_sample_time = now;
if (now > (cur.manual_mode_ts_millis + cur.manual_mode_timeout_millis)) {
cur.manual_mode = false;
}
cur.readSamples();
if (!cur.manual_mode) {
cur.controlHumidifier();
cur.controlFan();
printStatus();
}
printStatus();
}
if (Serial.available()) {
const int c = Serial.read();
@ -505,10 +506,14 @@ void loop()
Serial.print(F(":"));
tmp.readVal();
Serial.println(F(""));
} else if (c == 'z') humidifier(true);
else if (c == 'Z') humidifier(false);
else if (c == 'y') fan(true);
else if (c == 'Y') fan(false);
} else if (c == 'H') humidifier(true);
else if (c == 'h') humidifier(false);
else if (c == 'F') fan(true);
else if (c == 'f') fan(false);
else if (c == 'M') {
cur.manual_mode = true;
cur.manual_mode_ts_millis = millis();
} else if (c == 'm') cur.manual_mode = false;
else if (c == 'd') dumpIntrospect();
}
}

View File

@ -0,0 +1 @@
default_fqbn: arduino:avr:uno

742
shroom-client/Cargo.lock generated Normal file
View File

@ -0,0 +1,742 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "addr2line"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678"
dependencies = [
"gimli",
]
[[package]]
name = "adler"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
[[package]]
name = "autocfg"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0"
[[package]]
name = "backtrace"
version = "0.3.73"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a"
dependencies = [
"addr2line",
"cc",
"cfg-if",
"libc",
"miniz_oxide",
"object",
"rustc-demangle",
]
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
[[package]]
name = "bytes"
version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50"
[[package]]
name = "cc"
version = "1.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57b6a275aa2903740dc87da01c62040406b8812552e97129a63ea8850a17c6e6"
dependencies = [
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "futures"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0"
dependencies = [
"futures-channel",
"futures-core",
"futures-executor",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d"
[[package]]
name = "futures-executor"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1"
[[package]]
name = "futures-macro"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "futures-sink"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5"
[[package]]
name = "futures-task"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004"
[[package]]
name = "futures-util"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite",
"pin-utils",
"slab",
]
[[package]]
name = "gimli"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd"
[[package]]
name = "hermit-abi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
[[package]]
name = "io-kit-sys"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "617ee6cf8e3f66f3b4ea67a4058564628cde41901316e19f559e14c7c72c5e7b"
dependencies = [
"core-foundation-sys",
"mach2",
]
[[package]]
name = "itoa"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
[[package]]
name = "libc"
version = "0.2.158"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439"
[[package]]
name = "lock_api"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
[[package]]
name = "mach2"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b955cdeb2a02b9117f121ce63aa52d08ade45de53e48fe6a38b39c10f6f709"
dependencies = [
"libc",
]
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "memoffset"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4"
dependencies = [
"autocfg",
]
[[package]]
name = "miniz_oxide"
version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08"
dependencies = [
"adler",
]
[[package]]
name = "mio"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys 0.48.0",
]
[[package]]
name = "mio"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec"
dependencies = [
"hermit-abi",
"libc",
"wasi",
"windows-sys 0.52.0",
]
[[package]]
name = "mio-serial"
version = "5.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20a4c60ca5c9c0e114b3bd66ff4aa5f9b2b175442be51ca6c4365d687a97a2ac"
dependencies = [
"log",
"mio 0.8.11",
"nix",
"serialport",
"winapi",
]
[[package]]
name = "nix"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b"
dependencies = [
"bitflags 1.3.2",
"cfg-if",
"libc",
"memoffset",
"pin-utils",
]
[[package]]
name = "object"
version = "0.36.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b64972346851a39438c60b341ebc01bba47464ae329e55cf343eb93964efd9"
dependencies = [
"memchr",
]
[[package]]
name = "parking_lot"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-targets 0.52.6",
]
[[package]]
name = "pin-project-lite"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "proc-macro2"
version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4"
dependencies = [
"bitflags 2.6.0",
]
[[package]]
name = "rustc-demangle"
version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
[[package]]
name = "ryu"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.209"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99fce0ffe7310761ca6bf9faf5115afbc19688edd00171d81b1bb1b116c63e09"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.209"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5831b979fd7b5439637af1752d535ff49f4860c0f341d1baeb6faf0f4242170"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.127"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8043c06d9f82bd7271361ed64f415fe5e12a77fdb52e573e7f06a516dea329ad"
dependencies = [
"itoa",
"memchr",
"ryu",
"serde",
]
[[package]]
name = "serialport"
version = "4.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "241ebb629ed9bf598b2b392ba42aa429f9ef2a0099001246a36ac4c084ee183f"
dependencies = [
"bitflags 2.6.0",
"cfg-if",
"core-foundation-sys",
"io-kit-sys",
"mach2",
"nix",
"scopeguard",
"unescaper",
"winapi",
]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "shroom-client"
version = "0.1.0"
dependencies = [
"serde_json",
"tokio",
"tokio-serial",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
dependencies = [
"libc",
]
[[package]]
name = "slab"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
dependencies = [
"autocfg",
]
[[package]]
name = "smallvec"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
name = "socket2"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c"
dependencies = [
"libc",
"windows-sys 0.52.0",
]
[[package]]
name = "syn"
version = "2.0.76"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "578e081a14e0cefc3279b0472138c513f37b41a08d5a3cca9b6e4e8ceb6cd525"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio"
version = "1.39.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babc99b9923bfa4804bd74722ff02c0381021eafa4db9949217e3be8e84fff5"
dependencies = [
"backtrace",
"bytes",
"libc",
"mio 1.0.2",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys 0.52.0",
]
[[package]]
name = "tokio-macros"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-serial"
version = "5.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa6e2e4cf0520a99c5f87d5abb24172b5bd220de57c3181baaaa5440540c64aa"
dependencies = [
"cfg-if",
"futures",
"log",
"mio-serial",
"tokio",
]
[[package]]
name = "unescaper"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c878a167baa8afd137494101a688ef8c67125089ff2249284bd2b5f9bfedb815"
dependencies = [
"thiserror",
]
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets 0.48.5",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
name = "windows-targets"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm 0.48.5",
"windows_aarch64_msvc 0.48.5",
"windows_i686_gnu 0.48.5",
"windows_i686_msvc 0.48.5",
"windows_x86_64_gnu 0.48.5",
"windows_x86_64_gnullvm 0.48.5",
"windows_x86_64_msvc 0.48.5",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

11
shroom-client/Cargo.toml Normal file
View File

@ -0,0 +1,11 @@
[package]
name = "shroom-client"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
serde_json = "1.0"
tokio = { version = "1.39.3", features = ["full"] }
tokio-serial = "5.4"

57
shroom-client/src/main.rs Normal file
View File

@ -0,0 +1,57 @@
extern crate serde_json;
extern crate tokio;
extern crate tokio_serial;
//use tokio::process::Command;
use tokio::net::TcpStream;
use tokio::io::AsyncWriteExt;
use tokio_serial::{SerialPort, available_ports};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// use two tasks to handle everything, passing data into queues
// one to supervise the SSH tunnel used to transfer data over TCP
// to the server backend
// one for serial, one for TCP messages
// Moving this into a systemd service that the client will depend on
/*
tokio::spawn(async {
// constantly retry spawning with exponential timeouts
let mut timeout = 5;
loop {
let child = Command::new(ssh)
.args("-L 0.0.0.0:3333:localhost:4444")
.args("shrooms@git.threefortiethofonehamster.com")
.args("-N")
.kill_on_drop(true)
.spawn();
if !child.is_ok() {
println!("ssh pipe failed to spawn, ")
}
let status = child..await;
println!("")
}
});
*/
tokio::spawn(async move {
// TODO TCP stuff here
// TODO connect to the SSH tunnel
// TODO retry if it fails
// TODO read from TCP or serial event queue, handle appropriately
});
loop {
// TODO serial stuff here
let mut ser: Option<Box<dyn SerialPort>> = {
let all_ports = available_ports();
// TODO get the port
None
};
}
Ok(())
}

View File

@ -1,5 +1,3 @@
import numpy as np
import json
import os
import serial
@ -7,10 +5,6 @@ import subprocess
import threading
import time
from humidifier import Humidifier, HumidifierV2
from humidifier_v3 import HumidifierV3
from controller import Controller
import utils
from utils import start_process, send_update
@ -21,98 +15,105 @@ SAMPLE_PERIOD = 0.5
DECIMATION_RATE = 1
try:
is_mock = os.environ['MOCK']
is_mock = os.environ["MOCK"]
except KeyError:
is_mock = False
is_mock = False
print("controller start")
start_process()
if is_mock:
import mock_serial
s = mock_serial.MockSerial()
import mock_serial
s = mock_serial.MockSerial()
else:
s = serial.Serial(SERIAL_PATH, SERIAL_BAUD, timeout = 0.3)
print("pausing for bootloader...")
time.sleep(10)
print("pause done")
s = serial.Serial(SERIAL_PATH, SERIAL_BAUD, timeout=0.3)
print("pausing for bootloader...")
time.sleep(10)
print("pause done")
def reset_serial():
global s
if not is_mock:
s.close()
s = serial.Serial(SERIAL_PATH, SERIAL_BAUD, timeout = 0.3)
time.sleep(10)
global s
if not is_mock:
s.close()
s = serial.Serial(SERIAL_PATH, SERIAL_BAUD, timeout=0.3)
time.sleep(10)
humidifier = HumidifierV3()
controller = Controller([humidifier])
exiting = False
# run thread to process data from process's stdout
def stdout_loop():
global process, controller, humidifier, humidifier2
while not exiting:
msg = utils.process.stdout.readline()
if len(msg) <= 1:
continue
print("got message ", msg)
try:
msg_js = json.loads(msg)
if "query_params" in msg_js:
if msg_js["query_params"]:
send_update({"params": {
"target_lower": controller.target_lower,
"target_upper": controller.target_upper,
"feedforward_coeff": controller.feedforward_coeff,
"manual_timeout": controller.manual_timeout,
"manual_duration_s": controller.manual_duration,
"manual_mode": 1.0 if controller.manual_mode else 0.0,
"manual_hum_on": 1.0 if controller.manual_on else 0.0,
global process, controller, humidifier, humidifier2
while not exiting:
msg = utils.process.stdout.readline()
if len(msg) <= 1:
continue
print("got message ", msg)
try:
msg_js = json.loads(msg)
if "query_params" in msg_js:
if msg_js["query_params"]:
send_update(
{
"params": {
"target_lower": controller.target_lower,
"target_upper": controller.target_upper,
"feedforward_coeff": controller.feedforward_coeff,
"manual_timeout": controller.manual_timeout,
"manual_duration_s": controller.manual_duration,
"manual_mode": 1.0 if controller.manual_mode else 0.0,
"manual_hum_on": 1.0 if controller.manual_on else 0.0,
"off_threshold_volts": humidifier.off_threshold,
"on_threshold_volts": humidifier.on_threshold,
"toggle_cooldown": humidifier.toggle_cooldown,
}
}
)
elif "set_params" in msg_js:
if type(msg_js["set_params"]) is dict:
set_params = msg_js["set_params"]
if "name" in set_params and "value" in set_params:
name, value = set_params["name"], set_params["value"]
if type(value) is float:
if name == "target_lower":
controller.target_lower = value
elif name == "target_upper":
controller.target_upper = value
elif name == "feedforward_coeff":
controller.feedforward_coeff = value
elif name == "manual_timeout":
controller.manual_timeout = value
elif name == "manual_duration_s":
controller.manual_duration = value
elif name == "off_threshold_volts":
humidifier.off_threshold = value
elif name == "on_threshold_volts":
humidifier.on_threshold = value
elif name == "toggle_cooldown":
humidifier.toggle_cooldown = value
elif name == "off_threshold_volts2":
humidifier2.off_threshold = value
elif name == "on_threshold_volts2":
humidifier2.on_threshold = value
elif name == "toggle_cooldown2":
humidifier2.toggle_cooldown = value
elif "manual_mode" in msg_js:
controller.manual_mode = msg_js["manual_mode"]
if controller.manual_mode:
controller.manual_timeout = time.time() + controller.manual_duration
elif "manual_mode_on" in msg_js:
controller.manual_on = msg_js["manual_mode_on"]
except json.JSONDecodeError as e:
print("received bad json ", msg)
"off_threshold_volts": humidifier.off_threshold,
"on_threshold_volts": humidifier.on_threshold,
"toggle_cooldown": humidifier.toggle_cooldown
}
})
elif "set_params" in msg_js:
if type(msg_js["set_params"]) is dict:
set_params = msg_js["set_params"]
if "name" in set_params and "value" in set_params:
name, value = set_params["name"], set_params["value"]
if type(value) is float:
if name == "target_lower":
controller.target_lower = value
elif name == "target_upper":
controller.target_upper = value
elif name == "feedforward_coeff":
controller.feedforward_coeff = value
elif name == "manual_timeout":
controller.manual_timeout = value
elif name == "manual_duration_s":
controller.manual_duration = value
elif name == "off_threshold_volts":
humidifier.off_threshold = value
elif name == "on_threshold_volts":
humidifier.on_threshold = value
elif name == "toggle_cooldown":
humidifier.toggle_cooldown = value
elif name == "off_threshold_volts2":
humidifier2.off_threshold = value
elif name == "on_threshold_volts2":
humidifier2.on_threshold = value
elif name == "toggle_cooldown2":
humidifier2.toggle_cooldown = value
elif "manual_mode" in msg_js:
controller.manual_mode = msg_js["manual_mode"]
if controller.manual_mode:
controller.manual_timeout = time.time() + controller.manual_duration
elif "manual_mode_on" in msg_js:
controller.manual_on = msg_js["manual_mode_on"]
except json.JSONDecodeError as e:
print("received bad json ", msg)
stdout_thread = threading.Thread(target=stdout_loop)
stdout_thread.start()
def restart_pipe():
global exiting, stdout_thread
exiting = True
@ -127,7 +128,6 @@ def restart_pipe():
stdout_thread.start()
frame_num = 0
last_sample = 0
@ -138,83 +138,83 @@ pipe_timeout = 10
fan_on = False
try:
while True:
now = time.time()
while True:
now = time.time()
# check to see if the SSH pipe is working
if utils.running():
if not last_running and utils.running():
print("pipe is now running, resetting timeout", pipe_timeout)
pipe_timeout = 10
last_running = utils.running()
# check to see if the SSH pipe is working
if utils.running():
if not last_running and utils.running():
print("pipe is now running, resetting timeout", pipe_timeout)
pipe_timeout = 10
last_running = utils.running()
if not utils.running() and (now - last_pipe_reboot) > pipe_timeout:
try:
restart_pipe()
except Exception as e:
print("error restarting pipe: {}".format(repr(e)))
last_pipe_reboot = now
pipe_timeout *= 1.5
pipe_timeout = min(pipe_timeout, 5 * 60)
print("new pipe timeout ", pipe_timeout)
now = time.time()
if now - last_sample < SAMPLE_PERIOD:
time.sleep(SAMPLE_PERIOD - (now - last_sample) + 0.001)
continue
last_sample = now
# turn on the fan 1 minutes every 5 minutes
cur_min = int(now / 60)
fan_should_be_on = cur_min % 5 == 0
if fan_on != fan_should_be_on:
if fan_should_be_on:
s.write(b"Y")
else:
s.write(b"y")
# print("write s")
s.write(b"s")
s.flush()
resp = s.read(120)
# print("read", resp)
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])
volts2 = float(parts[3])
fan_on = int(volts2)
# print(parts)
if not utils.running() and (now - last_pipe_reboot) > pipe_timeout:
try:
restart_pipe()
humidifier.update(volts)
controller.update(s, humidity)
if frame_num == 0:
# print(humidity, temp, volts)
update = {
"data": {
"time": int(now * 1000),
"temp": temp,
"hum": humidity,
"hv": volts,
"hv2": volts2,
}
}
send_update(update)
# print("sending update {}".format(update))
frame_num = (frame_num + 1) % DECIMATION_RATE
except Exception as e:
print("error restarting pipe: {}".format(repr(e)))
last_pipe_reboot = now
pipe_timeout *= 1.5
pipe_timeout = min(pipe_timeout, 5*60)
print("new pipe timeout ", pipe_timeout)
now = time.time()
if now - last_sample < SAMPLE_PERIOD:
time.sleep(SAMPLE_PERIOD - (now - last_sample) + 0.001)
continue
last_sample = now
# turn on the fan 1 minutes every 5 minutes
cur_min = int(now / 60)
fan_should_be_on = (cur_min % 5 == 0)
if fan_on != fan_should_be_on:
if fan_should_be_on:
s.write(b"Y")
else:
s.write(b"y")
#print("write s")
s.write(b"s")
s.flush()
resp = s.read(120)
#print("read", resp)
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])
volts2 = float(parts[3])
fan_on = int(volts2)
#print(parts)
try:
humidifier.update(volts)
controller.update(s, humidity)
if frame_num == 0:
#print(humidity, temp, volts)
update = {
"data": {
"time": int(now*1000),
"temp": temp,
"hum": humidity,
"hv": volts,
"hv2": volts2,
}
}
send_update(update)
#print("sending update {}".format(update))
frame_num = (frame_num + 1) % DECIMATION_RATE
except Exception as e:
print("pipe errored out, restarting: ", repr(e))
# restart the process I guess
restart_pipe()
print("pipe errored out, restarting: ", repr(e))
# restart the process I guess
restart_pipe()
finally:
# kill ssh connection
exiting = True
utils.process.kill()
stdout_thread.join()
# kill ssh connection
exiting = True
utils.process.kill()
stdout_thread.join()