From da9476d052dea16369b898bb6decd7286e642fb5 Mon Sep 17 00:00:00 2001 From: beniroquai Date: Thu, 2 Jul 2026 22:09:32 +0200 Subject: [PATCH] Add set_mode to GPIO and fix checkFirmware error Add `set_mode()` to GPIO for switching between auto/manual collision detection modes (persisted in NVS). Also wrap the firmware check loop body in a try/except to prevent crashes on decode errors. --- uc2rest/gpio.py | 20 ++++++++++++++++++-- uc2rest/mserial.py | 13 ++++++++----- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/uc2rest/gpio.py b/uc2rest/gpio.py index 864f721..2ff27e6 100644 --- a/uc2rest/gpio.py +++ b/uc2rest/gpio.py @@ -150,6 +150,22 @@ def set_reference(self, reference, node=None, timeout=1): def calibrate(self, node=None, timeout=1): """Tell the slave to take its CURRENT rolling mean as the new - reference (persisted in NVS). Do this while the system is idle and - collision-free.""" + reference (persisted in NVS). MANUAL mode only — in AUTO the baseline + tracks itself. Do this while the system is idle and collision-free.""" return self._act(node=node, timeout=timeout, calibrate=1) + + def set_mode(self, mode, node=None, timeout=1): + """Select the detection mode (persisted on the slave in NVS). + + mode: "auto" (default, recommended) — adaptive baseline + robust + sigma z-score. Parameter-free: tracks a slowly drifting + background and trips on a fast deflection. No calibration. + mode: "manual" — fixed reference +/- threshold. Deterministic; + requires the reference to be calibrated to the idle level. + + Accepts "auto"/"manual" or 0/1.""" + if isinstance(mode, str): + mval = 1 if mode.lower() == "manual" else 0 + else: + mval = 1 if int(mode) else 0 + return self._act(node=node, timeout=timeout, mode=mval) diff --git a/uc2rest/mserial.py b/uc2rest/mserial.py index 5c9d2c0..f6706b6 100644 --- a/uc2rest/mserial.py +++ b/uc2rest/mserial.py @@ -364,11 +364,14 @@ def checkFirmware(self, ser): for i in range(500): # if we just want to send but not even wait for a response mReadline = self._read(ser) - if self.DEBUG and mReadline != "" and mReadline != "\n" and mReadline != b'' and mReadline != b'\n': - self._logger.debug("[checkFirmware]: "+str(mReadline)) - if mReadline.decode('utf-8').strip() == "++" or mReadline.decode('utf-8').strip().find("++")>=0: - self._freeSerialBuffer(ser) - return True + try: + if self.DEBUG and mReadline != "" and mReadline != "\n" and mReadline != b'' and mReadline != b'\n': + self._logger.debug("[checkFirmware]: "+str(mReadline)) + if mReadline.decode('utf-8').strip() == "++" or mReadline.decode('utf-8').strip().find("++")>=0: + self._freeSerialBuffer(ser) + return True + except Exception as e: + self._logger.error("Error in checkFirmware: "+str(e)) return False def _generate_identifier(self):