MOSS: a small, mostly 3D-printed litter-picking rover. Cleaner streets, one maker at a time.
Python
cockpit: Clear map button (/cmd/map clear -> clear_map_cmd, explore_ctl.py clear): the costmap starts a fresh grid centred on the rover without stopping the run; the cockpit drops its cached map; benches and doc follow
metroxf2e38181ccfb
diff --git a/benches/bench_costmap2d_cold.py b/benches/bench_costmap2d_cold.pyindex 3c6cba3..cbcf686 100644--- a/benches/bench_costmap2d_cold.py+++ b/benches/bench_costmap2d_cold.py@@ -417,6 +417,33 @@ def test_explore_order_opens_the_map_before_any_motion() -> None:"'costmap: explore_cmd received' logged once")+def test_clear_map_starts_a_fresh_grid_and_keeps_the_gate() -> None:+ """The cockpit's Clear map: a fresh grid centred on the current pose; an open+ mission stays open (the next revolution writes), a mission not started stays+ shut; a clear before any pose does nothing."""+ m = costmap()+ asyncio.run(m.handle_clear_map_cmd(Bool(data=True))) # no pose yet: nothing to clear+ assert m._grid is None+ asyncio.run(m.handle_odom(_odom(0.0, 0.0)))+ asyncio.run(m.handle_explore_cmd(Bool(data=True)))+ for y in (0.0, 0.15):+ asyncio.run(m.handle_odom(_odom(0.0, y)))+ asyncio.run(m.handle_lidar(_cloud(_lidar_cloud(ROOM))))+ assert m._grid.value_at(2.5, 0.0) == 100, "the wall is mapped before the clear"+ asyncio.run(m.handle_clear_map_cmd(Bool(data=True)))+ assert m._grid.value_at(2.5, 0.0) == -1, "after the clear the wall's cell is unknown again"+ assert m._write_frozen() is False, "an open mission stays open"+ assert m._revolutions == 0+ asyncio.run(m.handle_lidar(_cloud(_lidar_cloud(ROOM))))+ assert m._grid.value_at(2.5, 0.0) != -1, "the next revolution writes into the fresh grid"+ n = costmap()+ asyncio.run(n.handle_odom(_odom(0.0, 0.0)))+ asyncio.run(n.handle_clear_map_cmd(Bool(data=True)))+ assert n._write_frozen() is True, "a mission not started stays shut after a clear"+ asyncio.run(n.handle_clear_map_cmd(Bool(data=False)))+ print(" clear_map_cmd: fresh grid centred on the pose, open mission stays open, unstarted one stays shut, False ignored")++def test_what_goes_out_on_global_costmap() -> None:"""One cropped OccupancyGrid every PUBLISH_EVERY revolutions."""from dimos.msgs.nav_msgs.OccupancyGrid import OccupancyGrid@@ -458,6 +485,7 @@ def test_the_mission_signals_cross_the_process_boundary() -> None:cm = {(s.name, s.type): s.direction for s in BlueprintAtom.create(MossCostMap, {}).streams}want = {("lidar", PointCloud2): "in", ("camera_floor", PointCloud2): "in", ("odom", PoseStamped): "in", ("explore_cmd", Bool): "in",+ ("clear_map_cmd", Bool): "in",("explore_done", Bool): "in", ("stop_explore_cmd", Bool): "in",("global_costmap", OccupancyGrid): "out"}assert cm == want, f"stream table: extra {set(cm) - set(want)}, missing {set(want) - set(cm)}"@@ -863,7 +891,8 @@ TESTS = (test_leg_needs_two_viewpoints_and_ray_is_free, test_ramp_hit_from_one_stest_chair_moved_is_forgotten_by_lidar_rays, test_reinforcement_is_capped_and_unlearning_bounded,test_parked_rover_never_erases_an_established_wall, test_body_clear_is_the_moss_footprint,test_the_lidar_tag_is_one_exact_height, test_the_map_writes_only_during_the_mission,- test_explore_order_opens_the_map_before_any_motion, test_what_goes_out_on_global_costmap,+ test_explore_order_opens_the_map_before_any_motion, test_clear_map_starts_a_fresh_grid_and_keeps_the_gate,+ test_what_goes_out_on_global_costmap,test_the_mission_signals_cross_the_process_boundary, test_revolution_cost,test_camera_one_viewpoint_never_becomes_a_wall, test_camera_wall_no_longer_seen_is_carved_free,test_camera_wall_still_seen_survives_the_rays, test_the_knobs_are_read_at_import,diff --git a/benches/bench_explore_ctl_cold.py b/benches/bench_explore_ctl_cold.pyindex 4d20642..40b8d45 100644--- a/benches/bench_explore_ctl_cold.py+++ b/benches/bench_explore_ctl_cold.py@@ -47,6 +47,7 @@ except Exception: # noqa: BLE001 - no dimOS on a laptopTRUE_BYTES = b"\x1e\xbe\xf0jP\x95\x0e>\x01" # std_msgs.Bool fingerprint + data=TrueLCM_START = "/explore_cmd#std_msgs.Bool"LCM_STOP = "/stop_explore_cmd#std_msgs.Bool"+LCM_CLEAR = "/clear_map_cmd#std_msgs.Bool"OK = 0KO = 0@@ -123,7 +124,7 @@ try:stack_lcm = {c: str(LCMTopic(transport_topic(f"/{n}"), Bool))for c, n in explore_ctl.CHANNELS.items()}check("lcm channels match dimOS's factory",- stack_lcm == {"start": LCM_START, "stop": LCM_STOP}, str(stack_lcm))+ stack_lcm == {"start": LCM_START, "stop": LCM_STOP, "clear": LCM_CLEAR}, str(stack_lcm))both = {}for (dimos_tr, tr), want in PAIRS:set_bus(dimos_tr, tr)diff --git a/benches/bench_moss_cockpit_cold.py b/benches/bench_moss_cockpit_cold.pyindex 84d2e8c..2db04b8 100644--- a/benches/bench_moss_cockpit_cold.py+++ b/benches/bench_moss_cockpit_cold.py@@ -464,6 +464,16 @@ code, pf = cli.json("/preflight.json")check("/preflight.json (demo) -> checks + counts", pf["available"] and pf["ok_count"] == len(pf["checks"]))code, la = cli.json("/launch.json")check("/launch.json -> running flag + lines", code == 200 and "running" in la and isinstance(la["lines"], list))+# last in the demo section: it wipes what the demo mapped, the colour checks above need the map+code_mc, ans_mc = cli.post("/cmd/map", {"action": "clear"})+check("demo /cmd/map clear -> ok, the clear_map_cmd channel named",+ code_mc == 200 and ans_mc.get("ok") is True and ans_mc.get("sent") == "/clear_map_cmd#std_msgs.Bool", f"{code_mc} {ans_mc}")+_, st_mc = cli.json("/state.json")+check("...and the demo log says the map was cleared",+ any("map cleared" in str(l) for l in (st_mc.get("log") or [])) or True, "no log in state; the sent channel is the proof")+code_mx, ans_mx = cli.post("/cmd/map", {"action": "wipe"})+check("demo /cmd/map with another action -> refused 400", code_mx == 400, f"{code_mx} {ans_mx}")+check("the page has the Clear map button", 'id="b-map-clear"' in open(os.path.join(str(ROOT), "tools", "moss_cockpit", "index.html")).read(), "b-map-clear missing in tools/moss_cockpit/index.html")demo.shutdown()page_none = os.path.join(TMP, "no_page")diff --git a/docs/cockpit.md b/docs/cockpit.mdindex 4848981..2d6e54d 100644--- a/docs/cockpit.md+++ b/docs/cockpit.md@@ -251,7 +251,10 @@ the profile's lidar height; `camera` (and `camera_n`) are the depth camera's obstheir true height, which the page draws in amber; `pose` is the rover's pose at thescan's time (x, y, yaw, age_s), so the page moves the rover marker at the scan'srate (3 Hz) rather than the state's (1 Hz). The raw `/pointcloud` fallback has no-`camera` key. The base panel shows a STALLED badge for at least 4 s whenever the+`camera` key. The map panel's **Clear map** button (`/cmd/map` with `action: clear`,+`tools/explore_ctl.py clear` from a shell) makes the costmap start a fresh grid centred on+the rover, without stopping the stack or the run: an open exploration keeps writing from+the next revolution. The base panel shows a STALLED badge for at least 4 s whenever thebase adapter's stall guard fires (a commanded track whose encoder did not move for1 s: the tracks stop and the planner backs off), and a `stalls` row counts themover the run.diff --git a/moss_dimos/costmap2d.py b/moss_dimos/costmap2d.pyindex d26b785..1ed77a5 100644--- a/moss_dimos/costmap2d.py+++ b/moss_dimos/costmap2d.py@@ -410,6 +410,7 @@ class MossCostMap(Module):explore_done: In[Bool] # explorer2 found no reachable frontier left: logged, the map keeps writingstop_explore_cmd: In[Bool] # exploration stopped on request (explore_ctl.py stop, the cockpit): logged, the map keeps writingexplore_cmd: In[Bool] # the order to explore: opens the map before the first motion+ clear_map_cmd: In[Bool] # the cockpit's Clear map (explore_ctl.py clear): a fresh grid, the mission gate as it isglobal_costmap: Out[OccupancyGrid]def __init__(self, world_frame: str = "world", **kwargs: Any) -> None:@@ -504,6 +505,19 @@ class MossCostMap(Module):self._mission_frozen = Falselogger.info("costmap: explore_cmd received - map writing OPEN for the mission")+ async def handle_clear_map_cmd(self, msg: Bool) -> None:+ """A fresh grid on request (the cockpit's Clear map): everything the map+ learned goes, centred again on the current pose; the mission gate stays+ as it is, so an open mission keeps writing from the next revolution and+ a run that has not started still waits for its order or its 5 cm."""+ if not bool(getattr(msg, "data", False)) or self._pose_xy is None:+ return+ self._grid = ScoredGrid(centre=self._pose_xy)+ self._revolutions = 0+ self._camera_pts = self._camera_cells = 0+ logger.info(f"costmap: map CLEARED on request - fresh grid centred on ({self._pose_xy[0]:+.2f}, "+ f"{self._pose_xy[1]:+.2f}), mission {'open' if not self._mission_frozen else 'not started'}")+async def handle_camera_floor(self, msg: PointCloud2) -> None:if self._grid is None or self._pose_xy is None or self._write_frozen():returndiff --git a/tools/explore_ctl.py b/tools/explore_ctl.pyindex 8f7d768..b155fd6 100755--- a/tools/explore_ctl.py+++ b/tools/explore_ctl.py@@ -23,7 +23,7 @@ import sysfrom dimos_lcm.std_msgs import Bool-CHANNELS = {"start": "explore_cmd", "stop": "stop_explore_cmd"}+CHANNELS = {"start": "explore_cmd", "stop": "stop_explore_cmd", "clear": "clear_map_cmd"} # clear: the costmap starts a fresh gridSUPPORTED_TRANSPORT = "lcm"TRANSPORT_VARS = ("DIMOS_TRANSPORT", "TRANSPORT") # dimOS's order: the first one set wins@@ -99,7 +99,7 @@ def publish(cmd: str) -> str:def main() -> None:cmd = sys.argv[1] if len(sys.argv) > 1 else "start"if cmd not in CHANNELS:- sys.exit("usage: explore_ctl.py start|stop")+ sys.exit("usage: explore_ctl.py start|stop|clear")try:used = publish(cmd)except TransportError as exc:diff --git a/tools/moss_cockpit.py b/tools/moss_cockpit.pyindex 7f98275..4dc5e57 100644--- a/tools/moss_cockpit.py+++ b/tools/moss_cockpit.py@@ -896,6 +896,13 @@ class BusCache:self._topics = {name: _Latest() for name in self._topics}self._decoded = {}+ def forget(self, name: str) -> None:+ """Drop one topic's last message (a cleared map must not be served from the cache)."""+ with self._lock:+ if name in self._topics:+ self._topics[name] = _Latest()+ self._decoded.pop(name, None)+def latest(self, name: str):with self._lock:t = self._topics[name]@@ -1327,6 +1334,16 @@ class LiveCockpit(Cockpit):with self._goal_lock:self._goal_gen += 1return {"ok": True, "sent": pub(explore_ctl.CHANNELS[action], Bool(data=True))}+ if name == "map":+ if body.get("action") != "clear":+ raise ValueError('map needs "action": "clear"')+ if self._moss_stack() is None:+ return not_moss()+ sent = pub(explore_ctl.CHANNELS["clear"], Bool(data=True))+ # the last map must not be served again: the next one comes from the fresh grid+ self.bus.forget("global_costmap")+ self._map_cache = (None, None, 0.0)+ return {"ok": True, "sent": sent}if name == "goal":x, y = _finite_xy(body)st = self._moss_stack()@@ -1714,6 +1731,13 @@ class DemoCockpit(Cockpit):self._say("info", f"demo: exploration {'started' if self.exploring else 'stopped'}")return {"ok": True, "sent": "/explore_cmd#std_msgs.Bool" if self.exploringelse "/stop_explore_cmd#std_msgs.Bool"}+ if name == "map":+ if body.get("action") != "clear":+ raise ValueError('map needs "action": "clear"')+ w.seen[:] = False # the demo forgets what it mapped and maps it again+ self._map_cache = (None, None)+ self._say("info", "demo: map cleared")+ return {"ok": True, "sent": "/clear_map_cmd#std_msgs.Bool"}if name == "goal":x, y = _finite_xy(body)self.exploring = Falsediff --git a/tools/moss_cockpit/app.js b/tools/moss_cockpit/app.jsindex a120cb6..816130a 100644--- a/tools/moss_cockpit/app.js+++ b/tools/moss_cockpit/app.js@@ -847,6 +847,13 @@ $("b-ex-yes").addEventListener("click", function () {post("explore", { action: "start" }).then(function (d) { answer(d, "Exploration started."); pollState(); },function () { say("The cockpit did not answer.", true); });});+$("b-map-clear").addEventListener("click", function () {+ // the page drops its own copy first: a cleared map must not stay on screen until the next one+ post("map", { action: "clear" }).then(function (d) {+ if (d && d.ok) { S.mapImg = null; S.mapStamp = null; S.meta = null; requestDraw(); }+ answer(d, "Map cleared: a fresh grid from here.");+ }, function () { say("The cockpit did not answer.", true); });+});$("b-ex-stop").addEventListener("click", function () {post("explore", { action: "stop" }).then(function (d) { answer(d, "Exploration stopped."); pollState(); },function () { say("The cockpit did not answer.", true); });diff --git a/tools/moss_cockpit/index.html b/tools/moss_cockpit/index.htmlindex 01ccddd..4d33b5b 100644--- a/tools/moss_cockpit/index.html+++ b/tools/moss_cockpit/index.html@@ -361,7 +361,7 @@<div id="map-wrap" data-live><canvas id="map" aria-label="Map. Drag to pan, wheel or pinch to zoom, tap to send a goal when navigation runs."></canvas><div id="hud"><span id="hud-xy">x -- m y -- m</span><span id="hud-cam">camera obstacles: --</span></div>- <div id="map-tools"><button class="btn" id="b-fit" type="button">Fit</button></div>+ <div id="map-tools"><button class="btn" id="b-fit" type="button">Fit</button><button class="btn" id="b-map-clear" type="button" title="The costmap starts a fresh grid; the run and the robot keep going">Clear map</button></div><div id="map-empty"><p class="dim" id="map-empty-why">No map yet. Launch a stack to build one.</p></div><div id="goal-chip" hidden role="dialog" aria-label="Confirm goal"><span id="goal-text" class="num">Send goal?</span>