Compare commits

...

12 Commits

28 changed files with 5366 additions and 248 deletions

10
.gitignore vendored
View File

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

0
.gitmodules vendored Normal file
View File

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

@ -24,18 +24,121 @@ TwoWire twowire;
DFRobot_SHT20 sht20(&twowire);
#endif
void fanOn() {
digitalWrite(7, HIGH);
}
void fanOff() {
digitalWrite(7, LOW);
}
const int PIN_RELAY4 = 4;
const int PIN_RELAY3 = 5;
void fan(bool state) {
int last_state = digitalRead(PIN_RELAY3);
digitalWrite(PIN_RELAY3, state);
if (last_state != state) {
Serial.print(F("f:"));
Serial.println(state);
}
}
void humidifier(bool state) {
int last_state = digitalRead(PIN_RELAY4);
digitalWrite(PIN_RELAY4, state);
if (last_state != state) {
Serial.print(F("h:"));
Serial.println(state);
}
}
constexpr int sample_sz = 20;
struct {
int sample_time_millis = 250;
unsigned long last_sample_time = 0;
float humd = 0.0f, temp = 0.0f;
int volt1, volt2; // corresponds to humdifier and fan state respectively
int manual_mode_ts_millis = 0;
int manual_mode_timeout_millis = 5000; // how long to wait to time out from manual mode
bool manual_mode = false;
struct {
// simple ring buffer to allow
float humd[sample_sz];
int towrite = 0;
bool started = false;
void add(float h) {
if (!started) {
for (auto& val: humd) {
val = h;
}
started = true;
} else {
humd[towrite] = h;
}
towrite = (towrite + 1) % sample_sz;
}
float readLast(int n) {
if (n >= sample_sz) {
n = sample_sz - 1;
}
if (n < 0) {
n = 0;
}
int idx = towrite - 1 - n;
while (idx < 0) {
idx += sample_sz;
}
return humd[idx];
}
} samples;
struct {
float upper = 0.87f;
float lower = 0.83f;
} thresh;
int fan_on_secs = 10;
int fan_cycle_secs = 5*60;
void readSamples() {
last_sample_time = millis();
/*
#ifdef USE_SHT30
sht30.read();
humd = sht30.getHumidity();
temp = sht30.getTemperature();
#else
humd = sht20.readHumidity(); // Read Humidity
temp = sht20.readTemperature(); // Read Temperature
#endif
*/
volt1 = digitalRead(PIN_RELAY4);
volt2 = digitalRead(PIN_RELAY3);
samples.add(humd);
}
float feedforward_coeff = 50;
void controlHumidifier() {
// TODO maybe use linear regression instead of just the last point
const int prev_idx = (samples.towrite - 2 + sample_sz) % sample_sz;
const float cur_h = humd;
const float prev_h = samples.readLast(1);
const float slope = (cur_h - prev_h) * feedforward_coeff;
const float comp_h = cur_h + slope;
if (cur_h < thresh.lower) {
humidifier(true);
}
if (cur_h > thresh.upper) {
humidifier(false);
}
}
void controlFan() {
unsigned long time_secs = millis() / 1000;
if ((time_secs % fan_cycle_secs) < fan_on_secs) {
fan(true);
} else {
fan(false);
}
}
} cur;
void setup()
{
pinMode(PIN_RELAY4, OUTPUT);
@ -54,35 +157,363 @@ void setup()
#endif
delay(100);
//sht20.checkSHT20(); // Check SHT20 Sensor
cur.readSamples();
}
void printStatus() {
Serial.print(F("s:"));
Serial.print(cur.humd);
Serial.print(F(":"));
Serial.print(cur.temp);
Serial.print(F(":"));
Serial.print(cur.volt1);
Serial.print(F(":"));
Serial.print(cur.volt2);
Serial.println(F(""));
}
// this would be nice with AVR supported it..
struct Introspect {
public:
const char *name;
void* val;
enum Ty {
kInt,
kFloat,
kBool
};
Ty ty;
Introspect(): name(nullptr), val(nullptr), ty(Ty::kInt) {}
constexpr Introspect(const char* n, int& v): name(n), val(reinterpret_cast<void*>(&v)), ty(Ty::kInt) {}
constexpr Introspect(const char* n, float& v): name(n), val(reinterpret_cast<void*>(&v)), ty(Ty::kFloat) {}
constexpr Introspect(const char* n, bool& v): name(n), val(reinterpret_cast<void*>(&v)), ty(Ty::kBool) {}
void readVal() const {
switch (ty) {
case kInt: {
const int* v = val;
Serial.print(*v);
break;
}
case kFloat: {
const float* v = val;
Serial.print(*v);
break;
}
case kBool: {
const bool* v = val;
int val = *v;
Serial.print(val);
break;
}
}
}
bool writeVal(const char* buf, int len) {
switch (ty) {
case kInt: {
bool isnegative = false;
bool hasdigit = false;
int tmp = 0;
for (int i = 0; i < len; i++) {
if (i == 0 && buf[i] == '-') {
isnegative = true;
} else if (buf[i] >= '0' && buf[i] <= '9') {
tmp = 10*tmp + (buf[i] - '0');
hasdigit = true;
} else {
return false;
}
}
if (!hasdigit) {
return false;
}
if (isnegative) {
tmp = -tmp;
}
int* v = reinterpret_cast<int*>(val);
*v = tmp;
return true;
}
case kFloat: {
float tmp = 0.0f;
float factor = 0.1f;
int exponent = 0;
bool is_negative = false, has_digit = false;
bool using_exponent = false, has_exponent = false;
bool exp_is_negative = false;
enum State {
kPredecimal,
kPostdecimal, // after the decimal point
kExponent, // after the e
kExponentPostsign, // after the +/-
};
State state = kPredecimal;
for (int i = 0; i < len; i++) {
switch (state) {
case kPredecimal:
if (i == 0 && buf[i] == '-') {
is_negative = true;
} else if (buf[i] >= '0' && buf[i] <= '9') {
has_digit = true;
tmp = 10.0f * tmp + (buf[i] - '0');
} else if (buf[i] == '.') {
state = kPostdecimal;
} else if (buf[i] == 'e') {
state = kExponent;
using_exponent = true;
} else {
return false;
}
break;
case kPostdecimal:
if (buf[i] >= '0' && buf[i] <= '9') {
has_digit = true;
tmp = tmp + factor * (buf[i] - '0');
factor *= 0.1f;
} else if (buf[i] == 'e') {
state = kExponent;
using_exponent = true;
} else {
return false;
}
break;
case kExponent:
if (buf[i] == '+') {
state = kExponentPostsign;
} else if (buf[i] == '-') {
exp_is_negative = true;
state = kExponentPostsign;
} else if (buf[i] >= '0' && buf[i] <= '9') {
has_exponent = true;
exponent = (buf[i] - '0');
state = kExponentPostsign;
} else {
return false;
}
break;
case kExponentPostsign:
if (buf[i] >= '0' && buf[i] <= '9') {
has_exponent = true;
exponent = 10*exponent + (buf[i] - '0');
} else {
return false;
}
break;
}
}
if (!has_digit) return false;
if (using_exponent && !has_exponent) return false;
if (is_negative) {
tmp = -tmp;
}
if (has_exponent) {
if (exp_is_negative) {
for (int i = 0; i < exponent; i++) {
tmp *= 0.1f;
}
} else {
for (int i = 0; i < exponent; i++) {
tmp *= 10.f;
}
}
}
float* v = reinterpret_cast<float*>(val);
*v = tmp;
return true;
}
case kBool: {
if (len < 1) {
return false;
}
bool* v = reinterpret_cast<bool*>(val);
*v = (buf[0] != '0');
return true;
}
}
}
};
#define LIST_PROPS(x) \
x(sample_time_millis, cur.sample_time_millis) \
x(manual_mode_timeout_millis, cur.manual_mode_timeout_millis) \
x(manual_mode, cur.manual_mode) \
x(thresh_upper, cur.thresh.upper) \
x(thresh_lower, cur.thresh.lower) \
x(fan_on_secs, cur.fan_on_secs) \
x(fan_cycle_secs, cur.fan_cycle_secs) \
x(feedforward_coeff, cur.feedforward_coeff) \
#define DEFINE_STRS(n, var) const char n##_str[] PROGMEM = #n;
#define DEFINE_INTRO(n, var) {n##_str, var},
/*
const Introspect introspect_vals[] PROGMEM = {
{("cur_sample_time_millis"), cur.cur_sample_time_millis},
{("manual_mode_timeout_millis"), cur.manual_mode_timeout_millis},
{("manual_mode"), cur.manual_mode},
{("thresh.upper"), cur.thresh.upper},
{("thresh.lower"), cur.thresh.lower},
{("fan_on_secs"), cur.fan_on_secs},
{("fan_cycle_secs"), cur.fan_cycle_secs},
{("feedforward_coeff"), cur.feedforward_coeff},
};
*/
LIST_PROPS(DEFINE_STRS)
const Introspect introspect_vals[] PROGMEM = {
LIST_PROPS(DEFINE_INTRO)
};
bool match(const char* name, int len, Introspect& intro);
bool match(const char* name, int len, Introspect& intro) {
for (int i = 0; i < sizeof(introspect_vals)/sizeof(introspect_vals[0]); i++) {
memcpy_P((void*)&intro, (void*)&introspect_vals[i], sizeof(intro));
int intro_len = strlen_P(intro.name);
if (intro_len != len) {
continue;
}
if (strncmp_P(name, intro.name, len) == 0) {
return true;
}
}
return nullptr;
}
void dumpIntrospect() {
char buf[40];
Introspect intro;
for (int i = 0; i < sizeof(introspect_vals)/sizeof(introspect_vals[0]); i++) {
memcpy_P((void*)&intro, (void*)&introspect_vals[i], sizeof(intro));
Serial.print(F("d:"));
strncpy_P(buf, intro.name, sizeof(buf));
Serial.print(buf);
Serial.print(F(":"));
switch (intro.ty) {
case Introspect::kInt:
Serial.print(F("i"));
break;
case Introspect::kFloat:
Serial.print(F("f"));
break;
case Introspect::kBool:
Serial.print(F("b"));
break;
}
Serial.println(F(""));
}
Serial.println(F("d:done"));
return nullptr;
}
void loop()
{
while (Serial.available()) {
unsigned long now = 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;
cur.readSamples();
if (!cur.manual_mode) {
cur.controlHumidifier();
cur.controlFan();
}
printStatus();
}
if (Serial.available()) {
const int c = Serial.read();
if (c == 's') {
#ifdef USE_SHT30
sht30.read();
float humd = sht30.getHumidity();
float temp = sht30.getTemperature();
#else
float humd = sht20.readHumidity(); // Read Humidity
float temp = sht20.readTemperature(); // Read Temperature
#endif
Serial.print(humd);
Serial.print(",");
Serial.print(temp);
Serial.print(",");
Serial.print(digitalRead(PIN_RELAY4));
Serial.print(",");
Serial.print(digitalRead(PIN_RELAY3));
Serial.println("");
}
if (c == 'z') digitalWrite(PIN_RELAY4, LOW);
if (c == 'Z') digitalWrite(PIN_RELAY4, HIGH);
if (c == 'y') digitalWrite(PIN_RELAY3, LOW);
if (c == 'Y') digitalWrite(PIN_RELAY3, HIGH);
printStatus();
} else if (c == 'r') {
char buf[40];
int len = Serial.readBytesUntil('\n', buf, sizeof(buf) - 1);
buf[len] = 0;
if (len == 0) {
Serial.println(F("r:"));
Serial.print(buf+1);
Serial.println(F(":invalid name"));
return;
}
Introspect tmp;
if (!match(buf+1, len-1, tmp)) {
Serial.println(F("r:"));
Serial.print(buf+1);
Serial.print(",");
Serial.print(len);
Serial.println(F(":no match"));
return;
}
Serial.print(F("r:"));
Serial.print(buf+1);
Serial.print(F(":"));
tmp.readVal();
Serial.println(F(""));
} else if (c == 'w') {
char buf[40];
int len = Serial.readBytesUntil('\n', buf, sizeof(buf) - 1);
buf[len] = 0;
if (len == 0) {
Serial.println(F("w:no name"));
return;
}
int colon_idx = -1;
for (int i = 1; i < len; i++) {
if (buf[i] == ':') {
colon_idx = i;
break;
}
}
if (colon_idx == -1) {
Serial.println(F("w:invalid command"));
return;
}
buf[colon_idx] = 0;
Introspect tmp;
if (!match(buf+1, colon_idx-1, tmp)) {
Serial.println(F("w:no match"));
return;
}
if (!tmp.writeVal(buf + colon_idx + 1, len - colon_idx - 1)) {
Serial.println(F("w:invalid value"));
return;
}
Serial.print(F("w:"));
Serial.print(buf+1);
Serial.print(F(":"));
tmp.readVal();
Serial.println(F(""));
} 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();
}
delay(1);
}

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(())
}

3
shroom-controller/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.cache/
build/
managed_components/

View File

@ -0,0 +1,3 @@
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(shroom-controller)

View File

@ -0,0 +1,18 @@
dependencies:
idf:
source:
type: idf
version: 5.4.0
skuodi/libssh2_esp:
component_hash: a65c753c7388cf47299765dc8c8a22dccdc53d1e72a2fb0cf361c1f800067a63
dependencies: []
source:
registry_url: https://components.espressif.com/
type: service
version: 1.0.0
direct_dependencies:
- idf
- skuodi/libssh2_esp
manifest_hash: d8b4209272b4e81a14bbef159a9fa99da51e39fb3a9a5dd92295f22e4eb5cf79
target: esp32
version: 2.0.0

5
shroom-controller/main/.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
wifi_private.h
shrooms-key
shrooms-key.pub
shrooms-key.o
shrooms-key.pub.o

View File

@ -0,0 +1,20 @@
idf_component_register(
SRCS "main.c"
INCLUDE_DIRS "include"
REQUIRES
esp_driver_gpio
esp_wifi
nvs_flash
libssh2_esp
)
# TODO maybe add the commands to generate these?
# xtensa-esp-elf-objcopy -I binary -O elf32-xtensa-le shrooms-key shrooms-key.o
# xtensa-esp-elf-objcopy -I binary -O elf32-xtensa-le shrooms-key.pub shrooms-key.pub.o
target_link_libraries(
${COMPONENT_LIB}
${CMAKE_CURRENT_SOURCE_DIR}/shrooms-key.o
${CMAKE_CURRENT_SOURCE_DIR}/shrooms-key.pub.o
)

View File

@ -0,0 +1,9 @@
static void controller_job(void* args);
void controller_init(void) {
}
static void controller_job(void* args) {
}

View File

@ -0,0 +1,17 @@
## IDF Component Manager Manifest File
dependencies:
## Required IDF version
idf:
version: '>=4.1.0'
# # Put list of dependencies here
# # For components maintained by Espressif:
# component: "~1.0.0"
# # For 3rd party components:
# username/component: ">=1.0.0,<2.0.0"
# username2/component2:
# version: "~1.0.0"
# # For transient dependencies `public` flag can be set.
# # `public` flag doesn't have an effect dependencies of the `main` component.
# # All dependencies of `main` are public by default.
# public: true
skuodi/libssh2_esp: ^1.0.0

View File

@ -0,0 +1,288 @@
#include "esp_err.h"
#include "esp_event_base.h"
#include "esp_log.h"
#include "esp_netif_types.h"
#include "esp_wifi.h"
#include "esp_wifi_default.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include "libssh2.h"
#include "wifi_private.h"
const char TAG[] = "main";
// assigned to an esp timer to run after a set time
static void reconnect_job(void* arg) {
// TODO: if it's still disconnected try to reconnect
}
static void reconnect_in(int ticks_ms) {
}
EventGroupHandle_t s_wifi_event_group;
#define WIFI_FAIL_BIT (1)
#define WIFI_CONNECTED_BIT (2)
static int s_retry_num = 0;
static void event_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data) {
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
// TODO is this correct?
xEventGroupClearBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
if (s_retry_num < 5) {
esp_wifi_connect();
s_retry_num++;
ESP_LOGI(TAG, "retry to connect to the AP");
} else {
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
}
ESP_LOGI(TAG,"connect to the AP fail");
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
s_retry_num = 0;
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
}
}
void main_task(void* args) {
// connect via TCP here
struct addrinfo *results = 0;
int rc = libssh2_init(0);
if (rc) {
ESP_LOGE(TAG, "libssh2 initialization failed: %d", rc);
// TODO panic
}
int retry_time = 5000;
while (true) {
bool failed = true;
bool connect_success = false;
libssh2_socket_t sock = LIBSSH2_INVALID_SOCKET;
LIBSSH2_SESSION* session = 0;
LIBSSH2_CHANNEL* channel = 0;
xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT, 0, pdTRUE, portMAX_DELAY);
if (!(xEventGroupGetBits(s_wifi_event_group) & WIFI_CONNECTED_BIT)) {
continue;
}
struct addrinfo hints = {};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype= SOCK_STREAM;
ESP_LOGI(TAG, "looking up server...");
rc = getaddrinfo("batmanbatman.local", "22", &hints, &results);
if (rc) {
ESP_LOGE(TAG, "getaddrinfo failed: %d", rc);
goto cleanup;
}
if (!results) {
ESP_LOGE(TAG, "getaddrinfo returned no results");
goto cleanup;
}
for (struct addrinfo* rp = results; rp; rp = rp->ai_next) {
ESP_LOGI(TAG, "creating socket fam %d type %d proto %d", rp->ai_family, rp->ai_socktype, rp->ai_protocol);
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sock == LIBSSH2_INVALID_SOCKET) {
ESP_LOGE(TAG, "failed to create socket");
goto cleanup;
}
if (connect(sock, results->ai_addr, results->ai_addrlen) != -1) {
ESP_LOGE(TAG, "connected successfully");
connect_success = true;
break;
}
close(sock);
sock = LIBSSH2_INVALID_SOCKET;
}
freeaddrinfo(results);
if (!connect_success) {
goto cleanup;
}
ESP_LOGI(TAG, "connection established, creating SSH session...");
session = libssh2_session_init();
if (!session) {
ESP_LOGE(TAG, "could not create libssh2 session");
goto cleanup;
}
//libssh2_session_set_read_timeout(session, 20);
libssh2_trace(session, -1);
libssh2_session_handshake(session, sock);
const char* fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_SHA1);
const char username[] = "shrooms";
extern char _binary_shrooms_key_start[];
extern char _binary_shrooms_key_end[];
size_t shrooms_key_size = _binary_shrooms_key_end - _binary_shrooms_key_start;
extern char _binary_shrooms_key_pub_start[];
extern char _binary_shrooms_key_pub_end[];
size_t shrooms_key_pub_size = _binary_shrooms_key_pub_end - _binary_shrooms_key_pub_start;
ESP_LOGI(TAG, "pub key %p %p %d key %p %p %d",
_binary_shrooms_key_pub_start,
_binary_shrooms_key_pub_end,
shrooms_key_pub_size,
_binary_shrooms_key_start,
_binary_shrooms_key_end,
shrooms_key_size
);
rc = libssh2_userauth_publickey_frommemory(
session,
username,
sizeof(username) - 1,
_binary_shrooms_key_pub_start,
shrooms_key_pub_size,
_binary_shrooms_key_start,
shrooms_key_size,
NULL);
if (rc) {
ESP_LOGE(TAG, "could not authenticate, err %d", rc);
goto cleanup;
}
ESP_LOGE(TAG, "authenticated, opening channel...");
channel = libssh2_channel_open_session(session);
if (!channel) {
ESP_LOGE(TAG, "unable to open channel");
goto cleanup;
}
rc = libssh2_channel_request_pty(channel, "vanilla");
if (rc) {
ESP_LOGE(TAG, "unable to request pty %d", rc);
goto cleanup;
}
ESP_LOGE(TAG, "executing command...");
rc = libssh2_channel_exec(channel, "./runtest");
if (rc) {
ESP_LOGE(TAG, "could not open channel");
goto cleanup;
}
libssh2_session_set_timeout(session, 100);
ESP_LOGE(TAG, "waiting for results...");
while (!libssh2_channel_eof(channel)) {
ESP_LOGE(TAG, "waiting for read loop");
char tmp[256];
ssize_t rlen = libssh2_channel_read(channel, tmp, sizeof(tmp) - 1);
if (rlen < 0) {
ESP_LOGE(TAG, "received err %d", rlen);
continue;
}
tmp[rlen] = 0;
ESP_LOGI(TAG, "received %s", tmp);
}
failed = false;
ESP_LOGI(TAG, "ssh exiting");
//rc = libssh2_channel_get_get_exit_status(channel);
cleanup:
if (libssh2_channel_close(channel)) {
ESP_LOGE(TAG, "could not close channel");
}
if (channel) {
libssh2_channel_free(channel);
}
channel = 0;
if (session) {
libssh2_session_disconnect(session, "normal shutdown");
libssh2_session_free(session);
}
if (sock != LIBSSH2_INVALID_SOCKET) {
shutdown(sock, 2);
LIBSSH2_SOCKET_CLOSE(sock);
}
if (failed) {
retry_time *= 2;
} else {
retry_time = 5000;
}
if (retry_time > 10*60*1000) {
retry_time = 10*60*1000;
}
ESP_LOGI(TAG, "retrying in %d ms...", retry_time);
vTaskDelay(pdMS_TO_TICKS(retry_time));
}
while (true);
}
void app_main(void) {
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
s_wifi_event_group = xEventGroupCreate();
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_create_default_wifi_sta();
esp_event_handler_instance_t instance_any_id;
esp_event_handler_instance_t instance_got_ip;
ESP_ERROR_CHECK(esp_event_handler_instance_register(
WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, &instance_any_id));
ESP_ERROR_CHECK(esp_event_handler_instance_register(
IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, &instance_got_ip));
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
wifi_config_t wifi_config = {
.sta = {
.ssid = WIFI_SSID,
.password = WIFI_PASS,
.threshold.authmode = WIFI_AUTH_WPA_WPA2_PSK,
},
};
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
if (xTaskCreate(main_task, "ssh task", 4096, NULL, 17, NULL) != pdPASS) {
ESP_LOGE(TAG, "unable to create ssh task");
// TODO panic
}
}

2091
shroom-controller/sdkconfig Normal file

File diff suppressed because it is too large Load Diff

428
shroom-server/Cargo.lock generated Normal file
View File

@ -0,0 +1,428 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "anyhow"
version = "1.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04"
[[package]]
name = "bitflags"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36"
[[package]]
name = "bytes"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f61dac84819c6588b558454b194026eb1f09c293b9036ae9b159e74e73ab6cf9"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "crc"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69e6e4d7b33a94f0991c26729976b10ebde1d34c3ee82408fb536164fa10d636"
dependencies = [
"crc-catalog",
]
[[package]]
name = "crc-catalog"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
[[package]]
name = "either"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "errno"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "fixedbitset"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
[[package]]
name = "getrandom"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8"
dependencies = [
"cfg-if",
"libc",
"wasi",
"windows-targets",
]
[[package]]
name = "hashbrown"
version = "0.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "indexmap"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "itertools"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
dependencies = [
"either",
]
[[package]]
name = "libc"
version = "0.2.169"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
[[package]]
name = "log"
version = "0.4.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04cbf5b083de1c7e0222a7a51dbfdba1cbe1c6ab0b15e29fff3f6c077fd9cd9f"
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "multimap"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03"
[[package]]
name = "once_cell"
version = "1.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e"
[[package]]
name = "petgraph"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772"
dependencies = [
"fixedbitset",
"indexmap",
]
[[package]]
name = "prettyplease"
version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6924ced06e1f7dfe3fa48d57b9f74f55d8915f5036121bef647ef4b204895fac"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
dependencies = [
"unicode-ident",
]
[[package]]
name = "prost"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-build"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf"
dependencies = [
"heck",
"itertools",
"log",
"multimap",
"once_cell",
"petgraph",
"prettyplease",
"prost",
"prost-types",
"regex",
"syn",
"tempfile",
]
[[package]]
name = "prost-derive"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
dependencies = [
"anyhow",
"itertools",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "prost-types"
version = "0.13.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16"
dependencies = [
"prost",
]
[[package]]
name = "quote"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
name = "rustix"
version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "shroom-server"
version = "0.1.0"
dependencies = [
"crc",
"prost",
"prost-build",
"tempfile",
]
[[package]]
name = "syn"
version = "2.0.98"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38c246215d7d24f48ae091a2902398798e05d978b24315d6efbc00ede9a8bb91"
dependencies = [
"cfg-if",
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]]
name = "unicode-ident"
version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034"
[[package]]
name = "wasi"
version = "0.13.3+wasi-0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2"
dependencies = [
"wit-bindgen-rt",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[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.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[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.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[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.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "wit-bindgen-rt"
version = "0.33.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c"
dependencies = [
"bitflags",
]

16
shroom-server/Cargo.toml Normal file
View File

@ -0,0 +1,16 @@
[package]
name = "shroom-server"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
crc = "3.2.1"
prost = "0.13.5"
[build-dependencies]
prost-build = "0.13.5"
[dev-dependencies]
tempfile = "3.16.0"

7
shroom-server/build.rs Normal file
View File

@ -0,0 +1,7 @@
use std::io::Result;
fn main() -> Result<()> {
println!("cargo:rerun-if-changed=entry.proto");
prost_build::compile_protos(&["entry.proto"], &["."])?;
Ok(())
}

11
shroom-server/entry.proto Normal file
View File

@ -0,0 +1,11 @@
syntax = "proto2";
package internalstore;
message Entry {
optional uint64 timestamp = 1;
repeated float humidity = 2;
optional float temp = 3;
repeated bool humidifer = 4;
optional bool fan = 5;
}

View File

@ -0,0 +1,235 @@
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use crate::proto::Entry;
use crate::store::Store;
pub type Error = std::io::Error;
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(not(test))]
const MAX_ENTRIES: usize = 4096;
#[cfg(test)]
const MAX_ENTRIES: usize = 2;
// manages a directory of append-only logs
// the most recent log is kept open for easy access, the rest are opened as needed
// to access old data
// a new log is started once the current log is larger than a given size
pub struct Datalog {
cur_store: Store<File>,
path: PathBuf,
prefix: String,
}
fn walk_dir<P: AsRef<Path>>(path: P, prefix: &str) -> Result<Vec<PathBuf>> {
let mut dir_path = path.as_ref().to_path_buf();
dir_path.push(".");
//println!("reading dir {:?}", &dir_path);
let contents = std::fs::read_dir(dir_path)?;
let mut entries: Vec<PathBuf> = contents
.into_iter()
.filter_map(|dir_entry| dir_entry.ok().map(|de| de.path()))
.filter(|path| {
path.as_path()
.file_name()
.and_then(|filen| filen.to_str())
.map(|filen| filen.starts_with(prefix))
.unwrap_or(false)
})
.collect();
entries.sort_by_key(|path| {
path.file_stem()
.and_then(|stem| stem.to_str())
.and_then(|stem| stem[prefix.len()..].parse::<u64>().ok())
.unwrap_or(0)
});
Ok(entries)
}
fn in_range(start: u64, end: Option<u64>, start2: Option<u64>, end2: Option<u64>) -> bool {
match (start2, end2) {
(Some(s2), Some(e2)) => {
if e2 < start {
return false;
}
if let Some(e) = end {
if e < s2 {
return false;
}
}
return true;
}
_ => false,
}
}
fn new_path<P: AsRef<Path>>(dir: P, file_prefix: &str) -> PathBuf {
let timestamp = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();
let mut path = dir.as_ref().to_path_buf();
path.push(&format!("{file_prefix}{timestamp}.shrooms"));
path
}
impl Datalog {
pub fn new<P: AsRef<Path>>(dirpath: P, file_prefix: &str) -> Result<Datalog> {
let files = walk_dir(&dirpath, file_prefix)?;
let cur_store_path = files
.last()
.map(|path| path.clone())
.unwrap_or_else(|| new_path(&dirpath, file_prefix));
println!("opening most recent store {:?}", &cur_store_path);
let cur_store = Store::open(cur_store_path)?;
Ok(Datalog {
cur_store,
path: dirpath.as_ref().to_path_buf(),
prefix: file_prefix.to_string(),
})
}
pub fn lookup_range(&self, start: u64, end: Option<u64>) -> Result<Vec<Entry>> {
let only_most_recent = self.cur_store.start().map(|ts| ts < start).unwrap_or(false);
if only_most_recent {
let result = self.cur_store.lookup_range(start, end);
return Ok(result);
}
let mut relevant_stores = Vec::new();
//println!("walking dir {:?}", &self.path);
let mut entries = walk_dir(&self.path, &self.prefix)?;
//println!("found logs {:?}", &entries);
entries.reverse();
for e in entries {
let store = Store::open_read_only(e).ok();
if let Some(s) = store {
if in_range(start, end, s.start(), s.end()) {
relevant_stores.push(s);
}
}
}
// reverse to return it to chronological order
relevant_stores.reverse();
let mut ret = Vec::new();
for s in relevant_stores {
ret.extend(s.lookup_range(start, end));
}
Ok(ret)
}
pub fn add(&mut self, e: &Entry) -> Result<()> {
self.cur_store.append(e)?;
if self.cur_store.num_entries() >= MAX_ENTRIES {
self.cur_store = Store::open(new_path(&self.path, &self.prefix))?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{Datalog, Entry};
#[test]
fn test_write1() {
let temp_dir = tempfile::TempDir::new().unwrap();
let mut datalog = Datalog::new(temp_dir.path(), "test").unwrap();
let entry = Entry {
timestamp: Some(7),
humidity: vec![0.95],
temp: Some(32.2),
fan: Some(false),
humidifer: vec![false],
};
datalog.add(&entry).unwrap();
let entries = datalog.lookup_range(0, None).unwrap();
assert_eq!(entries, vec![entry.clone()]);
}
#[test]
fn overflow() {
let temp_dir = tempfile::TempDir::new().unwrap();
let mut datalog = Datalog::new(temp_dir.path(), "test").unwrap();
let entry = Entry {
timestamp: Some(7),
humidity: vec![0.95],
temp: Some(32.2),
fan: Some(false),
humidifer: vec![false],
};
let entry2 = Entry {
timestamp: Some(16),
humidity: vec![0.92],
temp: Some(31.2),
fan: Some(true),
humidifer: vec![false],
};
let entry3 = Entry {
timestamp: Some(17),
humidity: vec![0.95],
temp: Some(31.4),
fan: Some(false),
humidifer: vec![true],
};
let entry4 = Entry {
timestamp: Some(31),
humidity: vec![0.95],
temp: Some(31.4),
fan: Some(false),
humidifer: vec![true],
};
let entry5 = Entry {
timestamp: Some(47),
humidity: vec![0.95],
temp: Some(31.4),
fan: Some(false),
humidifer: vec![true],
};
let entry6 = Entry {
timestamp: Some(97),
humidity: vec![0.95],
temp: Some(31.4),
fan: Some(false),
humidifer: vec![true],
};
datalog.add(&entry).unwrap();
datalog.add(&entry2).unwrap();
datalog.add(&entry3).unwrap();
datalog.add(&entry4).unwrap();
datalog.add(&entry5).unwrap();
datalog.add(&entry6).unwrap();
let entries = datalog.lookup_range(4, Some(8)).unwrap();
assert_eq!(entries, vec![entry.clone()]);
let entries = datalog.lookup_range(4, Some(16)).unwrap();
assert_eq!(entries, vec![entry.clone(), entry2.clone()]);
let entries = datalog.lookup_range(8, Some(16)).unwrap();
assert_eq!(entries, vec![entry2.clone()]);
let entries = datalog.lookup_range(4, Some(17)).unwrap();
assert_eq!(entries, vec![entry.clone(), entry2.clone(), entry3.clone()]);
let entries = datalog.lookup_range(8, None).unwrap();
assert_eq!(
entries,
vec![
entry2.clone(),
entry3.clone(),
entry4.clone(),
entry5.clone(),
entry6.clone()
]
);
}
}

0
shroom-server/src/io.rs Normal file
View File

View File

@ -0,0 +1,9 @@
mod proto {
include!(concat!(env!("OUT_DIR"), "/internalstore.rs"));
}
mod datalog;
mod store;
fn main() {
println!("Hello, world!");
}

425
shroom-server/src/store.rs Normal file
View File

@ -0,0 +1,425 @@
use std::fs::{File, OpenOptions};
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::path::Path;
use prost::Message;
pub use crate::proto::Entry;
pub type Error = std::io::Error;
pub type Result<T> = std::result::Result<T, Error>;
const X25: crc::Crc<u16> = crc::Crc::<u16>::new(&crc::CRC_16_IBM_SDLC);
// data is stored in append-only logs
// each data entry starts with a checksum (CRC16),
// followed by a one-byte length, and the
// actual entry encoded in protocol buffer
// upon opening a file, all the entries within it are
// read, any corrupted contents at the end truncated/overwritten
pub struct Store<T> {
contents: T,
entries: Vec<Entry>,
start_ts: Option<u64>,
end_ts: Option<u64>,
}
impl<T> Store<T> {
pub fn num_entries(&self) -> usize {
self.entries.len()
}
pub fn data(&self) -> Vec<Entry> {
self.entries.clone()
}
pub fn start(&self) -> Option<u64> {
self.start_ts
}
pub fn end(&self) -> Option<u64> {
self.end_ts
}
}
impl Store<Cursor<Vec<u8>>> {
pub fn open_read_only<P: AsRef<Path>>(p: P) -> Result<Store<Cursor<Vec<u8>>>> {
let data = std::fs::read(p)?;
Ok(Store::new(Cursor::new(data)))
}
}
impl Store<File> {
pub fn open<P: AsRef<Path>>(p: P) -> Result<Store<File>> {
let mut f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(p)?;
let _ = f.seek(SeekFrom::Start(0))?;
Ok(Store::new(f))
}
}
impl<T: Read + Seek> Store<T> {
pub fn new(mut t: T) -> Store<T> {
let mut entries = Vec::new();
let mut start_ts = None;
let mut end_ts = None;
// start of the next unread entry
let mut cur_pos = 0;
let mut data: Vec<u8> = Vec::new();
loop {
let mut crc16 = [0u8; 2];
let mut len = [0u8; 1];
if let Err(_) = t.read_exact(&mut crc16) {
break;
}
if let Err(_) = t.read_exact(&mut len) {
break;
}
data.resize(len[0] as usize, 0);
if let Err(_) = t.read_exact(&mut data) {
break;
}
// CRC check data
let calculated = X25.checksum(&data);
let crc = (crc16[0] as u16) | ((crc16[1] as u16) << 8);
if calculated != crc {
break;
}
// decode data into an entry
if let Ok(entry) = Entry::decode(&data[..]) {
cur_pos = t.stream_position().unwrap();
if start_ts.is_none() {
start_ts = entry.timestamp.clone();
}
if entry.timestamp.is_some() {
end_ts = entry.timestamp.clone();
}
entries.push(entry);
} else {
break;
}
}
let _ = t.seek(SeekFrom::Start(cur_pos)).unwrap();
Store {
contents: t,
entries,
start_ts,
end_ts,
}
}
pub fn lookup_range(&self, start: u64, end: Option<u64>) -> Vec<Entry> {
if let Some(start_ts) = self.start_ts {
if let Some(end_range) = end {
if end_range < start_ts {
return Vec::new();
}
}
}
if let Some(end_ts) = self.end_ts {
if start > end_ts {
return Vec::new();
}
}
let mut ret = Vec::new();
for e in &self.entries {
if let Some(ts) = e.timestamp {
if ts >= start {
if let Some(end_range) = end {
if ts > end_range {
continue;
}
}
ret.push(e.clone());
}
}
}
ret
}
}
impl<T: Write> Store<T> {
pub fn append(&mut self, e: &Entry) -> Result<()> {
let payload = e.encode_to_vec();
let len = payload.len();
let len_u8: [u8; 1] = if len < 256 {
[len as u8]
} else {
return Err(Error::new(std::io::ErrorKind::Other, "payload too large"));
};
// CRC check data
let calculated = X25.checksum(&payload);
let crc: [u8; 2] = [(calculated & 0xff) as u8, ((calculated >> 8) & 0xff) as u8];
self.contents.write(&crc)?;
self.contents.write(&len_u8)?;
self.contents.write(&payload)?;
self.entries.push(e.clone());
if self.start_ts.is_none() {
self.start_ts = e.timestamp;
}
if let Some(ts) = e.timestamp {
self.end_ts = Some(ts);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{Entry, Store};
#[test]
fn append_read() {
let temp_file = tempfile::NamedTempFile::new().unwrap();
let entry = Entry {
timestamp: Some(7),
humidity: vec![0.95],
temp: Some(32.2),
fan: Some(false),
humidifer: vec![false],
};
{
let mut store = Store::open(temp_file.path()).unwrap();
store.append(&entry).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone()]);
}
{
let store = Store::open_read_only(temp_file.path()).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone()]);
}
}
#[test]
fn append2_read2() {
let temp_file = tempfile::NamedTempFile::new().unwrap();
let entry = Entry {
timestamp: Some(7),
humidity: vec![0.95],
temp: Some(32.2),
fan: Some(false),
humidifer: vec![false],
};
let entry2 = Entry {
timestamp: Some(16),
humidity: vec![0.92],
temp: Some(31.2),
fan: Some(true),
humidifer: vec![false],
};
{
let mut store = Store::open(temp_file.path()).unwrap();
store.append(&entry).unwrap();
store.append(&entry2).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone(), entry2.clone()]);
}
{
let store = Store::open_read_only(temp_file.path()).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone(), entry2.clone()]);
}
}
#[test]
fn append2_read2_interrupted() {
let temp_file = tempfile::NamedTempFile::new().unwrap();
let entry = Entry {
timestamp: Some(7),
humidity: vec![0.95],
temp: Some(32.2),
fan: Some(false),
humidifer: vec![false],
};
let entry2 = Entry {
timestamp: Some(16),
humidity: vec![0.92],
temp: Some(31.2),
fan: Some(true),
humidifer: vec![false],
};
{
let mut store = Store::open(temp_file.path()).unwrap();
store.append(&entry).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone()]);
}
{
let mut store = Store::open(temp_file.path()).unwrap();
store.append(&entry2).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone(), entry2.clone()]);
}
{
let store = Store::open_read_only(temp_file.path()).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone(), entry2.clone()]);
}
}
#[test]
fn append2_read2_with_corruption() {
let temp_file = tempfile::NamedTempFile::new().unwrap();
let entry = Entry {
timestamp: Some(7),
humidity: vec![0.95],
temp: Some(32.2),
fan: Some(false),
humidifer: vec![false],
};
let entry2 = Entry {
timestamp: Some(16),
humidity: vec![0.92],
temp: Some(31.2),
fan: Some(true),
humidifer: vec![false],
};
let entry3 = Entry {
timestamp: Some(17),
humidity: vec![0.95],
temp: Some(31.4),
fan: Some(false),
humidifer: vec![true],
};
{
use std::io::Write;
let mut store = Store::open(temp_file.path()).unwrap();
store.append(&entry).unwrap();
store.append(&entry2).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone(), entry2.clone()]);
store.contents.write(&[45, 34, 44]).unwrap();
store.append(&entry3).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone(), entry2.clone(), entry3.clone()]);
}
{
let store = Store::open_read_only(temp_file.path()).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone(), entry2.clone()]);
}
}
#[test]
fn append2_with_corruption_write() {
let temp_file = tempfile::NamedTempFile::new().unwrap();
let entry = Entry {
timestamp: Some(7),
humidity: vec![0.95],
temp: Some(32.2),
fan: Some(false),
humidifer: vec![false],
};
let entry2 = Entry {
timestamp: Some(16),
humidity: vec![0.92],
temp: Some(31.2),
fan: Some(true),
humidifer: vec![false],
};
let entry3 = Entry {
timestamp: Some(17),
humidity: vec![0.95],
temp: Some(31.4),
fan: Some(false),
humidifer: vec![true],
};
{
use std::io::Write;
let mut store = Store::open(temp_file.path()).unwrap();
store.append(&entry).unwrap();
store.append(&entry2).unwrap();
store.contents.write(&[45, 34, 44]).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone(), entry2.clone()]);
}
{
let mut store = Store::open(temp_file.path()).unwrap();
store.append(&entry3).unwrap();
}
{
let store = Store::open_read_only(temp_file.path()).unwrap();
let entries = store.lookup_range(0, None);
assert_eq!(entries, vec![entry.clone(), entry2.clone(), entry3.clone()]);
}
}
#[test]
fn read_different_ranges() {
let temp_file = tempfile::NamedTempFile::new().unwrap();
let entry = Entry {
timestamp: Some(7),
humidity: vec![0.95],
temp: Some(32.2),
fan: Some(false),
humidifer: vec![false],
};
let entry2 = Entry {
timestamp: Some(16),
humidity: vec![0.92],
temp: Some(31.2),
fan: Some(true),
humidifer: vec![false],
};
let entry3 = Entry {
timestamp: Some(17),
humidity: vec![0.95],
temp: Some(31.4),
fan: Some(false),
humidifer: vec![true],
};
let mut store = Store::open(temp_file.path()).unwrap();
store.append(&entry).unwrap();
store.append(&entry2).unwrap();
store.append(&entry3).unwrap();
let entries = store.lookup_range(4, Some(8));
assert_eq!(entries, vec![entry.clone()]);
let entries = store.lookup_range(4, Some(16));
assert_eq!(entries, vec![entry.clone(), entry2.clone()]);
let entries = store.lookup_range(8, Some(16));
assert_eq!(entries, vec![entry2.clone()]);
let entries = store.lookup_range(4, Some(17));
assert_eq!(entries, vec![entry.clone(), entry2.clone(), entry3.clone()]);
let entries = store.lookup_range(8, None);
assert_eq!(entries, vec![entry2.clone(), entry3.clone()]);
}
}

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()

133
test_float_parse.cc Normal file
View File

@ -0,0 +1,133 @@
#include <optional>
#include <iostream>
bool parseFloat(const char* buf, int len, float* v) {
float tmp = 0.0f;
float factor = 0.1f;
int exponent = 0;
bool is_negative = false, has_digit = false;
bool using_exponent = false, has_exponent = false;
bool exp_is_negative = false;
enum State {
kPredecimal,
kPostdecimal, // after the decimal point
kExponent, // after the e
kExponentPostsign, // after the +/-
};
State state = kPredecimal;
for (int i = 0; i < len; i++) {
switch (state) {
case kPredecimal:
if (i == 0 && buf[i] == '-') {
is_negative = true;
} else if (buf[i] >= '0' && buf[i] <= '9') {
has_digit = true;
tmp = 10.0f * tmp + (buf[i] - '0');
} else if (buf[i] == '.') {
state = kPostdecimal;
} else if (buf[i] == 'e') {
state = kExponent;
using_exponent = true;
} else {
return false;
}
break;
case kPostdecimal:
if (buf[i] >= '0' && buf[i] <= '9') {
has_digit = true;
tmp = tmp + factor * (buf[i] - '0');
factor *= 0.1f;
} else if (buf[i] == 'e') {
state = kExponent;
using_exponent = true;
} else {
return false;
}
break;
case kExponent:
if (buf[i] == '+') {
state = kExponentPostsign;
} else if (buf[i] == '-') {
exp_is_negative = true;
state = kExponentPostsign;
} else if (buf[i] >= '0' && buf[i] <= '9') {
has_exponent = true;
exponent = (buf[i] - '0');
state = kExponentPostsign;
} else {
return false;
}
break;
case kExponentPostsign:
if (buf[i] >= '0' && buf[i] <= '9') {
has_exponent = true;
exponent = 10*exponent + (buf[i] - '0');
} else {
return false;
}
break;
}
}
if (!has_digit) return false;
if (using_exponent && !has_exponent) return false;
if (is_negative) {
tmp = -tmp;
}
if (has_exponent) {
if (exp_is_negative) {
for (int i = 0; i < exponent; i++) {
tmp *= 0.1f;
}
} else {
for (int i = 0; i < exponent; i++) {
tmp *= 10.f;
}
}
}
*v = tmp;
return true;
}
std::optional<float> parseWrapper(const char* buf, int len) {
float tmp;
if (parseFloat(buf, len, &tmp)) {
return tmp;
} else {
return std::nullopt;
}
}
#define ASSERT_VALID_MATCHES(s) \
do { \
auto tmp = parseWrapper(#s, sizeof(#s) - 1); \
if (!tmp) { \
std::cout << "failed to parse " << s << std::endl; \
return -1; \
} \
float err = (*tmp - s) / (s + 1e-12); \
if (err < 0) err = -err; \
if (err > 1e-6) { \
std::cout << "error out of range for " << #s << " err = " << err << ", parsed = " << *tmp << ", expected = " << s << std::endl; \
} \
} while (0)
int main() {
ASSERT_VALID_MATCHES(1.);
ASSERT_VALID_MATCHES(0.1);
ASSERT_VALID_MATCHES(-0.1);
ASSERT_VALID_MATCHES(-0.1e3);
ASSERT_VALID_MATCHES(-0.1e-3);
ASSERT_VALID_MATCHES(1.2e-3);
ASSERT_VALID_MATCHES(.2e-3);
ASSERT_VALID_MATCHES(-.3e-4);
ASSERT_VALID_MATCHES(-.3e4);
ASSERT_VALID_MATCHES(-.0003342);
ASSERT_VALID_MATCHES(-.0073342e12);
ASSERT_VALID_MATCHES(3.141592);
return 0;
}