MOSS: a small, mostly 3D-printed litter-picking rover. Cleaner streets, one maker at a time.
Python
litter probe: read robot.env first, like the launcher (same camera origin as the stack); bench 35
metrox3c25f79f5fb5
diff --git a/benches/bench_moss_litter_probe_cold.py b/benches/bench_moss_litter_probe_cold.pyindex efcc511..08f7801 100644--- a/benches/bench_moss_litter_probe_cold.py+++ b/benches/bench_moss_litter_probe_cold.py@@ -142,6 +142,30 @@ with tempfile.TemporaryDirectory(prefix="moss_litter_probe_") as td:r3 = subprocess.run([sys.executable, str(ROOT / "tools" / "moss_litter_probe.py"), "--fake", "--frames", "0", "--seconds", "0"],capture_output=True, text=True, timeout=60, env=env)check(r3.returncode == 2 and "nothing to do" in r3.stderr, "no frames and no seconds -> exit 2 with a reason")+ check("robot.env" in r.stdout and "absent" in r.stdout, "without a robot.env the tool says so", r.stdout[:300])++ print("E. robot.env, the stack's own geometry")+ check(lp.load_robot_env('# c\nexport MOSS_CAMERA_XYZ_M="0.026 -0.084 0.075"\nMOSS_CAMERA_PITCH_DEG=12\nbad line\n')+ == {"MOSS_CAMERA_XYZ_M": "0.026 -0.084 0.075", "MOSS_CAMERA_PITCH_DEG": "12"},+ "load_robot_env: export, quotes, comments and junk lines")+ e2 = {"MOSS_STATE_DIR": td, "MOSS_CAMERA_PITCH_DEG": "3"}+ (Path(td) / "robot.env").write_text('MOSS_CAMERA_XYZ_M="0.026 -0.084 0.075"\nMOSS_CAMERA_PITCH_DEG=0\n')+ path, taken = lp.apply_robot_env(e2)+ check(path == Path(td) / "robot.env" and taken == ["MOSS_CAMERA_XYZ_M"] and e2["MOSS_CAMERA_PITCH_DEG"] == "3",+ "apply_robot_env: takes what the shell does not set, the shell's value wins", (taken, e2))+ r4 = subprocess.run([sys.executable, str(ROOT / "tools" / "moss_litter_probe.py"), "--fake", "--frames", "2", "--seconds", "0",+ "--out", str(Path(td) / "p4.csv")], capture_output=True, text=True, timeout=120, env=env)+ rows4 = list(csv.DictReader((Path(td) / "p4.csv").open())) if (Path(td) / "p4.csv").is_file() else []+ check(r4.returncode == 0 and rows4 and near(float(rows4[0]["x_m"]), 1.026, 2e-3) and near(float(rows4[0]["y_m"]), -0.184, 2e-3)+ and "MOSS_CAMERA_XYZ_M" in r4.stdout,+ "the tool reads robot.env from MOSS_STATE_DIR: camera (0.026, -0.084, 0.075) -> x 1.026, y -0.184, and says it",+ rows4[:1] if rows4 else r4.stderr[-300:])+ r5 = subprocess.run([sys.executable, str(ROOT / "tools" / "moss_litter_probe.py"), "--fake", "--frames", "2", "--seconds", "0",+ "--out", str(Path(td) / "p5.csv"), "--camera-xyz", "0.156 0 0.075", "--pitch-deg", "0"],+ capture_output=True, text=True, timeout=120, env=env)+ rows5 = list(csv.DictReader((Path(td) / "p5.csv").open())) if (Path(td) / "p5.csv").is_file() else []+ check(r5.returncode == 0 and rows5 and near(float(rows5[0]["x_m"]), 1.156, 2e-3) and near(float(rows5[0]["y_m"]), -0.100, 2e-3),+ "--camera-xyz on the command line beats robot.env", rows5[:1] if rows5 else r5.stderr[-300:])print(f"{OK} OK, {KO} KO")print("TEST PASSED" if KO == 0 else "TEST FAILED")diff --git a/tools/moss_litter_probe.py b/tools/moss_litter_probe.pyindex 8c2cc49..6fcce38 100755--- a/tools/moss_litter_probe.py+++ b/tools/moss_litter_probe.py@@ -337,6 +337,44 @@ def run(camera, detector, wanted: set[str], camera_xyz, pitch_deg: float, out: Preturn s+def load_robot_env(text: str) -> dict[str, str]:+ """KEY=VALUE lines of a robot.env (optional `export `, # comments, quotes stripped). Pure."""+ 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 key:+ out[key] = val+ return out+++def apply_robot_env(env: dict | None = None) -> tuple[Path, list[str]]:+ """The launchers source <MOSS_STATE_DIR>/robot.env before the stack starts; this tool reads the+ same file so its camera geometry is the stack's (the flight check does the same). The shell's+ own values win. Returns the path and the keys taken from the file."""+ e = os.environ if env is None else env+ path = moss_state_dir(e) / "robot.env"+ try:+ text = path.read_text()+ except OSError:+ return path, []+ taken = []+ for key, val in load_robot_env(text).items():+ if key not in e:+ e[key] = val+ taken.append(key)+ return path, taken++def main(argv=None) -> int:ap = argparse.ArgumentParser(description="Measure the litter detector on the floor: hits and positions.")ap.add_argument("--fake", action="store_true", help="no camera, no torch: a synthetic frame and a fake detector")@@ -357,6 +395,12 @@ def main(argv=None) -> int:ap.add_argument("--out", default=None, help="CSV path")a = ap.parse_args(argv)+ env_path, taken = apply_robot_env()+ if taken:+ print(f"robot.env {env_path}: {', '.join(sorted(taken))}")+ else:+ print(f"robot.env {env_path}: {'nothing taken (the shell sets everything)' if env_path.is_file() else 'absent'}"+ " - the camera geometry is the profile's default unless MOSS_CAMERA_XYZ_M / --camera-xyz says otherwise")profile = moss_profile()camera_xyz = parse_xyz(a.camera_xyz) if a.camera_xyz else profile.camera_xyz_base_mpitch = profile.camera_pitch_deg if a.pitch_deg is None else a.pitch_deg