MOSS: a small, mostly 3D-printed litter-picking rover. Cleaner streets, one maker at a time.
Python
flight check and launchers: robot.env declares the driver and the pad layout; the check refuses a firmware built for another driver, a mute pad, a pad in another layout; the teleop launcher says YOU CAN DRIVE only after the stack trusts the pad
metrox760e3a3488e6
diff --git a/benches/bench_moss_preflight_cold.py b/benches/bench_moss_preflight_cold.pyindex 934b253..4aa1845 100644--- a/benches/bench_moss_preflight_cold.py+++ b/benches/bench_moss_preflight_cold.py@@ -115,6 +115,9 @@ class FakeSerial:def default_world():return {"files": {QTPY, C1, WRIST, "/dev/input/js0"},+ "pad_names": {"/dev/input/js0": "shanwan Android GamePad"},+ "pad_axes": {"/dev/input/js0": [0, 0, 0, 0, 0, 0, 0, 0]}, # alive at rest+ "robot_env": None, # text of <state>/robot.env, None = absent"runs": [], # (run_id, pid)"alive": set(),"cmdlines": [(1, "/sbin/init")],@@ -146,7 +149,8 @@ def default_world():ENV_KEYS = ("MOSS_PORT", "MOSS_LIDAR_PORT", "MOSS_MOCK_BUS", "MOSS_RS_SERIAL", "MOSS_CAMERA",- "MOSS_WRIST", "MOSS_REQUIRE_PAD", "MOSS_STATE_DIR")+ "MOSS_WRIST", "MOSS_REQUIRE_PAD", "MOSS_STATE_DIR",+ "MOSS_DRIVER", "MOSS_PAD_LAYOUT", "MOSS_PAD_INDEX") # robot.env setdefaults these: cleared per casedef run(argv=(), **over):@@ -165,6 +169,9 @@ def run(argv=(), **over):mp._ls = lambda pat: sorted(f for f in w["files"] if fnmatch.fnmatch(f, pat))mp._exists = lambda p: p in w["files"]+ mp._pad_name = lambda js: w["pad_names"].get(js, "?")+ mp._pad_init_axes = lambda js, listen_s=1.0: w["pad_axes"].get(js)+ mp._read_text = lambda path: (w["robot_env"] if str(path).endswith("robot.env") else None)mp._runs_dir = lambda: runs_dirmp._pid_alive = lambda pid: pid in w["alive"]mp._proc_cmdlines = lambda: list(w["cmdlines"])@@ -261,7 +268,7 @@ check("firmware version read from telemetry", "qtpy-mdd3a-v3" in line_of(out, "fcheck("firmware disarmed: mode 0", "mode 0 (off)" in line_of(out, "firmware disarmed"))check("ticks L 160585 R 158263", "L 160585 R 158263" in line_of(out, "encoder ticks"))check("driver absent -> informational OK with the build note",- line_of(out, "motor driver") == "OK motor driver - not reported (a firmware build older than the driver key)",+ line_of(out, "motor driver") == "OK motor driver - not reported (a firmware build older than the driver key); set MOSS_DRIVER in robot.env to make this a check",line_of(out, "motor driver"))check("telemetry parsed across chunk boundaries (3 lines, banner ignored)","3 line(s)" in line_of(out, "firmware telemetry"), line_of(out, "firmware telemetry"))@@ -288,7 +295,7 @@ check("the stack's moss_dimos comes from this checkout",line_of(out, "moss-dimos install"))check("the state dir and recordings/ were created", (w["state"] / "recordings").is_dir())check("sections in the spec order",- [r["section"].split(" ")[0] for r in res][:1] == ["stack"]+ [r["section"].split(" ")[0] for r in res][:2] == ["robot.env", "stack"]and [out.find("\n" + h + "\n") for h in HEADERS] == sorted(out.find("\n" + h + "\n") for h in HEADERS)and -1 not in [out.find("\n" + h + "\n") for h in HEADERS])rc, out, res, w = run(lo_flags=0x1009)@@ -362,7 +369,7 @@ check("057e:2009 -> the Nintendo sentence, as a warning (nothing refuses a missiand "WARN" in line_of(out, "gamepad"),line_of(out, "gamepad"))rc, out, res, w = run(files=files_nopad, usb={"2563:0526"})-check("2563:0526 -> receiver visible, no js0", "receiver visible (2563:0526), no js0: replug or reboot" in line_of(out, "gamepad"))+check("2563:0526 -> receiver visible, no js device", "receiver visible (2563:0526), no js device: replug or reboot" in line_of(out, "gamepad"))rc, out, res, w = run(files=files_nopad, usb=set())check("nothing -> no pad, still a warning", "no pad" in line_of(out, "gamepad") and line_of(out, "gamepad").startswith("OK"))rc, out, res, w = run(files=files_nopad, usb=set(), env={"MOSS_REQUIRE_PAD": "1"})@@ -370,6 +377,53 @@ check("MOSS_REQUIRE_PAD=1 -> no pad is a KO and the check fails", line_of(out, "rc, out, res, w = run(usb={"057e:2009"})check("js0 present wins over any USB id", line_of(out, "gamepad").startswith("OK"))+# E2. the pad must be ALIVE and in the layout the stack will use (14 Oct: a mute dongle passed as OK;+# the pad on its cable is an Xbox 360 pad with another button map)+rc, out, res, w = run(files={QTPY, C1, "/dev/input/js0"}, pad_axes={"/dev/input/js0": [-32767] * 8})+check("every axis at -32767 (never reported) -> KO MUTE with the cause",+ line_of(out, "gamepad").startswith("KO") and "MUTE" in line_of(out, "gamepad") and "not paired" in line_of(out, "gamepad"),+ line_of(out, "gamepad"))+rc, out, res, w = run(files={QTPY, C1, "/dev/input/js1"}, pad_names={"/dev/input/js1": "Microsoft X-Box 360 pad"},+ pad_axes={"/dev/input/js1": [0, 0, -32767, 0, 0, -32767, 0, 0]})+check("Xbox pad (cable) with the default android layout -> KO, fix = MOSS_PAD_LAYOUT=xinput",+ line_of(out, "gamepad").startswith("KO") and "MOSS_PAD_LAYOUT=xinput" in line_of(out, "gamepad"), line_of(out, "gamepad"))+rc, out, res, w = run(files={QTPY, C1, "/dev/input/js1"}, pad_names={"/dev/input/js1": "Microsoft X-Box 360 pad"},+ pad_axes={"/dev/input/js1": [0, 0, -32767, 0, 0, -32767, 0, 0]}, env={"MOSS_PAD_LAYOUT": "xinput"})+check("Xbox pad with MOSS_PAD_LAYOUT=xinput -> OK, alive, layout xinput",+ line_of(out, "gamepad").startswith("OK") and "layout xinput" in line_of(out, "gamepad"), line_of(out, "gamepad"))+rc, out, res, w = run(files={QTPY, C1, "/dev/input/js0"}, env={"MOSS_PAD_LAYOUT": "xinput"})+check("dongle (shanwan) with MOSS_PAD_LAYOUT=xinput -> KO, fix = android",+ line_of(out, "gamepad").startswith("KO") and "MOSS_PAD_LAYOUT=android" in line_of(out, "gamepad"), line_of(out, "gamepad"))+rc, out, res, w = run(files={QTPY, C1, "/dev/input/js0", "/dev/input/js1"},+ pad_names={"/dev/input/js0": "shanwan Android GamePad", "/dev/input/js1": "Microsoft X-Box 360 pad"},+ pad_axes={"/dev/input/js0": [-32767] * 8, "/dev/input/js1": [0, 0, -32767, 0, 0, -32767, 0, 0]},+ env={"MOSS_PAD_LAYOUT": "xinput", "MOSS_PAD_INDEX": "1"})+check("two pads, MOSS_PAD_INDEX=1 -> the Xbox one is judged (OK), the mute dongle only listed",+ line_of(out, "gamepad").startswith("OK") and "js1:" in line_of(out, "gamepad") and "also plugged: js0" in line_of(out, "gamepad"),+ line_of(out, "gamepad"))+check("pad_verdict: cannot read -> KO", mp.pad_verdict("x", None, "android")[0] is False)++# E3. robot.env: read before the checks, the shell wins, the driver is checked against it+rc, out, res, w = run(robot_env="# MOSS robot\nMOSS_DRIVER=mdd10a\nexport MOSS_PAD_LAYOUT=\"xinput\"\n",+ files={QTPY, C1, "/dev/input/js1"}, pad_names={"/dev/input/js1": "Microsoft X-Box 360 pad"},+ pad_axes={"/dev/input/js1": [0, 0, -32767, 0, 0, -32767, 0, 0]})+check("robot.env line lists what it declared", "MOSS_DRIVER=mdd10a" in line_of(out, "robot.env") and "MOSS_PAD_LAYOUT=xinput" in line_of(out, "robot.env"),+ line_of(out, "robot.env"))+check("MOSS_PAD_LAYOUT from robot.env reaches the pad check (xinput -> OK)", line_of(out, "gamepad").startswith("OK"), line_of(out, "gamepad"))+check("firmware without a driver key, robot.env expects mdd10a -> KO with the reflash line",+ line_of(out, "motor driver").startswith("KO") and "reflash the mdd10a build" in line_of(out, "motor driver"), line_of(out, "motor driver"))+rc, out, res, w = run(robot_env="MOSS_DRIVER=mdd10a\n", telemetry=dict(TELEMETRY, driver="mdd10a"))+check("firmware driver = MOSS_DRIVER -> OK", line_of(out, "motor driver").startswith("OK") and "= MOSS_DRIVER" in line_of(out, "motor driver"), line_of(out, "motor driver"))+rc, out, res, w = run(robot_env="MOSS_DRIVER=mdd10a\n", telemetry=dict(TELEMETRY, driver="mdd3a"))+check("firmware mdd3a, robot.env mdd10a -> KO naming both", line_of(out, "motor driver").startswith("KO") and "built for mdd3a" in line_of(out, "motor driver"), line_of(out, "motor driver"))+rc, out, res, w = run(robot_env="MOSS_DRIVER=mdd3a\n", env={"MOSS_DRIVER": "mdd10a"}, telemetry=dict(TELEMETRY, driver="mdd10a"))+check("the shell's MOSS_DRIVER wins over robot.env", line_of(out, "motor driver").startswith("OK"), line_of(out, "motor driver"))+rc, out, res, w = run()+check("no robot.env, no driver key -> informative OK that says how to make it a check",+ line_of(out, "motor driver").startswith("OK") and "set MOSS_DRIVER in robot.env" in line_of(out, "motor driver"), line_of(out, "motor driver"))+check("load_robot_env: comments, export, quotes, junk", mp.load_robot_env("# c\nexport A=\"1 2\"\nB='x'\nnot a pair\nlower=3\nC=\n") == {"A": "1 2", "B": "x", "C": ""})+check("driver_verdict pure: expected set and nothing reported -> KO", mp.driver_verdict("mdd10a", None) == (False, "not reported, robot.env expects mdd10a: reflash the mdd10a build (bench/README.md)"))+print("F. --json")rc, out, res, w = run(["--json"], telemetry=dict(TELEMETRY, bus_mV=10500))try:@@ -415,7 +469,7 @@ rc, out, res, w = run(serial_chunks=[b"", b"garbage\n"])check("mute firmware -> KO, no further firmware verdict",line_of(out, "firmware telemetry").startswith("KO") and "mute" in out and not find(res, "battery"))rc, out, res, w = run(telemetry=dict(TELEMETRY, driver="mdd10a"))-check("driver reported -> shown", line_of(out, "motor driver") == "OK motor driver - mdd10a")+check("driver reported -> shown (informative without MOSS_DRIVER)", line_of(out, "motor driver").startswith("OK motor driver - mdd10a; set MOSS_DRIVER"))rc, out, res, w = run(realsense=[dict(D455, usb="2.1")])check("RealSense on USB 2.1 -> KO 5 fps max", "on USB 2: 5 fps max" in line_of(out, "RealSense D455")and line_of(out, "RealSense D455").startswith("KO"))diff --git a/docs/base.md b/docs/base.mdindex 17a09c7..ab6f311 100644--- a/docs/base.md+++ b/docs/base.md@@ -89,6 +89,23 @@ The coordinator publishes the firmware telemetry on `/base_telemetry` every`ticks`, `target_pct`, `output_pct`, `ramp_ms`, `firmware_age_s`, `mock`), sonothing else ever has to open the serial port.+## robot.env: what this robot is, declared once++`~/.local/state/moss/robot.env` (or `$MOSS_STATE_DIR/robot.env`), `KEY=VALUE` lines. The launchers+(`tools/moss-fly.sh`, `tools/moss-teleop.sh`) read it before anything else, the flight check reads the+same file, so a verdict there is a verdict on what will actually run. The shell's own exports win.++```+MOSS_DRIVER=mdd10a # the motor driver on the board: the flight check refuses a firmware built for another one+MOSS_PAD_LAYOUT=xinput # android = the pad on its 2.4 GHz dongle; xinput = the same pad on its USB cable (an Xbox 360 pad to the kernel)+MOSS_MIN_PCT=20 # measured floor: both tracks turn from 20 %+```++The flight check then refuses, in red, what used to pass as "OK": a firmware that does not match+`MOSS_DRIVER`, a pad the receiver has never heard (every axis at its never-reported value), a pad+plugged in a layout other than the declared one. And `tools/moss-teleop.sh` prints "YOU CAN DRIVE"+only once the stack itself has written that it saw the sticks at neutral and trusts the commands.+## Calibrate before trusting a numberThe firmware is open loop (PWM percent). Three numbers turn a twist intodiff --git a/tools/moss-fly.sh b/tools/moss-fly.shindex 8a52e02..bfefbfb 100755--- a/tools/moss-fly.sh+++ b/tools/moss-fly.sh@@ -23,6 +23,17 @@# 300 ms after the last command whatever happens up here.set -ucd "$(dirname "$0")/.." || exit 1+# robot.env: what THIS robot is (MOSS_DRIVER, MOSS_PAD_LAYOUT, measured numbers), next to the+# recordings; the flight check reads the same file, so its verdicts match what runs here.+# The shell's own exports win over the file.+ROBOT_ENV="${MOSS_STATE_DIR:-$HOME/.local/state/moss}/robot.env"+if [ -f "$ROBOT_ENV" ]; then+ while IFS= read -r _l || [ -n "$_l" ]; do+ _l="${_l#export }"; case "$_l" in ''|'#'*) continue;; esac+ _k="${_l%%=*}"; _v="${_l#*=}"; _v="${_v%\"}"; _v="${_v#\"}"+ case "$_k" in [A-Z]*) [ -z "${!_k:-}" ] && export "$_k=$_v";; esac+ done < "$ROBOT_ENV"+fiDIMOS=.venv/bin/dimosPY=.venv/bin/pythonBYID_DIR=/dev/serial/by-iddiff --git a/tools/moss-teleop.sh b/tools/moss-teleop.shindex b06b96f..920bee4 100755--- a/tools/moss-teleop.sh+++ b/tools/moss-teleop.sh@@ -18,6 +18,17 @@# stay up with the pad on the table.set -ucd "$(dirname "$0")/.." || exit 1+# robot.env: what THIS robot is (MOSS_DRIVER, MOSS_PAD_LAYOUT, measured numbers), next to the+# recordings; the flight check reads the same file, so its verdicts match what runs here.+# The shell's own exports win over the file.+ROBOT_ENV="${MOSS_STATE_DIR:-$HOME/.local/state/moss}/robot.env"+if [ -f "$ROBOT_ENV" ]; then+ while IFS= read -r _l || [ -n "$_l" ]; do+ _l="${_l#export }"; case "$_l" in ''|'#'*) continue;; esac+ _k="${_l%%=*}"; _v="${_l#*=}"; _v="${_v%\"}"; _v="${_v#\"}"+ case "$_k" in [A-Z]*) [ -z "${!_k:-}" ] && export "$_k=$_v";; esac+ done < "$ROBOT_ENV"+fiDIMOS=.venv/bin/dimosPY=.venv/bin/pythonLAUNCH_LOG=/tmp/moss_teleop_launch.log@@ -107,23 +118,28 @@ if [ "${MOCK:-0}" = "1" ]; then export MOSS_MOCK_BUS=1; else export MOSS_PORT="$export MOSS_MAX_PCT="${MOSS_MAX_PCT:-100}" # firmware limit 100; lower it here for a cautious lapexport MOSS_RAMP_MS="${MOSS_RAMP_MS:-5 5}" # firmware ramp, ms per % up/down (the pad slew still takes 0.75 s to full)nohup $DIMOS --rerun-open none run moss-dimos.moss-gamepad --daemon > "$LAUNCH_LOG" 2>&1 < /dev/null &-OK_BASE=0; OK_PAD=0+# "YOU CAN DRIVE" is a commitment: the base connected, the pad connected AND seen at neutral by the+# stack itself ("commands now trusted"). A mute pad (dongle without its pad) connects but is never+# trusted: that is a refusal here, not a banner.+OK_BASE=0; OK_PAD=0; OK_TRUST=0for i in $(seq 1 40); dosleep 1- L=$($DIMOS log 2>/dev/null | grep -a "MOSS base: connected\|MOSS base: MOCK BUS\|Gamepad connected\|MOSS base: cannot open\|MOSS base: no telemetry\|Traceback")+ L=$($DIMOS log 2>/dev/null | grep -a "MOSS base: connected\|MOSS base: MOCK BUS\|Gamepad connected\|commands now trusted\|MOSS base: cannot open\|MOSS base: no telemetry\|Traceback")echo "$L" | grep -q "MOSS base: connected\|MOSS base: MOCK BUS" && OK_BASE=1echo "$L" | grep -q "Gamepad connected" && OK_PAD=1+ echo "$L" | grep -q "commands now trusted" && OK_TRUST=1echo "$L" | grep -q "cannot open\|no telemetry\|Traceback" && break- [ $OK_BASE = 1 ] && [ $OK_PAD = 1 ] && break+ [ $OK_BASE = 1 ] && [ $OK_PAD = 1 ] && [ $OK_TRUST = 1 ] && breakdone$DIMOS log 2>/dev/null | grep -a "MOSS\|[Gg]amepad\|Traceback\|Error" | tail -8-if [ $OK_BASE != 1 ] || [ $OK_PAD != 1 ]; then- echo "STACK NOT READY (base=$OK_BASE pad=$OK_PAD) - see above and $LAUNCH_LOG; stopping"+if [ $OK_BASE != 1 ] || [ $OK_PAD != 1 ] || [ $OK_TRUST != 1 ]; then+ echo "STACK NOT READY (base=$OK_BASE pad=$OK_PAD trusted=$OK_TRUST) - see above and $LAUNCH_LOG; stopping"+ [ $OK_PAD = 1 ] && [ $OK_TRUST != 1 ] && echo " the pad connected but the stack never saw its sticks at neutral: a MUTE pad (dongle without its pad, or off), or the wrong MOSS_PAD_LAYOUT (cable = xinput, dongle = android) in robot.env"tail -5 "$LAUNCH_LOG"; $DIMOS stop >/dev/null 2>&1; exit 1fi-echo "== 5/5 YOU CAN DRIVE =="-echo " deadman = R1 (right shoulder, SDL button 7) held the whole time"+echo "== 5/5 YOU CAN DRIVE (base connected, pad seen at neutral by the stack, layout ${MOSS_PAD_LAYOUT:-android}) =="+echo " deadman = R1 (right shoulder) held the whole time"echo " left stick up/down = forward/back right stick left/right = turn R2 = boost (capped at ${MOSS_MAX_PCT} %)"echo " release R1 = 0.5 s of zeros then silence; the firmware stops 300 ms after the last drive"echo " stop: tools/moss-teleop.sh stop watch: tools/moss-teleop.sh log"diff --git a/tools/moss_preflight.py b/tools/moss_preflight.pyindex deef8a0..5b372e6 100755--- a/tools/moss_preflight.py+++ b/tools/moss_preflight.py@@ -126,6 +126,53 @@ def _exists(path: str) -> bool:return os.path.exists(path)+def _read_text(path) -> str | None:+ try:+ return Path(path).read_text(encoding="utf-8")+ except OSError:+ return None+++def _pad_name(js: str) -> str:+ try:+ return Path(f"/sys/class/input/{os.path.basename(js)}/device/name").read_text(encoding="utf-8").strip()+ except OSError:+ return os.path.basename(js)+++def _pad_init_axes(js: str, listen_s: float = 1.0) -> list[int] | None:+ """The joystick API's initial axis values (events flagged 0x80 on open): a pad the receiver has+ never heard reports every axis at -32767; a live pad at rest reports its sticks at 0."""+ import select+ import struct++ fmt, size = "IhBB", struct.calcsize("IhBB")+ try:+ fd = os.open(js, os.O_RDONLY | os.O_NONBLOCK)+ except OSError:+ return None+ axes: dict[int, int] = {}+ try:+ deadline = time.monotonic() + listen_s+ while time.monotonic() < deadline:+ r, _, _ = select.select([fd], [], [], 0.1)+ if not r:+ if axes:+ break+ continue+ try:+ data = os.read(fd, size * 64)+ except OSError:+ break+ for i in range(0, len(data) - size + 1, size):+ _, value, typ, num = struct.unpack(fmt, data[i:i + size])+ if typ & 0x80 and typ & 0x02:+ axes[num] = value+ finally:+ os.close(fd)+ return [axes[k] for k in sorted(axes)]++def _runs_dir() -> Path:"""dimOS's run registry, where dimOS, tools/moss-fly.sh and the cockpitlook for it (XDG_STATE_HOME when set and not empty)."""@@ -364,6 +411,78 @@ def _state_dir() -> Path:return robot_profile.moss_state_dir()+# ── robot.env: what the robot IS (driver, pad layout, measured numbers) ──────────────────────+ROBOT_ENV_NAME = "robot.env"+++def load_robot_env(text: str) -> dict[str, str]:+ """KEY=VALUE lines (optional `export `, # comments, quotes stripped). Pure: tests/benches."""+ out: dict[str, str] = {}+ for raw in text.splitlines():+ line = raw.strip()+ if not line or line.startswith("#"):+ continue+ if line.startswith("export "):+ line = line[7:].strip()+ if "=" not in line:+ continue+ key, val = line.split("=", 1)+ key, val = key.strip(), val.strip()+ if len(val) >= 2 and val[0] == val[-1] and val[0] in "\"'":+ val = val[1:-1]+ if re.fullmatch(r"[A-Z][A-Z0-9_]*", key):+ out[key] = val+ return out+++def apply_robot_env(env: dict | None = None) -> tuple[Path, dict[str, str]]:+ """The launchers source <MOSS_STATE_DIR>/robot.env; the flight check reads the same file so its+ verdicts match what the stack will run with. The shell's own values win (setdefault)."""+ e = os.environ if env is None else env+ path = _state_dir() / ROBOT_ENV_NAME+ text = _read_text(path)+ pairs = load_robot_env(text) if text is not None else {}+ for key, val in pairs.items():+ e.setdefault(key, val)+ return path, pairs+++def driver_verdict(expected: str, reported) -> tuple[bool, str]:+ """MOSS_DRIVER (robot.env) against the firmware's `driver` key. Pure.+ No expectation: informative. Expectation and a different (or missing) driver: a KO with the fix."""+ exp = (expected or "").strip().lower()+ rep = (str(reported).strip().lower() if reported else "")+ if not exp:+ return True, (rep or "not reported (a firmware build older than the driver key)") + \+ "; set MOSS_DRIVER in robot.env to make this a check"+ if rep == exp:+ return True, f"{rep} = MOSS_DRIVER"+ if not rep:+ return False, f"not reported, robot.env expects {exp}: reflash the {exp} build (bench/README.md)"+ return False, f"firmware built for {rep}, robot.env expects {exp}: reflash the {exp} build (bench/README.md)"+++PAD_MUTE_AXIS = -32767 # the kernel's initial value for an axis the pad never reported+++def pad_verdict(name: str, init_axes, layout: str) -> tuple[bool, str]:+ """One pad as SDL will take it: alive at neutral, in the layout the stack will use. Pure.+ init_axes: the joystick API's initial axis values (None = could not read)."""+ lay = (layout or "android").strip().lower() or "android"+ n = (name or "").lower()+ if init_axes is None:+ return False, f"{name}: cannot read it (permissions? held exclusively?)"+ if init_axes and all(int(v) == PAD_MUTE_AXIS for v in init_axes):+ return False, (f"{name}: MUTE - every axis at its never-reported value: the receiver sees no pad "+ "(pad off, or not paired with this dongle); the stack will never see it at neutral")+ xbox = ("x-box" in n or "xbox" in n or "x box" in n)+ if xbox and lay != "xinput":+ return False, f"{name}: an Xbox 360 pad to the kernel (the pad on its cable), MOSS_PAD_LAYOUT is {lay}: set MOSS_PAD_LAYOUT=xinput in robot.env"+ if "shanwan" in n and lay == "xinput":+ return False, f"{name}: the dongle in Android mode, MOSS_PAD_LAYOUT is xinput: set MOSS_PAD_LAYOUT=android in robot.env"+ return True, f"{name} alive, layout {lay} (deadman = R1)"++# ── helpers ────────────────────────────────────────────────────────────────def _env_on(name: str, default: bool) -> bool:"""A MOSS_* switch, parsed by the stack's own parser."""@@ -540,8 +659,8 @@ def check_firmware(ctx: dict, quick: bool) -> None:mode = last.get("mode")verdict(mode == 0, "firmware disarmed","mode 0 (off)" if mode == 0 else f"mode {mode} ({last.get('reason')}) - something else is driving it")- drv = last.get("driver")- verdict(True, "motor driver", str(drv) if drv else "not reported (a firmware build older than the driver key)")+ ok, detail = driver_verdict(_raw("MOSS_DRIVER"), last.get("driver"))+ verdict(ok, "motor driver", detail)_battery(last)ticks = last.get("ticks")good = isinstance(ticks, list) and len(ticks) == 2 and all(isinstance(x, int) for x in ticks)@@ -626,25 +745,26 @@ def check_wrist(ctx: dict) -> None:def check_gamepad(ctx: dict) -> None:section("gamepad")- pads = sorted(glob.glob("/dev/input/js*")) # any number: the pad on its cable keeps js1 after the dongle's js0+ pads = _ls("/dev/input/js*") # any number: the pad on its cable keeps js1 after the dongle's js0if pads:- names = []- for j in pads:- try:- with open(f"/sys/class/input/{os.path.basename(j)}/device/name", encoding="utf-8") as f:- names.append(f"{os.path.basename(j)}={f.read().strip()}")- except OSError:- names.append(os.path.basename(j))- verdict(True, "gamepad", ", ".join(names) + " (dongle mute: button under the pad, then move a stick; cable = Xbox 360 pad: MOSS_PAD_LAYOUT=xinput)")+ try:+ index = max(0, int(_raw("MOSS_PAD_INDEX") or "0"))+ except ValueError:+ index = 0+ js = pads[index] if index < len(pads) else pads[0]+ name = _pad_name(js)+ ok, detail = pad_verdict(name, _pad_init_axes(js), _raw("MOSS_PAD_LAYOUT"))+ others = [f"{os.path.basename(j)}={_pad_name(j)}" for j in pads if j != js]+ verdict(ok, "gamepad", f"{os.path.basename(js)}: {detail}" + (f"; also plugged: {', '.join(others)}" if others else ""))returnusb = _usb_devices()if PAD_SHANWAN in usb:- why = f"receiver visible ({PAD_SHANWAN}), no js0: replug or reboot"+ why = f"receiver visible ({PAD_SHANWAN}), no js device: replug or reboot"elif PAD_SWITCH_PRO in usb:why = (f"pad enumerated as a Nintendo Pro Controller ({PAD_SWITCH_PRO}) without a driver: ""switch the pad to its Android/X-input mode and replug")else:- why = "no pad (no js0, no known receiver on USB)"+ why = "no pad (no js device, no known receiver on USB)"# A missing pad stops nothing from running: the map builds, the cockpit shows, exploration# can be armed; only hand driving is lost. MOSS_REQUIRE_PAD=1 turns this into a refusal.required = _env_on("MOSS_REQUIRE_PAD", False)@@ -779,6 +899,10 @@ def _save(path: str, doc: dict) -> None:def run(quick: bool = False, no_spin: bool = False) -> None:ctx: dict = {}+ section("robot.env (what the robot is: driver, pad layout, measured numbers)")+ env_path, pairs = apply_robot_env()+ verdict(True, "robot.env", (f"{env_path}: " + ", ".join(f"{k}={v}" for k, v in pairs.items())) if pairs+ else f"{env_path} absent: nothing declared (MOSS_DRIVER, MOSS_PAD_LAYOUT...) - the checks stay informative")check_stack(ctx)check_ports(ctx)check_firmware(ctx, quick)