MOSS: a small, mostly 3D-printed litter-picking rover. Cleaner streets, one maker at a time.
Python
sounds, gyro, odometry: the speaker stays awake, the gyro prior is the default, a contact no longer corrupts the map
metroxf81b022b3cd0
diff --git a/benches/bench_lidar_odometry_cold.py b/benches/bench_lidar_odometry_cold.pyindex e25ef34..45f55b9 100644--- a/benches/bench_lidar_odometry_cold.py+++ b/benches/bench_lidar_odometry_cold.py@@ -14,10 +14,19 @@ the dimOS messages are real. Known input -> known output, in metres and degrees:points (float32 on the wire) exactly when both read the same height.D. the gyro prior: a yaw rate of 0.5 rad/s for 0.2 s (gyro y = -0.5 on thedefault "-y" axis) -> the next revolution turns 5.73 deg; with the prior- off, kiss-icp's constant-velocity model is used instead.+ off, kiss-icp's constant-velocity model is used instead. start() with the+ prior on (the MOSS default) says "prior: gyro=True" in its up line.E. the optional depth path: 1.000 m of depth at the principal point, roverat the origin -> a camera point at (1.156, 0, 0.075) m on the next lidarcloud, which costmap2d.lidar_returns does NOT tag as lidar.+ G. a contact (`bump`): at rest after 10 revolutions of 300 points, a+ revolution of 90 points turned 6 deg right after a bump is dropped (the+ yaw moves by the gyro's +0.40 deg only, the log says so); the next 5 full+ revolutions register with sigma x2 and the 6th with the plain sigma; with+ no bump, outside the 0.4 s window or MOSS_CONTACT_DROP_RATIO=0 the same+ revolution registers at +6.0 deg. MOSS_RELOC_SWEEPS=3+ MOSS_RELOC_SIGMA_GAIN=3 give 3 revolutions at x3; MOSS_CONTACT_WINDOW_S=0.05+ lets a thin revolution 0.1 s after the bump register.Needs dimOS (kiss-icp is not needed: faked through sys.modules).@@ -50,6 +59,7 @@ from dimos.msgs.sensor_msgs.Imu import Imu # noqa: E402from dimos.msgs.sensor_msgs.JointState import JointState # noqa: E402from dimos.msgs.sensor_msgs.PointCloud2 import PointCloud2 # noqa: E402from dimos.msgs.tf2_msgs.TFMessage import TFMessage # noqa: E402+from dimos_lcm.std_msgs import Bool # noqa: E402from moss_dimos import costmap2d # noqa: E402from moss_dimos import lidar_odometry as LO # noqa: E402@@ -201,13 +211,13 @@ SCAN_FLAT = np.stack([np.cos(np.linspace(0, 2 * math.pi, 360, endpoint=False)) *print("A. streams, rpcs, defaults, start()")streams = {(s.name, s.type): s.direction for s in BlueprintAtom.create(LO.LidarOdometry, {}).streams}want = {("pointcloud", PointCloud2): "in", ("imu", Imu): "in", ("coordinator_joint_state", JointState): "in",- ("depth_image", Image): "in", ("camera_info", CameraInfo): "in",+ ("depth_image", Image): "in", ("camera_info", CameraInfo): "in", ("bump", Bool): "in",("odom", PoseStamped): "out", ("lidar", PointCloud2): "out", ("camera_floor", PointCloud2): "out",("tf", TFMessage): "out"}-check("the stream table: 5 Ins, 4 Outs, names and types as wired by the MOSS blueprints",+check("the stream table: 6 Ins, 4 Outs, names and types as wired by the MOSS blueprints",streams == want, f"extra {set(streams) - set(want)}, missing {set(want) - set(streams)}")-check("no reloc_frame, bump or bump_rear stream",- not any(n in ("reloc_frame", "bump", "bump_rear") for n, _ in streams))+check("bump is an In of dimos_lcm's Bool (the class BumpImu, the coordinator and the costmap use); no reloc_frame or bump_rear stream",+ streams.get(("bump", Bool)) == "in" and not any(n in ("reloc_frame", "bump_rear") for n, _ in streams))check("LidarOdometry.rpcs carries start and stop", {"start", "stop"} <= set(LO.LidarOdometry.rpcs))check("dimOS instance name 'lidarodometry'", LO.LidarOdometry.name == "lidarodometry")@@ -340,7 +350,7 @@ q = odometry(Kiss(0.10, 0.0, math.radians(2.0)), use_gyro_prior=False)for i in range(11):LOOP.run_until_complete(q.handle_imu(imu(-0.5, t0 + 0.02 * i)))drive(q, 1, SCAN_FLAT)-check("use_gyro_prior=False (the MOSS blueprint): the same gyro is ignored, 2.0 deg from the motion model",+check("use_gyro_prior=False (MOSS_GYRO=0 in the blueprint): the same gyro is ignored, 2.0 deg from the motion model",abs(yaw_of(q.odom.msgs[-1].orientation) - 2.0) < 0.01 and q._prior_used == "cv")js = types.SimpleNamespace(name=["base/vx", "base/vy", "base/wz"], position=[0.5, 0.0, 0.1])LOOP.run_until_complete(q.handle_coordinator_joint_state(js))@@ -352,6 +362,19 @@ check("wheel odometry is read for the log only: the pose follows the motion modeand abs(q.odom.msgs[-1].position.y - 0.10 * math.sin(step)) < 1e-9and abs(yaw_of(q.odom.msgs[-1].orientation) - 4.0) < 0.01,f"({q.odom.msgs[-1].position.x:.4f}, {q.odom.msgs[-1].position.y:.4f})")+gyro_spy, gyro_on = LogSpy(), LO.LidarOdometry(use_gyro_prior=True)+REAL.append(gyro_on)+_real_logger, _real_start = LO.logger, LO.Module.start+LO.logger, LO.Module.start = gyro_spy, (lambda self: None) # the dimOS runtime is not under test here+try:+ gyro_on.start()+finally:+ LO.logger, LO.Module.start = _real_logger, _real_start+up_on = [line for line in gyro_spy.lines if line.startswith("lidar odometry up")]+check("start() with the prior on (the MOSS default) logs 'prior: gyro=True' in its 'lidar odometry up' line "+ "(and section A's, prior off, said 'prior: gyro=False')",+ len(up_on) == 1 and "prior: gyro=True axis -y" in up_on[0] and len(up) == 1 and "prior: gyro=False" in up[0],+ up_on[0] if up_on else "no line")# --- E. the optional depth path -------------------------------------------------@@ -414,6 +437,236 @@ try:finally:_kiss_mod.KissICP = lambda cfg: Kiss(cfg=cfg)+# --- G. a contact and the map ---------------------------------------------------+print()+print("G. a contact: the shaken revolution dropped, the relocation after it")+++class MarkerRegistration(Registration):+ """The registration as a scan matcher on one feature: the revolution's+ marker (its farthest return) lies at bearing 0 in the world, so the+ heading the registration finds is minus the marker's bearing in the scan;+ the position stays the prediction's. A shaken sweep turned by 6 degrees+ registers 6 degrees off, as the real one did."""++ def align_points_to_map(self, points, voxel_map, initial_guess, max_correspondance_distance, kernel):+ guess = super().align_points_to_map(points, voxel_map, initial_guess, max_correspondance_distance, kernel)+ p = np.asarray(points)+ m = p[int(np.argmax(np.hypot(p[:, 0], p[:, 1])))]+ out = np.array(guess, dtype=float)+ out[:3, :3] = LO._se2(0.0, 0.0, -math.atan2(m[1], m[0]))[:3, :3]+ return out+++def marker_ring(n, heading_deg):+ """One revolution of n returns on a 2 m circle, the first one a marker at+ 3 m, as the lidar sees them from a rover heading heading_deg."""+ a = np.linspace(0.0, 2.0 * math.pi, n, endpoint=False) - math.radians(heading_deg)+ r = np.full(n, 2.0)+ r[0] = 3.0+ return np.stack([r * np.cos(a), r * np.sin(a), np.zeros(n)], 1)+++_imu_clock = [5000.0]+++def rev(o, pts, gyro_deg=0.0, n=1):+ """n revolutions, each after 0.1 s of gyro (6 samples at 50 Hz) turning the+ rover by gyro_deg degrees: the robot's 200 Hz IMU, thinned."""+ rate = math.radians(gyro_deg) / 0.1+ for _ in range(n):+ t = _imu_clock[0]+ _imu_clock[0] += 1.0 # a gap the integration skips: each revolution starts its own integral+ for i in range(6):+ LOOP.run_until_complete(o.handle_imu(imu(-rate, t + 0.02 * i)))+ drive(o, 1, pts)+++def contact_rover(use_gyro_prior):+ """A rover at rest that has registered 10 revolutions of 300 points at+ heading 0, with a spy on the sigma each registration gets."""+ k = Kiss()+ k.registration = MarkerRegistration()+ o = odometry(k, use_gyro_prior=use_gyro_prior)+ sigmas = []+ real_register = LO.LidarOdometry._register++ def spy_register(kiss, source, guess, sigma, where="scan"):+ sigmas.append(sigma)+ return real_register(kiss, source, guess, sigma, where)++ o._register = spy_register+ rev(o, marker_ring(300, 0.0), n=10)+ return o, sigmas+++def bump(o, data=True):+ LOOP.run_until_complete(o.handle_bump(Bool(data=data)))+++def heading(o):+ return yaw_of(o.odom.msgs[-1].orientation)+++def contact_section(spy):+ import importlib+ SHAKEN = marker_ring(90, 6.0) # the lidar shaken: 90 returns, 6 degrees off+ check("the knobs at their defaults: window 0.4 s, drop ratio 0.5, 5 relocation revolutions, sigma x2.0",+ (LO.CONTACT_WINDOW_S, LO.CONTACT_DROP_RATIO, LO.RELOC_SWEEPS, LO.RELOC_SIGMA_GAIN) == (0.4, 0.5, 5, 2.0))++ # (a) the contact, the gyro prior on and fed+ spy.lines.clear()+ o, sig = contact_rover(True)+ before = heading(o)+ bump(o)+ rev(o, SHAKEN, gyro_deg=0.4)+ check("(a) at rest, 10 revolutions of 300 points, a bump, a revolution of 90 points turned 6 deg: "+ "the yaw moves +0.40 deg (the gyro's), not 6",+ abs(before) < 1e-9 and abs(heading(o) - before - 0.4) < 0.01 and abs(heading(o) - before) <= 0.5,+ f"{before:+.3f} -> {heading(o):+.3f} deg")+ dropped = [line for line in spy.lines if "revolution dropped" in line]+ check("... one log line: 'contact: revolution dropped (90 pts, median 300), pose carried by the gyro'",+ len(dropped) == 1 and "contact: revolution dropped (90 pts, median 300), pose carried by the gyro" in dropped[0],+ dropped[0] if dropped else "no line")+ check("... counted (1), no registration for it, kiss-icp's map and threshold untouched",+ o._dropped_contact == 1 and len(sig) == 10 and o._kiss.local_map.updates == 10+ and o._kiss.adaptive_threshold.deviations == 10, f"{o._dropped_contact} dropped, {len(sig)} registrations")+ check("... the pose goes out (11 odom, 11 tf), the shaken cloud never reaches the map (10 clouds)",+ len(o.odom.msgs) == len(o.tf.msgs) == 11 and len(o.lidar.msgs) == 10)+ check("... the gyro integral consumed, kiss-icp's last pose at +0.40 deg (the next prior starts there)",+ o._gyro_acc == 0.0 and o._gyro_seen is False+ and abs(math.degrees(math.atan2(o._kiss.last_pose[1, 0], o._kiss.last_pose[0, 0])) - 0.4) < 0.01)++ # (c) the relocation: the rover truly heads +1.0 deg, the gyro said +0.4+ rev(o, marker_ring(300, 1.0), n=6)+ check("(c) after the bump, the next 5 full revolutions register with sigma x2 (0.40), the 6th with the plain 0.20",+ [round(s, 9) for s in sig[10:]] == [0.4] * 5 + [0.2], f"{sig[10:]}")+ reloc = [line for line in spy.lines if "relocat" in line]+ check("... one line at the first, 'contact: relocating over 5 revolutions (sigma x2.0)', one at the end: "+ "the registration corrected the yaw by +0.6 deg in total",+ len(reloc) == 2 and "contact: relocating over 5 revolutions (sigma x2.0)" in reloc[0]+ and "relocation done over 5 revolutions" in reloc[1] and "+0.6 deg in total" in reloc[1], f"{reloc}")+ check("... the heading the full revolutions show: +1.00 deg, the shaken +6 never published",+ abs(heading(o) - 1.0) < 0.01 and max(abs(yaw_of(m.orientation)) for m in o.odom.msgs) < 1.01, f"{heading(o):+.3f} deg")++ # (a) again, the gyro prior off: the pose is held+ spy.lines.clear()+ o, sig = contact_rover(False)+ bump(o)+ rev(o, SHAKEN, gyro_deg=0.4)+ check("(a) the prior off: dropped too, the pose held at 0.00 deg, the log says so",+ abs(heading(o)) < 1e-9 and o._dropped_contact == 1 and len(sig) == 10+ and any("revolution dropped (90 pts, median 300), pose held (no gyro prior)" in line for line in spy.lines),+ f"{heading(o):+.3f} deg")++ # (a) the prior on, but the imu stream quiet: no gyro sample since the last revolution+ spy.lines.clear()+ o, sig = contact_rover(True)+ bump(o)+ drive(o, 1, SHAKEN) # no imu message before this revolution+ dropped = [line for line in spy.lines if "revolution dropped" in line]+ check("(a) the prior on but no gyro sample since the last revolution: dropped, the pose held at 0.00 deg, the log says "+ "'pose held (no gyro sample since the last revolution)', not 'no gyro prior'",+ abs(heading(o)) < 1e-9 and o._dropped_contact == 1 and len(sig) == 10 and len(dropped) == 1+ and "pose held (no gyro sample since the last revolution)" in dropped[0] and "no gyro prior" not in dropped[0],+ dropped[0] if dropped else "no line")++ # (b) the control: no bump+ o, sig = contact_rover(True)+ bump(o, data=False)+ rev(o, SHAKEN, gyro_deg=0.4)+ check("(b) the same shaken revolution with no bump before it (a Bool False is none): registered, the yaw jumps to +6.0 deg",+ o._contact_t is None and abs(heading(o) - 6.0) < 0.01 and o._dropped_contact == 0+ and len(sig) == 11 and len(o.lidar.msgs) == 11, f"{heading(o):+.3f} deg")+ check("... with the plain sigma (no contact, no relocation)", abs(sig[-1] - 0.2) < 1e-12, f"{sig[-1]}")++ # (e) outside the window+ o, sig = contact_rover(True)+ bump(o)+ o._contact_t -= LO.CONTACT_WINDOW_S + 0.1 # the revolution comes 0.5 s after the contact+ rev(o, SHAKEN, gyro_deg=0.4)+ check("(e) the same revolution 0.5 s after the bump (window 0.4 s): registered as usual, +6.0 deg, nothing dropped",+ abs(heading(o) - 6.0) < 0.01 and o._dropped_contact == 0 and len(sig) == 11, f"{heading(o):+.3f} deg")++ # the running median follows the last 20 registered revolutions+ o, sig = contact_rover(True)+ rev(o, marker_ring(300, 0.0), n=15)+ rev(o, marker_ring(120, 0.0), n=20)+ bump(o)+ rev(o, SHAKEN, gyro_deg=0.4)+ check("the median is the last 20 revolutions': after 25 of 300 points then 20 of 120, 90 points is not shaken (>= 0.5 x 120)",+ o._dropped_contact == 0 and abs(heading(o) - 6.0) < 0.01, f"{o._dropped_contact} dropped")++ # start() says the knobs+ spy.lines.clear()+ up_mod = LO.LidarOdometry(use_gyro_prior=True)+ REAL.append(up_mod)+ real_start = LO.Module.start+ LO.Module.start = lambda self: None # the dimOS runtime is not under test here+ try:+ up_mod.start()+ finally:+ LO.Module.start = real_start+ said = [line for line in spy.lines if line.startswith("lidar odometry contacts:")]+ check("start() says the contact knobs in a line of its own",+ len(said) == 1 and "within 0.4 s of a bump under 0.5 x the median" in said[0]+ and "then 5 revolutions register with sigma x2" in said[0], said[0] if said else "no line")++ # (d) the knobs, read at import: bad values fall back, a drop ratio of 0 never drops+ knobs = {"MOSS_CONTACT_DROP_RATIO": "0", "MOSS_CONTACT_WINDOW_S": "soon",+ "MOSS_RELOC_SWEEPS": "3", "MOSS_RELOC_SIGMA_GAIN": "0.5"}+ tuned = {"MOSS_RELOC_SWEEPS": "3", "MOSS_RELOC_SIGMA_GAIN": "3", "MOSS_CONTACT_WINDOW_S": "0.05"}+ os.environ.update(knobs)+ try:+ importlib.reload(LO)+ LO.logger = spy+ check("MOSS_CONTACT_DROP_RATIO=0, MOSS_RELOC_SWEEPS=3 read at import; 'soon' -> the 0.4 s default, gain 0.5 -> its floor 1.0",+ (LO.CONTACT_WINDOW_S, LO.CONTACT_DROP_RATIO, LO.RELOC_SWEEPS, LO.RELOC_SIGMA_GAIN) == (0.4, 0.0, 3, 1.0),+ f"{(LO.CONTACT_WINDOW_S, LO.CONTACT_DROP_RATIO, LO.RELOC_SWEEPS, LO.RELOC_SIGMA_GAIN)}")+ o, sig = contact_rover(True)+ bump(o)+ rev(o, SHAKEN, gyro_deg=0.4)+ check("(d) MOSS_CONTACT_DROP_RATIO=0 never drops: the shaken revolution registers, +6.0 deg",+ o._dropped_contact == 0 and abs(heading(o) - 6.0) < 0.01 and len(sig) == 11, f"{heading(o):+.3f} deg")++ # (d) once more, with values that change the behaviour+ for name in knobs:+ os.environ.pop(name, None)+ os.environ.update(tuned)+ importlib.reload(LO)+ LO.logger = spy+ check("MOSS_RELOC_SWEEPS=3 MOSS_RELOC_SIGMA_GAIN=3 MOSS_CONTACT_WINDOW_S=0.05 read at import (drop ratio 0.5)",+ (LO.CONTACT_WINDOW_S, LO.CONTACT_DROP_RATIO, LO.RELOC_SWEEPS, LO.RELOC_SIGMA_GAIN) == (0.05, 0.5, 3, 3.0),+ f"{(LO.CONTACT_WINDOW_S, LO.CONTACT_DROP_RATIO, LO.RELOC_SWEEPS, LO.RELOC_SIGMA_GAIN)}")+ o, sig = contact_rover(True)+ bump(o)+ rev(o, SHAKEN, gyro_deg=0.4)+ rev(o, marker_ring(300, 0.0), n=4)+ check("(d) after a bump and the shaken revolution (dropped), 4 full ones register with sigma 0.60, 0.60, 0.60, "+ "then the plain 0.20: 3 relocation revolutions at x3",+ o._dropped_contact == 1 and [round(s, 9) for s in sig[10:]] == [0.6] * 3 + [0.2], f"{sig[10:]}")+ o, sig = contact_rover(True)+ bump(o)+ o._contact_t -= 0.1 # the thin revolution comes 0.1 s after the contact+ rev(o, SHAKEN, gyro_deg=0.4)+ check("(d) a thin revolution 0.1 s after the bump registers (the 0.05 s window has closed), +6.0 deg, nothing dropped",+ o._dropped_contact == 0 and abs(heading(o) - 6.0) < 0.01 and len(sig) == 11, f"{heading(o):+.3f} deg")+ finally:+ for name in {**knobs, **tuned}:+ os.environ.pop(name, None)+ importlib.reload(LO)+ check("... unset again: the defaults are back (0.4, 0.5, 5, 2.0)",+ (LO.CONTACT_WINDOW_S, LO.CONTACT_DROP_RATIO, LO.RELOC_SWEEPS, LO.RELOC_SIGMA_GAIN) == (0.4, 0.5, 5, 2.0))+++contact_spy, contact_logger = LogSpy(), LO.logger+LO.logger = contact_spy+try:+ contact_section(contact_spy)+finally:+ LO.logger = contact_logger+gc.collect()+print(f"{OK} OK, {KO} KO")print("TEST PASSED" if KO == 0 else "TEST FAILED")# section F built its own module after the clean-up above: drop its clouds too, ordiff --git a/benches/bench_moss_blueprints_cold.py b/benches/bench_moss_blueprints_cold.pyindex ca4be40..df8eb7a 100644--- a/benches/bench_moss_blueprints_cold.py+++ b/benches/bench_moss_blueprints_cold.py@@ -42,6 +42,14 @@ Known input -> known output in physical units. Groups:coordinator, no stream type conflict; refused without thecamera; both classes pickle by reference into a cleaninterpreter; importing the blueprints imports neither+ K. MOSS_GYRO - the odometry's rotation prior: on by default with the+ in-process IMU (MossRealSense, enable_imu True), off with+ MOSS_GYRO=0 (the contacts stay) or MOSS_IMU=0 (quietly);+ MOSS_IMU=0 MOSS_GYRO=1 refused with one warning (dimOS's+ camera keeps enable_imu False); MOSS_GYRO_FORCE=1 on top+ builds dimOS's camera with enable_imu True and the prior+ on, its imu wired to the odometry, with a warning; FORCE+ alone changes nothing; no camera, no priorI. the worker - what a dimOS forkserver worker does: unpickle thecoordinator class in a clean interpreter -> the module isimported, 'moss' is registered, the registry builds a@@ -462,7 +470,7 @@ check("lidar on the CP2102N by-id at 460800, frame lidar_link",hw = atom(nav, "MossControlCoordinator").kwargs["hardware"][0]check("base: adapter 'moss' on the QT Py by-id", hw.adapter_type == "moss" and hw.address == os.path.join(byid, QTPY))check("pad: the same MOSS envelope as moss-gamepad", atom(nav, "GamepadTeleop").kwargs.get("envelope") == teleop_envelope(g))-check("odometry without the gyro prior (MOSS_GYRO unset = off)", atom(nav, "LidarOdometry").kwargs.get("use_gyro_prior") is False)+check("odometry with the gyro prior (MOSS_GYRO unset = on with MOSS_IMU, the default)", atom(nav, "LidarOdometry").kwargs.get("use_gyro_prior") is True)check("odometry without deskew (MOSS_DESKEW unset = off: on the rover the deskew thread fails)", atom(nav, "LidarOdometry").kwargs.get("deskew") is False)cam = atom(nav, "MossRealSense").kwargscheck("RealSense 640x480 @ 5 fps, colour + depth (aligned), no point cloud, the IMU in the camera's own process (MOSS_IMU on by default)",@@ -573,6 +581,12 @@ check("... the sounds read it too when the sound module is in the build","MossSounds" not in names(imu_exp) or ("MossSounds", "in") in bump_side, f"{sorted(names(imu_exp))}")check("... no second bump stream of another type",[k for k in w if k[0] == "bump"] == [("bump", mb.Bool)], f"{[k for k in w if k[0] == 'bump']}")+check("... and the lidar odometry's contact In (the shaken revolution dropped), on the costmap's stream, in moss-explore and "+ "moss-nav; with MOSS_IMU=0 the stall guard's bump still reaches it",+ ("LidarOdometry", "in") in bump_side+ and {("LidarOdometry", "in"), ("MossCostMap", "in")} <= wiring(imu_nav).get(("bump", mb.Bool), set())+ and {("MossControlCoordinator", "out"), ("LidarOdometry", "in")} <= wiring(off_exp).get(("bump", mb.Bool), set()),+ f"{sorted(wiring(imu_nav).get(('bump', mb.Bool), set()))}")check("imu: MossRealSense out -> BumpImu in (and the odometry's In)",{("MossRealSense", "out"), ("BumpImu", "in"), ("LidarOdometry", "in")} <= w.get(("imu", Imu), set()),f"{sorted(w.get(('imu', Imu), set()))}")@@ -586,7 +600,7 @@ except ValueError as exc:check("dimOS's stream type check accepts both MOSS_IMU builds", False, str(exc)[:300])check("moss-nav with MOSS_IMU=1: bump reaches the costmap (no planner there)",{("BumpImu", "out"), ("MossCostMap", "in")} <= wiring(imu_nav).get(("bump", mb.Bool), set()))-check("MOSS_IMU=1 leaves the gyro prior off (MOSS_GYRO unset)", atom(imu_nav, "LidarOdometry").kwargs.get("use_gyro_prior") is False)+check("MOSS_IMU=1 (MOSS_GYRO unset): the gyro prior on, from the in-process IMU", atom(imu_nav, "LidarOdometry").kwargs.get("use_gyro_prior") is True)os.environ.update(MOSS_BUMP_ACCEL="6", MOSS_BUMP_AXIS="-z", MOSS_BUMP_DEBOUNCE_S="0.5", MOSS_IMU_LOG="/data/imu.csv", MOSS_GYRO="1")tuned = mb.build_moss_nav()for k in ("MOSS_BUMP_ACCEL", "MOSS_BUMP_AXIS", "MOSS_BUMP_DEBOUNCE_S", "MOSS_IMU_LOG", "MOSS_GYRO"):@@ -602,6 +616,115 @@ os.environ.pop("MOSS_CAMERA")check("MOSS_IMU=1 MOSS_CAMERA=0: no camera, so no BumpImu either (refused with a warning)",not ({"MossRealSense", "RealSenseCamera", "BumpImu"} & names(nocam)), f"{sorted(names(nocam))}")os.environ.pop("MOSS_IMU")++# ── K. MOSS_GYRO: the gyro as the rotation prior ──────────────────────────+print("K. MOSS_GYRO: the odometry's rotation prior from the in-process IMU")+++class BuildLog:+ """Stands in for the blueprint module's logger while one build runs: one (level, text) per line,+ so a warning that slides to debug (hidden on the robot) is seen."""++ def __init__(self):+ self.lines = []++ def _at(level):+ def record(self, msg, *args, **kwargs):+ self.lines.append((level, str(msg) % args if args else str(msg)))+ return record++ info, warning, error, debug, exception = _at("info"), _at("warning"), _at("error"), _at("debug"), _at("exception")+ del _at+++def build_logged(builder, **env):+ """(blueprint, log lines): built with these MOSS_* set (removed afterwards),+ the blueprint module's logger captured."""+ spy, real = BuildLog(), mb._logger+ os.environ.update(env)+ mb._logger = spy+ try:+ return builder(), spy.lines+ finally:+ mb._logger = real+ for k in env:+ os.environ.pop(k, None)+++def find(bp, cls_name):+ return next((b for b in bp.active_blueprints if b.module.__name__ == cls_name), None)+++def prior(bp):+ return find(bp, "LidarOdometry").kwargs.get("use_gyro_prior")+++def gyro_lines(lines, level="warning"):+ """The texts of the MOSS_GYRO lines logged at `level` (None = at any level)."""+ return [text for lvl, text in lines if "MOSS_GYRO" in text and level in (None, lvl)]+++for builder, label, default_bp in ((mb.build_moss_nav, "moss-nav", nav), (mb.build_moss_explore, "moss-explore", exp)):+ bp, log = build_logged(builder)+ cam_k = find(bp, "MossRealSense")+ check(f"{label}, every switch unset: use_gyro_prior True on MossRealSense with enable_imu True, no MOSS_GYRO line",+ prior(bp) is True and cam_k is not None and cam_k.kwargs.get("enable_imu") is True+ and "RealSenseCamera" not in names(bp) and not gyro_lines(log, None), f"{prior(bp)} {gyro_lines(log, None)}")+ check(f"{label}: the same blueprint as built in G, kwarg for kwarg", blueprint_text(bp) == blueprint_text(default_bp))+for spelled_off, builder in (("0", mb.build_moss_nav), ("off", mb.build_moss_explore)):+ bp, log = build_logged(builder, MOSS_GYRO=spelled_off)+ cam_k = find(bp, "MossRealSense")+ check(f"MOSS_GYRO={spelled_off}: use_gyro_prior False, and the contacts stay (MossRealSense enable_imu True, BumpImu)",+ prior(bp) is False and cam_k is not None and cam_k.kwargs.get("enable_imu") is True+ and "BumpImu" in names(bp) and not gyro_lines(log, None), f"{prior(bp)} {sorted(names(bp))}")+bp, log = build_logged(mb.build_moss_nav, MOSS_IMU="0")+cam_k = find(bp, "RealSenseCamera")+check("MOSS_IMU=0 alone: use_gyro_prior False, dimOS's camera with enable_imu False, no MOSS_GYRO line (the default follows quietly)",+ prior(bp) is False and cam_k is not None and cam_k.kwargs.get("enable_imu") is False+ and "MossRealSense" not in names(bp) and not gyro_lines(log, None), f"{prior(bp)} {gyro_lines(log, None)}")+bp, log = build_logged(mb.build_moss_nav, MOSS_IMU="0", MOSS_GYRO="1")+cam_k = find(bp, "RealSenseCamera")+warned = gyro_lines(log)+check("MOSS_IMU=0 MOSS_GYRO=1: refused, use_gyro_prior False, dimOS's camera keeps enable_imu False",+ prior(bp) is False and cam_k is not None and cam_k.kwargs.get("enable_imu") is False, f"{prior(bp)}")+check("... with one line at warning level that says refused and names MOSS_IMU=1 and MOSS_GYRO_FORCE=1",+ len(warned) == 1 == len(gyro_lines(log, None)) and "refused" in warned[0] and "MOSS_IMU=1" in warned[0]+ and "MOSS_GYRO_FORCE=1" in warned[0],+ f"{warned}")+for builder, label in ((mb.build_moss_nav, "moss-nav"), (mb.build_moss_explore, "moss-explore")):+ bp, log = build_logged(builder, MOSS_IMU="0", MOSS_GYRO="1", MOSS_GYRO_FORCE="1")+ cam_k = find(bp, "RealSenseCamera")+ warned = gyro_lines(log)+ check(f"{label}, MOSS_IMU=0 MOSS_GYRO=1 MOSS_GYRO_FORCE=1: dimOS's own camera with enable_imu True, use_gyro_prior True, no BumpImu",+ cam_k is not None and cam_k.module is RealSenseCamera and cam_k.kwargs.get("enable_imu") is True+ and "imu_hz" not in cam_k.kwargs and prior(bp) is True+ and not ({"MossRealSense", "BumpImu"} & names(bp)), f"{prior(bp)} {sorted(names(bp))}")+ check(f"{label}: ... its imu reaches the odometry's In, and one line at warning level calls it an experiment",+ {("RealSenseCamera", "out"), ("LidarOdometry", "in")} <= wiring(bp).get(("imu", Imu), set())+ and len(warned) == 1 == len(gyro_lines(log, None)) and "experiment" in warned[0],+ f"{sorted(wiring(bp).get(('imu', Imu), set()))} {warned}")+ try:+ _verify_no_name_conflicts(bp)+ check(f"{label}: dimOS's stream type check accepts the forced build", True)+ except ValueError as exc:+ check(f"{label}: dimOS's stream type check accepts the forced build", False, str(exc)[:300])+bp, log = build_logged(mb.build_moss_nav, MOSS_GYRO_FORCE="1")+check("MOSS_GYRO_FORCE=1 alone changes nothing: the default blueprint, no MOSS_GYRO line",+ blueprint_text(bp) == blueprint_text(nav) and not gyro_lines(log, None), f"{gyro_lines(log, None)}")+bp, log = build_logged(mb.build_moss_nav, MOSS_IMU="0", MOSS_GYRO="0", MOSS_GYRO_FORCE="1")+check("MOSS_IMU=0 MOSS_GYRO=0 MOSS_GYRO_FORCE=1: the force never turns the prior on by itself (enable_imu False)",+ prior(bp) is False and find(bp, "RealSenseCamera").kwargs.get("enable_imu") is False and not gyro_lines(log, None))+for force in ("0", "1"):+ bp, log = build_logged(mb.build_moss_nav, MOSS_CAMERA="0", MOSS_GYRO="1", MOSS_GYRO_FORCE=force)+ warned = gyro_lines(log)+ check(f"MOSS_CAMERA=0 MOSS_GYRO=1 MOSS_GYRO_FORCE={force}: no camera, no prior, one line at warning level: MOSS_GYRO needs the RealSense",+ prior(bp) is False and not ({"RealSenseCamera", "MossRealSense"} & names(bp))+ and len(warned) == 1 == len(gyro_lines(log, None)) and "needs the RealSense" in warned[0], f"{prior(bp)} {warned}")+bp, log = build_logged(mb.build_moss_nav, MOSS_CAMERA="0")+check("MOSS_CAMERA=0 alone: no prior, and no MOSS_GYRO line (nothing was asked)", prior(bp) is False and not gyro_lines(log, None))+check("every MOSS_GYRO* variable is gone from the environment after the builds",+ not [k for k in os.environ if k.startswith("MOSS_GYRO") or k in ("MOSS_IMU", "MOSS_CAMERA")])+pick = run_child("""import json, pickle, sysimport moss_dimos.blueprints as bdiff --git a/benches/bench_moss_sounds_cold.py b/benches/bench_moss_sounds_cold.pyindex 3e97940..c23a550 100644--- a/benches/bench_moss_sounds_cold.py+++ b/benches/bench_moss_sounds_cold.py@@ -4,7 +4,13 @@ Known input -> known output: a bump plays bump_surprise; a stall followed bymotion plays recovery_success once; the battery crossing the low threshold forlong enough plays battery_low once, with hysteresis; the vendored pack hasevery file its manifest names; the player in dry-run mode queues what the-module hands it. No audio device, no subprocess.+module hands it. E: the keep-awake period and the pre-roll are read from the+environment; the pre-rolled copy of a cue is N + 0.3 s * rate frames, silence+then the cue; the backend plays that copy, or the original with the pre-roll+off or when the copy cannot be written; the speaker script connects, sets the+default sink and gives up after its tries. No audio device and no Bluetooth:+the playback backend and the Bluetooth / PulseAudio tools are shell stubs that+record their arguments (the script runs with a PATH of stubs only).Run: PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=. python3 benches/bench_moss_sounds_cold.py"""@@ -46,7 +52,7 @@ with _wave.open(str(ASSETS / "keep_awake.wav"), "rb") as _w:and max(abs(x) for x in __import__("struct").unpack("<" + "h" * _w.getnframes(), _w.readframes(_w.getnframes()))) == 0,"keep_awake.wav: mono 44.1 kHz, about half a second, all zeros (silent)")from moss_dimos.sounds import KEEP_AWAKE_S # noqa: E402-check(KEEP_AWAKE_S == 240.0, "the keep-awake breath is every 4 min")+check(KEEP_AWAKE_S == 15.0, "the keep-awake default is every 15 s")cmd = playback_command(ASSETS / "boot_ready_01.wav", backend="paplay", target="bt_sink", volume=0.5) if __import__("shutil").which("paplay") else Nonecheck(cmd is None or (cmd[0] == "paplay" and "--device=bt_sink" in cmd and cmd[-1].endswith("boot_ready_01.wav")),f"paplay command names the sink and the file: {cmd}")@@ -135,6 +141,222 @@ texts = [(ROOT / "moss_dimos" / "sound_pack" / "player.py").read_text(), (ASSETScheck(not any(re.search(r"\b(20\d\d-\d\d-\d\d|\d\d/\d\d/20\d\d)\b", t) for t in texts), "no date in the player, the manifest or the config")check(all(ord(ch) < 128 for t in texts for ch in t), "ASCII only (English)")++print("E. the speaker that stays awake: keep-awake period, pre-roll, reconnection at boot")+import shutil # noqa: E402+import subprocess # noqa: E402+import tempfile # noqa: E402+from dimos.core.module import Module # noqa: E402+import moss_dimos.sounds as sounds_mod # noqa: E402+from moss_dimos.sound_pack.player import PREROLL_S, preroll_wav # noqa: E402++kap = sounds_mod.keep_awake_period+check(kap({}) == 15.0 and kap({"MOSS_SOUND_KEEP_AWAKE_S": "0"}) == 0.0 and kap({"MOSS_SOUND_KEEP_AWAKE_S": "often"}) == 15.0+ and kap({"MOSS_SOUND_KEEP_AWAKE_S": "30"}) == 30.0 and kap({"MOSS_SOUND_KEEP_AWAKE_S": "-5"}) == 0.0,+ "MOSS_SOUND_KEEP_AWAKE_S: unset -> 15 s, 0 -> off, text -> 15 s, 30 -> 30 s, negative -> off")+work = Path(tempfile.mkdtemp(prefix="moss_sounds_bench_"))+saved_env = {k: os.environ.get(k) for k in ("PATH", "MOSS_SOUND_CACHE", "MOSS_SOUND_PREROLL_S", "MOSS_SOUND_KEEP_AWAKE_S")}+++def frames_of(path):+ with _wave.open(str(path), "rb") as w:+ return (w.getnchannels(), w.getsampwidth(), w.getframerate()), w.getnframes(), w.readframes(w.getnframes())+++src = ASSETS / "bump_surprise_01.wav"+params, n, raw = frames_of(src)+pre = round(0.3 * params[2])+copy = preroll_wav(src, 0.3, work / "cache_unit")+cparams, cn, craw = frames_of(copy)+lead = pre * params[0] * params[1]+check(cparams == params and cn == n + pre, f"pre-rolled copy: {n} + 0.3 s * {params[2]} = {n + pre} frames, same params ({cn}, {cparams})")+check(craw[:lead] == bytes(lead) and craw[lead:] == raw, "its first 0.3 s are all zeros, the rest is the cue byte for byte")+mtime = copy.stat().st_mtime_ns+check(preroll_wav(src, 0.3, work / "cache_unit") == copy and copy.stat().st_mtime_ns == mtime+ and not list((work / "cache_unit").glob("*.tmp")), "a second call reuses the copy (written once), no temporary left")+os.environ.pop("MOSS_SOUND_PREROLL_S", None)+_p = MossSoundPlayer(root=ASSETS, dry_run=True)+check(PREROLL_S == 0.3 and _p.preroll_s == 0.3, "MOSS_SOUND_PREROLL_S unset -> 0.3 s")+_p.close()+for raw_env, want in (("0", 0.0), ("loud", 0.3), ("0.5", 0.5)):+ os.environ["MOSS_SOUND_PREROLL_S"] = raw_env+ _p = MossSoundPlayer(root=ASSETS, dry_run=True)+ check(_p.preroll_s == want, f"MOSS_SOUND_PREROLL_S={raw_env} -> {want} s ({_p.preroll_s})")+ _p.close()++# the backend: a paplay stub on the PATH that records its arguments, one call per line+stub_bin = work / "bin"+stub_bin.mkdir()+calls = work / "paplay_calls"+(stub_bin / "paplay").write_text(f'#!/bin/sh\necho "$*" >> "{calls}"\nexit 0\n')+(stub_bin / "paplay").chmod(0o755)+os.environ["PATH"] = f"{stub_bin}{os.pathsep}{saved_env['PATH']}"+++def played_by(config_extra=None, log=None, dry_run=False):+ """One bump_surprise through a real (not dry-run) player on the stub backend; the file it played."""+ calls.write_text("")+ pl = MossSoundPlayer(root=ASSETS, config={"backend": "paplay", "global_gap_s": 0.0, **(config_extra or {})},+ dry_run=dry_run, log=log)+ queued = pl.emit("bump_surprise")+ pl.wait_idle(timeout=8)+ rows = pl.drain_status()+ pl.close()+ lines = [ln for ln in calls.read_text().splitlines() if ln.strip()]+ return queued, (Path(lines[-1].split()[-1]) if lines else None), rows+++os.environ.pop("MOSS_SOUND_PREROLL_S", None)+os.environ["MOSS_SOUND_CACHE"] = str(work / "cache_on")+queued, played, rows = played_by()+ok = played is not None and played.parent == work / "cache_on" and played.name.startswith("bump_surprise_0")+if ok:+ orig = ASSETS / (played.name.split("-")[0] + ".wav")+ oparams, on, oraw = frames_of(orig)+ pparams, pn, praw = frames_of(played)+ ok = pparams == oparams and pn == on + round(0.3 * oparams[2]) and praw[round(0.3 * oparams[2]) * 2:] == oraw+check(queued and ok and any(r["state"] == "finished" for r in rows),+ f"pre-roll on: the backend plays the cached copy (silence + the cue) from MOSS_SOUND_CACHE: {played}")+check(len(list((work / "cache_on").glob("*.wav"))) == len(manifest["assets"]), "one copy per asset, written before the first cue")+os.environ["MOSS_SOUND_PREROLL_S"] = "0"+os.environ["MOSS_SOUND_CACHE"] = str(work / "cache_off")+queued, played, rows = played_by()+check(queued and played is not None and played.parent == ASSETS.resolve() and played.name.startswith("bump_surprise_0")+ and not (work / "cache_off").exists(), f"MOSS_SOUND_PREROLL_S=0: the backend plays the original asset, no cache written: {played}")+os.environ.pop("MOSS_SOUND_PREROLL_S", None)+(work / "not_a_dir").write_text("a file where the cache dir should be")+os.environ["MOSS_SOUND_CACHE"] = str(work / "not_a_dir" / "cache")+said = []+queued, played, rows = played_by(log=said.append)+check(queued and played is not None and played.parent == ASSETS.resolve() and len(said) == 1+ and sum(r["state"] == "preroll_failed" for r in rows) == 1,+ f"the cache cannot be written: the original plays, said once ({len(said)} log line(s): {said[:1]})")+os.environ["MOSS_SOUND_CACHE"] = str(work / "cache_dry")+dry = MossSoundPlayer(root=ASSETS, config={"global_gap_s": 0.0}, dry_run=True)+check(dry.emit("bump_surprise") is True, "dry run with the pre-roll on: emit is queued")+dry.wait_idle(timeout=3)+drows = dry.drain_status()+dry.close()+check(any(r.get("state") == "simulated" and r.get("event") == "bump_surprise" for r in drows) and not (work / "cache_dry").exists(),+ f"dry run: the emit still reports (simulated), nothing written: {[r.get('state') for r in drows]}")++# the module's start: the period read there and said in its first line (dimOS's own start/stop left out: no bus here)+lines_said = []+++class _Log:+ def info(self, text): lines_said.append(text)+ def warning(self, text): lines_said.append(text)+++real_logger, real_start, real_stop = sounds_mod.logger, Module.start, Module.stop+sounds_mod.logger = _Log()+Module.start = lambda self: None+Module.stop = lambda self: None+try:+ os.environ["MOSS_SOUND_BACKEND"] = "paplay"+ os.environ["MOSS_SOUND_CACHE"] = str(work / "cache_mod")+ os.environ["MOSS_SOUND_KEEP_AWAKE_S"] = "0.3"+ calls.write_text("")+ mod2 = MossSounds()+ mod2.start()+ time.sleep(1.5)+ mod2.stop()+ breaths = sum("keep_awake.wav" in ln for ln in calls.read_text().splitlines())+ up = next((ln for ln in lines_said if "MOSS sounds: up" in ln), "")+ check(mod2._keep_awake_s == 0.3 and "keep-awake every 0.3 s" in up and "pre-roll 0.30 s" in up,+ f"start reads MOSS_SOUND_KEEP_AWAKE_S and its line says the period and the pre-roll: {up[:160]}")+ check(breaths >= 2, f"the keep-awake clip plays at that period ({breaths} in 1.5 s at 0.3 s)")+ os.environ["MOSS_SOUND_KEEP_AWAKE_S"] = "0"+ lines_said.clear()+ mod3 = MossSounds()+ mod3.start()+ up = next((ln for ln in lines_said if "MOSS sounds: up" in ln), "")+ check(getattr(mod3, "_awake_stop", None) is None and "keep-awake off" in up, f"MOSS_SOUND_KEEP_AWAKE_S=0: no keep-awake thread, the line says off: {up[:160]}")+ mod3.stop()+finally:+ sounds_mod.logger, Module.start, Module.stop = real_logger, real_start, real_stop+ os.environ.pop("MOSS_SOUND_BACKEND", None)+ for k, v in saved_env.items():+ if v is None:+ os.environ.pop(k, None)+ else:+ os.environ[k] = v++# tools/moss-jbl-connect.sh: syntax, refusal, and a run against stubs (bluetoothctl, pactl, sleep) on a PATH of stubs only+SCRIPT = ROOT / "tools" / "moss-jbl-connect.sh"+BASH = shutil.which("bash")+check(subprocess.run([BASH, "-n", str(SCRIPT)], capture_output=True).returncode == 0, "moss-jbl-connect.sh: bash -n")+jbin = work / "jbin"+jbin.mkdir()+for tool in ("timeout", "seq", "sed", "grep", "awk", "tr", "tail"):+ (jbin / tool).symlink_to(shutil.which(tool))+count, bt_log, pa_log, sl_log = work / "bt_count", work / "bt_args", work / "pa_args", work / "sleep_args"+++def jbl_stubs(succeed_on, sink=True):+ """bluetoothctl answers "Connection successful" from its `succeed_on`-th call (0 = never);+ pactl lists the speaker's bluez sink unless `sink` is False (a link that dropped)."""+ count.write_text("0\n")+ for f in (bt_log, pa_log, sl_log):+ f.write_text("")+ (jbin / "bluetoothctl").write_text(+ "#!/bin/sh\n"+ f'read n < "{count}"; n=$((n + 1)); echo "$n" > "{count}"; echo "$*" >> "{bt_log}"\n'+ f'if [ {succeed_on} -gt 0 ] && [ "$n" -ge {succeed_on} ]; then echo "Attempting to connect to $2"; echo "Connection successful"; exit 0; fi\n'+ 'echo "Failed to connect: org.bluez.Error.Failed br-connection-page-timeout"; exit 1\n')+ (jbin / "pactl").write_text(+ "#!/bin/sh\n"+ f'echo "$*" >> "{pa_log}"\n'+ 'if [ "$1 $2 $3" = "list short sinks" ]; then\n'+ ' printf "0\\talsa_output.platform-sound.analog-stereo\\tmodule-alsa-card.c\\ts16le 2ch 44100Hz\\tSUSPENDED\\n"\n'+ + (' printf "1\\tbluez_sink.00_00_00_00_00_00.a2dp_sink\\tmodule-bluez5-device.c\\ts16le 2ch 44100Hz\\tIDLE\\n"\n'+ if sink else "")+ + "fi\nexit 0\n")+ (jbin / "sleep").write_text(f'#!/bin/sh\necho "$*" >> "{sl_log}"\nexit 0\n')+ for t in ("bluetoothctl", "pactl", "sleep"):+ (jbin / t).chmod(0o755)+++def jbl_run(env_extra):+ env = {"PATH": str(jbin), "HOME": str(work), "MOSS_STATE_DIR": str(work / "state"), **env_extra}+ return subprocess.run([BASH, str(SCRIPT)], env=env, capture_output=True, text=True, timeout=60)+++jbl_stubs(2)+r = jbl_run({})+check(r.returncode == 2 and "no speaker address" in r.stderr and bt_log.read_text() == "",+ f"no MOSS_JBL_MAC and no jbl.env: exit 2 with a message, bluetoothctl never called ({r.returncode}: {r.stderr.strip()[:90]})")+r = jbl_run({"MOSS_JBL_MAC": "not-an-address"})+check(r.returncode == 2 and "not a Bluetooth address" in r.stderr, f"a malformed address: exit 2 ({r.returncode})")+jbl_stubs(2)+r = jbl_run({"MOSS_JBL_MAC": "00:00:00:00:00:00"})+pa = pa_log.read_text().splitlines()+check(r.returncode == 0 and bt_log.read_text().splitlines() == ["connect 00:00:00:00:00:00"] * 2 and sl_log.read_text().split() == ["5"],+ f"bluetoothctl fails then connects: exit 0 after two tries, one 5 s wait between ({r.returncode}, {bt_log.read_text().splitlines()}, sleep {sl_log.read_text().split()})")+check("set-default-sink bluez_sink.00_00_00_00_00_00.a2dp_sink" in pa and not any("volume" in ln for ln in pa),+ f"the speaker's bluez sink becomes the default sink, the volume is never touched: {pa}")+(work / "state").mkdir()+(work / "state" / "jbl.env").write_text('MOSS_JBL_MAC="00:00:00:00:00:00"\n')+jbl_stubs(1)+r = jbl_run({})+check(r.returncode == 0 and bt_log.read_text().splitlines() == ["connect 00:00:00:00:00:00"] and sl_log.read_text() == "",+ f"the address read from $MOSS_STATE_DIR/jbl.env (quoted): connected on the first try ({r.returncode}: {r.stderr.strip()[:90]})")+jbl_stubs(0)+r = jbl_run({"MOSS_JBL_MAC": "00:00:00:00:00:00", "MOSS_JBL_TRIES": "3"})+check(r.returncode == 1 and "gave up after 3 tries" in r.stderr and "page-timeout" in r.stderr+ and len(bt_log.read_text().splitlines()) == 3 and sl_log.read_text().split() == ["5", "5"] and pa_log.read_text() == "",+ f"a speaker that never answers: exit 1 after MOSS_JBL_TRIES=3 with the reason ({r.returncode}: {r.stderr.strip()[:120]})")+jbl_stubs(1, sink=False)+r = jbl_run({"MOSS_JBL_MAC": "00:00:00:00:00:00", "MOSS_JBL_TRIES": "3"})+pa = pa_log.read_text().splitlines()+check(r.returncode == 1 and "gave up after 3 tries: connected, but no bluez sink" in r.stderr+ and bt_log.read_text().splitlines() == ["connect 00:00:00:00:00:00"] * 3 and sl_log.read_text().split() == ["5", "5"]+ and pa == ["list short sinks"] * 3,+ f"connected but the sink never appears (the link dropped): every try connects again, exit 1 after 3 "+ f"({r.returncode}: {r.stderr.strip()[:90]}; bluetoothctl x{len(bt_log.read_text().splitlines())}, pactl {pa})")+shutil.rmtree(work, ignore_errors=True)+print(f"\n{OK} OK, {KO} KO")print("TEST PASSED" if KO == 0 else "TEST FAILED")sys.exit(1 if KO else 0)diff --git a/docs/cockpit.md b/docs/cockpit.mdindex 1086d5b..87ac533 100644--- a/docs/cockpit.md+++ b/docs/cockpit.md@@ -68,8 +68,8 @@ firmware 300 ms after the last drive.straight to `cmd_vel`;- the RPLidar C1 reader (`moss_dimos/rplidar_c1.py`) on its own USB serial adapter;- lidar odometry (kiss-icp, `moss_dimos/lidar_odometry.py`), the pose source:- the encoders give metres only once `MOSS_TICKS_PER_M` is set, and no IMU- feeds the odometry;+ the encoders give metres only once `MOSS_TICKS_PER_M` is set, and the+ RealSense's gyro gives the odometry its rotation prior (below);- the 2D scored costmap (`moss_dimos/costmap2d.py`), where the lidar writes obstaclesand the depth camera adds the ones below the scan plane. An obstacle becomes awall once seen from two places 10 cm apart, never from one spot. The lidar's@@ -80,11 +80,14 @@ firmware 300 ms after the last drive.table top the rover has turned away from keeps its wall until the camera looksat that spot again and sees nothing. The knobs are `MOSS_HIT_CAP`,`MOSS_FREE_FLOOR` and `MOSS_RAY_MAX_M` (below);-- an experiment, off by default: the lidar odometry's rotation prior from the RealSense's- gyro (`MOSS_GYRO=1`): a full-power pivot turns the rover 25 degrees between two scans,- more than the constant-velocity prior follows, and the map drifts; the gyro would say- where the rover turned, but the IMU pipeline fails to open on the rover today and takes- the camera down with it;+- the lidar odometry's rotation prior from the RealSense's gyro, on with `MOSS_IMU` (the+ default): the IMU read in the camera's own process gives the yaw rate at 200 Hz, and each+ registration starts from the yaw integrated since the previous revolution. A full-power+ pivot turns the rover 25 degrees between two scans, more than the constant-velocity prior+ follows, and the map would drift. `MOSS_GYRO=0` turns it off; with `MOSS_IMU=0`,+ `MOSS_GYRO=1` is refused with a warning (it would open dimOS's second IMU pipeline, which+ fails on the rover and takes the camera down), and `MOSS_GYRO_FORCE=1` builds it anyway,+ as an experiment ([imu.md](imu.md#the-gyro-and-the-odometry));- the sound module (`moss_dimos/sounds.py`): a pack of short synthesized cues in`assets/sounds` played through the robot user's PulseAudio session (a Bluetoothspeaker once connected, the default sink otherwise) on confirmed events only: the@@ -93,7 +96,37 @@ firmware 300 ms after the last drive.Each cue has a cooldown and the player keeps a gap between cues, so the rovernever chatters. `MOSS_SOUNDS=0` leaves it out, `MOSS_SOUND_VOLUME` (0 to 1) and`MOSS_SOUND_SINK` (a PulseAudio sink name) tune it; a stack launched as a system- service has no audio session and stays silent;+ service has no audio session and stays silent. A Bluetooth speaker sleeps its link+ after a few tens of seconds of silence, and a short cue sent into a sleeping link is+ lost (a silent clip every 240 s did not keep it awake). The module does two things+ against it: it plays a silent clip every `MOSS_SOUND_KEEP_AWAKE_S` seconds (15; 0 =+ off), and it plays 0.3 s of silence in front of every cue (`MOSS_SOUND_PREROLL_S`, up+ to 2 s; 0 = off), meant to wake the link on the silence rather than on the cue. The+ cues with their silence are WAV copies written once into `MOSS_SOUND_CACHE` (default+ `<tempdir>/moss_sound_cache`); a cue whose copy cannot be written plays as it is. The+ module's first log line gives the period and the pre-roll. One check on the robot:+ `pactl list short modules | grep suspend`. When it shows `module-suspend-on-idle`,+ PulseAudio suspends the sink 5 s after each clip (its default timeout), whatever the+ keep-awake period. After a reboot the speaker comes back through a systemd user unit,+ `tools/moss-jbl.service`, which runs `tools/moss-jbl-connect.sh`: `bluetoothctl+ connect`, up to `MOSS_JBL_TRIES` tries (120) with 5 s between tries, then the+ speaker's PulseAudio sink becomes the default sink, at the volume PulseAudio remembers+ for it; a try that connects but finds no sink connects again on the next one. It gives+ up after about ten minutes of waits (about twenty with the speaker off, each connect+ waiting out its page timeout). The speaker is paired and trusted once with+ `bluetoothctl`; its address lives only in `~/.local/state/moss/jbl.env`. Install from+ the checkout as the robot's user, whose user manager starts at boot (`sudo loginctl+ enable-linger $USER`, once):++ ```sh+ mkdir -p ~/.config/systemd/user ~/.local/state/moss+ echo 'MOSS_JBL_MAC=<speaker address>' > ~/.local/state/moss/jbl.env+ sed -e "s|MOSS_DIR|$PWD|g" tools/moss-jbl.service > ~/.config/systemd/user/moss-jbl.service+ systemctl --user daemon-reload && systemctl --user enable moss-jbl && systemctl --user restart --no-block moss-jbl+ ```++ `--no-block` returns at once, the script runs on in the background;+ `journalctl --user -u moss-jbl` says when it connected, or why it gave up;- the RealSense colour stream at 640x480, 5 fps, carried as JPEG on the bus, and itsdepth aligned to colour at the same rate, which `lidar_odometry` turns into obstaclepoints from 12 cm (the camera's close-range depth) to 3 m, drawn in amber on the map@@ -428,9 +461,9 @@ $ sudo systemctl daemon-reload && sudo systemctl enable --now lcm-loopback- The geometry and the base numbers are placeholders until measured: groundspeed, ticks per metre, track width, lidar pose, the footprint and thestatic-friction floor. [base.md](base.md) says how to measure the base's.-- The lidar odometry runs without a gyro prior (`use_gyro_prior=False`); the- D455F IMU could feed it once the camera mount is measured, and there is no- switch for it.+- The gyro prior reads the yaw rate on one axis of the camera's frame+ (`gyro_axis="-y"`), the right one for the level, upright mount: a camera+ mounted upside down flips its sign, and there is no switch for the axis.- Every launch starts a fresh map: no map is saved between runs and there areno keep-out zones. The recording keeps the run.- A recording is not replayed through the stack; the SQLite file is readablediff --git a/docs/imu.md b/docs/imu.mdindex e0972b3..2d3f251 100644--- a/docs/imu.md+++ b/docs/imu.md@@ -10,8 +10,8 @@ short, hard deceleration along the direction of travel. The RealSense on thenose carries an IMU, and `MOSS_IMU=1` turns its decelerations into contacts onthe same `bump` stream.-It is opt-in (default off) until a stationary launch on the robot shows-colour, depth and the IMU alive together (below).+It is on by default since a stationary launch on the robot showed colour,+depth and the IMU alive together (below); `MOSS_IMU=0` turns it off.## The IMU@@ -27,7 +27,7 @@ Two facts decide how it must be opened:* dimOS's `RealSenseCamera` with `enable_imu=True` opens a SECOND pipeline forthe motion module (`_start_imu`). On the rover that pipeline fails ("Nodevice connected") and takes colour and depth down with it. That is why- `MOSS_GYRO=1` alone stays an experiment.+ the gyro prior never takes that path unless forced (below).So `moss_dimos/realsense_imu.py` defines `MossRealSense`, the same module withthe same outputs, which changes one method: `_start_imu` opens the motion@@ -66,6 +66,23 @@ and the mean accel on z goes negative (about -1.7 m/s^2 at 10 degrees). If itgoes positive, the camera is mounted the other way round: set`MOSS_BUMP_AXIS=-z`.+## The gyro and the odometry++The same IMU gives the lidar odometry its rotation prior. On the robot the+`imu` messages from the camera's own process reach `LidarOdometry` at about+200 Hz; it integrates the yaw rate (`-gyro.y`) from one lidar revolution to+the next, the next registration starts from that yaw (the translation stays+kiss-icp's constant-velocity model), and the integral starts again from+zero. A full-power pivot (254 deg/s measured on the floor) turns the rover 25+degrees between two scans, more than the constant-velocity prior follows; the+gyro says where the rover turned. A revolution with no gyro sample since the+last one falls back to the constant-velocity model. Three switches: with+`MOSS_IMU` on (the default) the prior is on, and the odometry's start line+says `prior: gyro=True`; `MOSS_GYRO=0` turns it off at any time; with+`MOSS_IMU=0`, `MOSS_GYRO=1` is refused with a warning, because the gyro would+then come from dimOS's second IMU pipeline (above), and `MOSS_GYRO_FORCE=1`+builds it anyway, the experiment path.+## The rule`moss_dimos/bump_imu.py`, class `ImuContactDetector` (pure, benched with known@@ -97,11 +114,12 @@ IMU contact: forward -4.8 m/s^2 (threshold 4.0) while commanded L=+70% R=+60%````bump` is the stream the coordinator's stall guard and the explorer's back-off-already publish on, so the same three listeners react: the planner's escape+already publish on, so the same listeners react: the planner's escape(stop, 0.20 m in reverse, the goal abandoned; a second contact during anescape stops dead), the costmap's contact memory (the band ahead becomes a-wall) and the sounds (`bump_surprise`, at the impact rather than a second-later). The stall guard stays on: a contact with the tracks frozen can be+wall), the sounds (`bump_surprise`, at the impact rather than a second+later) and the lidar odometry, which drops the shaken revolution that+follows ([below](#a-contact-and-the-map)). The stall guard stays on: a contact with the tracks frozen can bereported twice, by the IMU at the impact and by the encoders a second later.The cockpit shows each contact in its decision feed@@ -125,6 +143,90 @@ full-power pivot. Held steady, the high-pass removes it; its onset and its endare what the signature must look at, with the gyro columns of the CSV next to`hp` (a figure from the geometry, not from a recording).+## A contact and the map++A contact shakes the lidar as well as the chassis. Measured on the robot,+during the drive into the box turned 45 degrees: in the revolution swept+during the contact the lidar odometry's yaw jumped +6.4 degrees while the+gyro integral moved +0.5 degrees, and that revolution carried 97 points where+its neighbours carried about 300. The revolutions after it registered at the+wrong heading and kept it: one shaken sweep, one jump of the whole map.++So `LidarOdometry` listens to `bump` too (the same stream, whoever publishes+on it) and stamps the time of each contact. Then:++1. **The shaken sweep is dropped.** A revolution that arrives within+ `MOSS_CONTACT_WINDOW_S` (0.4 s) after a contact and carries fewer than+ `MOSS_CONTACT_DROP_RATIO` (0.5) times the median point count of the last+ 20 registered revolutions is not registered. The pose published for it is+ the last one turned by the gyro integral since then (prior on), or the+ last one unchanged (prior off, or no gyro sample since the last+ revolution: the log then says `pose held (no gyro prior)` or `pose held+ (no gyro sample since the last revolution)`); kiss-icp's map and adaptive+ threshold do not see it, and its cloud never reaches the costmap. One line+ in the log:++ ```+ lidar odom contact: revolution dropped (97 pts, median 300), pose carried by the gyro; dropped by contacts so far: 1+ ```++ A full revolution inside the window is registered as usual: only a thin+ one counts as shaken.++2. **The relocation.** The next `MOSS_RELOC_SWEEPS` (5) registered+ revolutions search wider: their sigma (the kernel, and the correspondence+ distance of 3 sigma) is the adaptive one times `MOSS_RELOC_SIGMA_GAIN`+ (2.0). The prior stays what it is: the gyro's rotation with the prior on,+ the constant-velocity translation. The registration starts from the+ gyro's heading and has room to pull the map back into place. Two lines+ frame it:++ ```+ lidar odom contact: relocating over 5 revolutions (sigma x2.0)+ lidar odom contact: relocation done over 5 revolutions, the registration corrected the yaw by +0.6 deg in total+ ```++ A second contact during a relocation starts its count again.++The knobs are read when the module is imported (a value that does not parse+keeps the default, a value outside its range takes the nearest bound, both+said in the log), and the odometry says them at start, on the line after+`lidar odometry up`:++```+lidar odometry contacts: a revolution within 0.4 s of a bump under 0.5 x the median point count is dropped; then 5 revolutions register with sigma x2+```++| Variable | Default | What |+|---|---|---|+| `MOSS_CONTACT_WINDOW_S` | 0.4 | seconds after a contact during which a thin revolution counts as shaken, 0 to 5 |+| `MOSS_CONTACT_DROP_RATIO` | 0.5 | a revolution under this share of the median point count is dropped, 0 to 1; `0` never drops |+| `MOSS_RELOC_SWEEPS` | 5 | registered revolutions after a contact that search wider, 0 to 50; `0` turns the relocation off |+| `MOSS_RELOC_SIGMA_GAIN` | 2.0 | their sigma times this, 1 to 10 |++`MOSS_CONTACT_DROP_RATIO=0 MOSS_RELOC_SWEEPS=0`: the odometry ignores `bump`, as before.++The contact lines start with `lidar odom` and so appear in+`tools/moss-fly.sh log`. `benches/bench_lidar_odometry_cold.py` section G+holds the mechanism on known numbers: at rest after 10 revolutions of 300+points, a bump and a revolution of 90 points turned 6 degrees leave the yaw+at the gyro's +0.40 degrees and log the drop; the next 5 full revolutions+register with sigma 0.40 m and the 6th with 0.20 m; with no bump, 0.5 s after+it, or with `MOSS_CONTACT_DROP_RATIO=0`, the same revolution registers at++6.0 degrees. Reloaded with `MOSS_RELOC_SWEEPS=3 MOSS_RELOC_SIGMA_GAIN=3+MOSS_CONTACT_WINDOW_S=0.05`, 3 revolutions register at 0.60 m, and a thin+revolution 0.1 s after the bump registers. `benches/bench_moss_blueprints_cold.py`+checks that `bump` reaches the odometry in moss-nav and moss-explore, on the+costmap's stream.++What it does not cover: a shaken sweep that keeps its point count (the drop+reads the count only); a shaken sweep whose revolution is handled before+`handle_bump` stamps the contact (the window only looks forward from the+stamp, so that sweep is registered at the wrong heading, the measured +6.4+degree case, and the relocation the late stamp arms starts from that+heading); and a contact nothing publishes on `bump`. The robot replay will+show how often a sweep beats its bump.+## Knobs| Variable | Default | What |@@ -134,7 +236,8 @@ are what the signature must look at, with the gyro columns of the CSV next to| `MOSS_BUMP_AXIS` | `+z` | the forward axis of the camera's frame, x, y or z with a sign || `MOSS_BUMP_DEBOUNCE_S` | 0.7 | seconds of silence after a contact, 0 to 10 || `MOSS_IMU_LOG` | unset | a CSV path: every sample is appended (below) |-| `MOSS_GYRO` | off | the gyro prior of the lidar odometry; with `MOSS_IMU=1` it reads the in-process IMU |+| `MOSS_GYRO` | on with `MOSS_IMU` | the gyro prior of the lidar odometry from the in-process IMU (above); `0` turns it off; with `MOSS_IMU=0`, `1` is refused with a warning |+| `MOSS_GYRO_FORCE` | off | `1` with `MOSS_IMU=0 MOSS_GYRO=1`: the prior on dimOS's second IMU pipeline, an experiment |They are read when the blueprint is built (the build log says`MOSS blueprint: IMU contacts on bump, forward axis +z, threshold 4 m/s^2, ...`);diff --git a/moss_dimos/blueprints.py b/moss_dimos/blueprints.pyindex ddc9a36..6507d9b 100644--- a/moss_dimos/blueprints.py+++ b/moss_dimos/blueprints.py@@ -34,9 +34,11 @@ Switches (env, read when moss-nav / moss-explore is built; robot_profile.env_onparses them: 0, false, no or off = off, any other value = on, unset = the default):MOSS_CAMERA=0 no RealSense (default on: colour 640x480 @ 5 fps, JPEG on the bus, plus depth alignedto colour at the same rate, turned into map obstacles by lidar_odometry)- MOSS_GYRO=1 gyro prior for the lidar odometry from the RealSense's IMU (default OFF: alone, it uses- dimOS's second IMU pipeline, which fails to open on the rover and takes the camera down- with it; an experiment. With MOSS_IMU=1 the gyro comes from the in-process motion module)+ MOSS_GYRO=0 no gyro prior for the lidar odometry (default ON with MOSS_IMU: each registration starts+ from the yaw the RealSense's gyro integrated since the last revolution, read in the+ camera's own process). With MOSS_IMU=0 the gyro would come from dimOS's second IMU+ pipeline, which fails to open on the rover and takes the camera down with it: MOSS_GYRO=1+ is then refused with a warning, and MOSS_GYRO_FORCE=1 builds it anyway (an experiment)MOSS_IMU=0 no IMU contacts (default ON: the RealSense's IMU is read inside the camera's ownprocess, colour, depth and IMU proven alive together on the robot; a deceleration againstthe commanded direction publishes bump). Knobs: MOSS_BUMP_ACCEL (default 4.0 m/s^2),@@ -437,10 +439,25 @@ def _common_parts(ports: dict, profile: RobotProfile) -> list:from moss_dimos.lidar_odometry import LidarOdometryfrom moss_dimos.rplidar_c1 import RPLidarC1- # MOSS_GYRO=1 is an experiment: dimOS's RealSense module opens a second pipeline for the IMU,- # which fails with 'No device connected' on the rover (the colour and depth streams then never- # start either), so the gyro prior is OFF unless asked for- gyro = robot_profile.env_on("MOSS_GYRO", False) and robot_profile.env_on("MOSS_CAMERA", True)+ # the rotation prior of the lidar odometry: the RealSense's gyro, read in the camera's own process+ # with the IMU (MOSS_IMU, on by default), so MOSS_GYRO follows MOSS_IMU unless set. Without MOSS_IMU+ # the gyro would come from dimOS's second IMU pipeline, which fails with 'No device connected' on the+ # rover (colour and depth then never start either): refused unless MOSS_GYRO_FORCE=1, an experiment+ has_camera = robot_profile.env_on("MOSS_CAMERA", True)+ in_process_imu = has_camera and robot_profile.env_on("MOSS_IMU", True)+ gyro = robot_profile.env_on("MOSS_GYRO", in_process_imu)+ if gyro and not has_camera:+ _logger.warning("MOSS blueprint: MOSS_GYRO needs the RealSense and MOSS_CAMERA is off: no gyro prior")+ gyro = False+ elif gyro and not in_process_imu:+ if robot_profile.env_on("MOSS_GYRO_FORCE", False):+ _logger.warning("MOSS blueprint: MOSS_GYRO_FORCE=1 with MOSS_IMU=0: the gyro prior on dimOS's second "+ "IMU pipeline, an experiment (on the rover it fails to open and takes the camera down)")+ else:+ _logger.warning("MOSS blueprint: MOSS_GYRO=1 with MOSS_IMU=0 refused (dimOS's second IMU pipeline "+ "fails on the rover and takes the camera down): no gyro prior. MOSS_IMU=1 gives it "+ "from the camera's own process; MOSS_GYRO_FORCE=1 is the experiment")+ gyro = False# MOSS_DESKEW=1 is an experiment too: kiss-icp's deskew (each point moved by its share of the motion# prior) dies on the rover at its first thread, and the odometry loop with itdeskew = robot_profile.env_on("MOSS_DESKEW", False)@@ -448,10 +465,9 @@ def _common_parts(ports: dict, profile: RobotProfile) -> list:_coordinator_blueprint(_moss_base(address=ports["base"])),_gamepad_part(),RPLidarC1.blueprint(port=ports["lidar"], baudrate=LIDAR_BAUDRATE, frame_id="lidar_link"),- # no IMU wired: kiss-icp on its constant-velocity prior- # the rotation prior: the RealSense's gyro when MOSS_GYRO is on (default), which holds the- # registration through a full-power pivot (254 deg/s measured on the floor: 25 deg between- # two scans, where the constant-velocity prior let the map drift); constant velocity otherwise+ # the rotation prior: the RealSense's gyro when MOSS_GYRO is on (default): a full-power pivot+ # (254 deg/s measured on the floor) turns 25 deg between two scans, more than the constant-velocity+ # prior follows (the map drifted); constant velocity otherwiseLidarOdometry.blueprint(use_gyro_prior=gyro, deskew=deskew),MossCostMap.blueprint(),]diff --git a/moss_dimos/lidar_odometry.py b/moss_dimos/lidar_odometry.pyindex e1e10b3..0f7ecbc 100644--- a/moss_dimos/lidar_odometry.py+++ b/moss_dimos/lidar_odometry.py@@ -15,6 +15,17 @@ sanity signal. Rotation without a gyro is the known weak spot: on C1 scans of~340 points, kiss-icp alone was measured under-estimating turns by 20-35 %.Bench the turn tracking before trusting long runs.+A contact shakes the lidar: the revolution swept during it comes in with a+fraction of its points and registers at a wrong heading (measured: +6.4 deg+in one revolution of 97 points where the gyro moved +0.5 deg), and every+later revolution keeps that heading. So a contact on `bump` (the IMU's+BumpImu, the base's stall guard, the explorer's back-off) is remembered: a+revolution within MOSS_CONTACT_WINDOW_S of it that carries fewer than+MOSS_CONTACT_DROP_RATIO times the running median point count is not+registered (the pose is carried by the gyro, or held without it, and its+cloud never reaches the map), and the next MOSS_RELOC_SWEEPS registered+revolutions search with their sigma times MOSS_RELOC_SIGMA_GAIN.+Frames and heights:* `world` is kiss-icp's own frame: every run starts at the origin, facing +x.* `odom` is published on the floor plane (z = 0) - see handle_pointcloud.@@ -33,6 +44,7 @@ costmap2d maps the camera obstacles next to the lidar returns.Streamspointcloud : In[PointCloud2] one revolution, lidar_link (rplidar_c1.py)imu : In[Imu] gyro (angular_velocity) for the optional rotation prior+ bump : In[Bool] a contact: the shaken revolution after it is droppedcoordinator_joint_state : In[JointState] base/vx, base/vy, base/wz positions = wheel odometry, logged onlydepth_image : In[Image] optional depth camera, DEPTH16 mm, aligned to colourcamera_info : In[CameraInfo] its colour intrinsics@@ -44,6 +56,7 @@ Streamsfrom __future__ import annotationsimport math+import osimport threadingimport timefrom typing import Any@@ -64,6 +77,7 @@ from dimos.msgs.sensor_msgs.JointState import JointStatefrom dimos.msgs.sensor_msgs.PointCloud2 import PointCloud2from dimos.msgs.tf2_msgs.TFMessage import TFMessagefrom dimos.utils.logging_config import setup_logger+from dimos_lcm.std_msgs import Bool # the SAME Bool class as BumpImu / the coordinator / the costmap: one 'bump' stream typefrom moss_dimos.robot_profile import RobotProfile, current as _current_profile@@ -80,6 +94,34 @@ OBSTACLE_MAX_M = 3.0 # camera obstacles are trusted up to this range;OBSTACLE_Z_M = (0.12, 1.30) # world z band the camera turns into floor obstacles. Upper bound 1.30, not 0.70: a table top is a BLOCK - the rover goes around tables, never between the legs+def _env_float(name: str, default: float, lo: float, hi: float) -> float:+ """A number from the environment, read once at import. Unset or empty ->+ `default`; not a number -> `default`, said in the log; outside [lo, hi]+ -> the nearest bound, said in the log."""+ raw = os.environ.get(name, "").strip()+ if not raw:+ return default+ try:+ value = float(raw)+ except ValueError:+ logger.warning(f"lidar odometry: {name}={raw!r} is not a number - using {default}")+ return default+ if not lo <= value <= hi:+ bounded = hi if value > hi else lo # below lo, or nan+ logger.warning(f"lidar odometry: {name}={raw!r} is outside [{lo}, {hi}] - using {bounded}")+ return bounded+ return value+++# A contact (`bump`) shakes the lidar: the revolution swept during it comes in thin and+# registers at a wrong heading, and the map jumps. These four decide what happens next.+CONTACT_WINDOW_S = _env_float("MOSS_CONTACT_WINDOW_S", 0.4, 0.0, 5.0) # a revolution this soon after a contact may be the shaken one+CONTACT_DROP_RATIO = _env_float("MOSS_CONTACT_DROP_RATIO", 0.5, 0.0, 1.0) # ... and is dropped under this share of the median point count (0 = never)+RELOC_SWEEPS = int(round(_env_float("MOSS_RELOC_SWEEPS", 5, 0, 50))) # registered revolutions after a contact that search wider (0 = none)+RELOC_SIGMA_GAIN = _env_float("MOSS_RELOC_SIGMA_GAIN", 2.0, 1.0, 10.0) # their sigma (kernel, and 3 sigma of correspondence distance) times this+COUNT_HISTORY = 20 # registered revolutions in the running median of the point count++def _profile() -> RobotProfile:"""The geometry the tf, the lidar lift and the depth projection use, readat call time so a MOSS_* override takes effect without a restart."""@@ -137,6 +179,7 @@ def split_floor_and_obstacles(bx: np.ndarray, by: np.ndarray, bz: np.ndarray,class LidarOdometry(Module):pointcloud: In[PointCloud2]imu: In[Imu]+ bump: In[Bool] # a contact (BumpImu, the stall guard, the explorer's back-off): the shaken revolution is droppedcoordinator_joint_state: In[JointState]depth_image: In[Image] # depth camera (aligned to colour), DEPTH16 mmcamera_info: In[CameraInfo] # colour intrinsics (= aligned depth intrinsics)@@ -186,6 +229,16 @@ class LidarOdometry(Module):self._depth_n = 0self._depth_pts_last = 0self._pending_cam_pts = None+ # contacts: the last one's monotonic stamp, the point counts of the last+ # registered revolutions, and the relocation that follows a contact+ self._contact_t: float | None = None+ self._dropped_contact = 0 # revolutions dropped as shaken by a contact+ self._counts: list[int] = []+ self._reloc_armed_t: float | None = None # the contact stamp that armed the current relocation+ self._reloc_left = 0 # registered revolutions still to search wider+ self._reloc_n = 0 # ... done so far in this relocation+ self._reloc_yaw = 0.0 # the yaw the registration corrected over them, rad+ self._reloc_announce = False# ── lifecycle ──────────────────────────────────────────────────────@rpc@@ -208,6 +261,9 @@ class LidarOdometry(Module):logger.info(f"lidar odometry up (kiss-icp, voxel {self.voxel_size_m} m, range "f"{self.min_range_m}-{self.max_range_m} m, prior: gyro={self.use_gyro_prior} "f"axis {self.gyro_axis}, wheels NEVER) -> {self.world_frame}")+ logger.info(f"lidar odometry contacts: a revolution within {CONTACT_WINDOW_S:g} s of a bump under "+ f"{CONTACT_DROP_RATIO:g} x the median point count is dropped; then {RELOC_SWEEPS} "+ f"revolutions register with sigma x{RELOC_SIGMA_GAIN:g}")@rpcdef stop(self) -> None:@@ -261,6 +317,13 @@ class LidarOdometry(Module):self._gyro_seen = Trueself._gyro_last_ts = ts+ async def handle_bump(self, msg: Bool) -> None:+ """A contact: stamped, nothing else here. The next revolutions read the+ stamp (handle_pointcloud): the shaken one is dropped, the relocation+ is armed."""+ if bool(getattr(msg, "data", False)):+ self._contact_t = time.monotonic()+async def handle_coordinator_joint_state(self, msg: JointState) -> None:names = list(msg.name); pos = list(msg.position)try:@@ -371,6 +434,51 @@ class LidarOdometry(Module):self._prior_used = "+".join(used) or "cv"return _se2(dx, dy, dyaw)+ # ── contacts ───────────────────────────────────────────────────────+ def _arm_relocation(self) -> None:+ """A contact not seen yet arms the relocation: the next RELOC_SWEEPS+ registered revolutions search wider. A contact during a relocation+ starts its count again; the yaw correction keeps adding up."""+ stamp = self._contact_t+ if stamp is None or stamp == self._reloc_armed_t:+ return+ self._reloc_armed_t = stamp+ if RELOC_SWEEPS > 0:+ self._reloc_left = RELOC_SWEEPS+ self._reloc_announce = True++ def _shaken(self, n_pts: int, t0: float) -> float | None:+ """The running median point count when this revolution is a shaken+ sweep to drop (within CONTACT_WINDOW_S of a contact, under+ CONTACT_DROP_RATIO times the median of the last registered ones),+ else None."""+ stamp = self._contact_t+ if stamp is None or t0 - stamp > CONTACT_WINDOW_S or not self._counts:+ return None+ median = float(np.median(self._counts))+ return median if n_pts < CONTACT_DROP_RATIO * median else None++ def _carry(self, k, n_pts: int, median: float) -> np.ndarray:+ """The pose for a dropped revolution: the last one turned by the gyro+ integral when the prior is on and fed, else the last one unchanged.+ kiss-icp's last pose follows it (the next prior starts from there);+ its map and its threshold are not touched."""+ last = np.asarray(k.last_pose)+ turned = self.use_gyro_prior and self._gyro_seen+ pose = last @ _se2(0.0, 0.0, self._gyro_acc) if turned else last+ k.last_pose = pose+ self._gyro_acc, self._gyro_seen = 0.0, False+ self._dropped_contact += 1+ if turned:+ how = "pose carried by the gyro"+ elif self.use_gyro_prior: # the prior is on but the imu stream went quiet+ how = "pose held (no gyro sample since the last revolution)"+ else:+ how = "pose held (no gyro prior)"+ logger.warning(f"lidar odom contact: revolution dropped ({n_pts} pts, median {median:.0f}), {how}; "+ f"dropped by contacts so far: {self._dropped_contact}")+ return pose+# ── the work ───────────────────────────────────────────────────────async def handle_pointcloud(self, msg: PointCloud2) -> None:out = msg.as_numpy()@@ -381,25 +489,15 @@ class LidarOdometry(Module):thick = np.concatenate([pts, pts + [0, 0, PLANE_THICKNESS_M], pts - [0, 0, PLANE_THICKNESS_M]])with self._lock:k = self._kiss- prior = self._prior_delta()- frame = k.preprocessor.preprocess(thick, np.tile(sweep_times(pts), 3) if self.deskew else np.zeros(len(thick)), prior)- source, frame_down = k.voxelize(frame)- sigma = k.adaptive_threshold.get_threshold()- initial_guess = np.asarray(k.last_pose) @ prior- try:- new_pose = self._register(k, source, initial_guess, sigma)- except RuntimeError as exc:- self._dropped += 1- logger.warning(f"lidar odometry: registration failed twice, revolution dropped ({exc}); "- f"dropped so far: {self._dropped}")- return- corr = np.linalg.inv(initial_guess) @ np.asarray(new_pose)- k.adaptive_threshold.update_model_deviation(corr)- k.local_map.update(frame_down, new_pose)- k.last_delta = np.linalg.inv(np.asarray(k.last_pose)) @ new_pose- k.last_pose = new_pose- # consume the priors- self._gyro_acc, self._gyro_seen = 0.0, False+ self._arm_relocation()+ median = self._shaken(len(pts), t0)+ shaken = median is not None+ if shaken:+ new_pose = self._carry(k, len(pts), median)+ else:+ new_pose = self._register_revolution(k, pts, thick)+ if new_pose is None:+ returnpose = np.asarray(new_pose)R, t = pose[:3, :3], pose[:3, 3]x, y, yaw = float(t[0]), float(t[1]), math.atan2(R[1, 0], R[0, 0])@@ -418,14 +516,17 @@ class LidarOdometry(Module):# goal FOREVER. The lidar height lives in the tf child and in the# world-cloud transform, never in the pose.self.odom.publish(PoseStamped(ts, self.world_frame, position=Vector3(x, y, 0.0), orientation=q))- cam = self._pending_cam_pts- if cam is not None and time.monotonic() - cam[1] < 0.5:- world_pts = np.vstack([world_pts, cam[0]])- self.lidar.publish(PointCloud2.from_numpy(world_pts.astype(np.float32), frame_id=self.world_frame, timestamp=ts))+ if not shaken: # a shaken sweep: its pose goes out, its cloud never reaches the map+ cam = self._pending_cam_pts+ if cam is not None and time.monotonic() - cam[1] < 0.5:+ world_pts = np.vstack([world_pts, cam[0]])+ self.lidar.publish(PointCloud2.from_numpy(world_pts.astype(np.float32), frame_id=self.world_frame, timestamp=ts))self.tf.publish(TFMessage(Transform(translation=Vector3(x, y, 0.0), rotation=q, frame_id=self.world_frame, child_frame_id=self.base_frame, ts=ts),Transform(translation=Vector3(0.0, 0.0, lidar_h), rotation=Quaternion(0, 0, 0, 1),frame_id=self.base_frame, child_frame_id=self.lidar_frame, ts=ts)))+ if shaken:+ returnself._n += 1self._last_ms = (time.monotonic() - t0) * 1000.0if t0 - self._last_log >= self.log_every_s:@@ -436,3 +537,47 @@ class LidarOdometry(Module):f"{self._depth_pts_last} pts) | gyro integral "f"x={g[0]:+.1f} y={g[1]:+.1f} z={g[2]:+.1f}deg | wheels "+ (f"x={w[0]:+.3f} y={w[1]:+.3f} th={math.degrees(w[2]):+.1f}deg" if w else "none"))++ def _register_revolution(self, k, pts: np.ndarray, thick: np.ndarray) -> np.ndarray | None:+ """Register one revolution into kiss-icp and update its state; the new+ pose, or None when the registration failed twice (revolution dropped).+ Called under the lock. During a relocation the sigma is RELOC_SIGMA_GAIN+ times the adaptive one, from the same prior (the gyro's heading when+ the prior is on)."""+ prior = self._prior_delta()+ frame = k.preprocessor.preprocess(thick, np.tile(sweep_times(pts), 3) if self.deskew else np.zeros(len(thick)), prior)+ source, frame_down = k.voxelize(frame)+ sigma = k.adaptive_threshold.get_threshold()+ relocating = self._reloc_left > 0+ if relocating:+ sigma *= RELOC_SIGMA_GAIN # after a contact: search wider, from the prior's heading+ if self._reloc_announce:+ self._reloc_announce = False+ logger.info(f"lidar odom contact: relocating over {self._reloc_left} revolutions "+ f"(sigma x{RELOC_SIGMA_GAIN:.1f})")+ initial_guess = np.asarray(k.last_pose) @ prior+ try:+ new_pose = self._register(k, source, initial_guess, sigma)+ except RuntimeError as exc:+ self._dropped += 1+ logger.warning(f"lidar odometry: registration failed twice, revolution dropped ({exc}); "+ f"dropped so far: {self._dropped}")+ return None+ corr = np.linalg.inv(initial_guess) @ np.asarray(new_pose)+ k.adaptive_threshold.update_model_deviation(corr)+ k.local_map.update(frame_down, new_pose)+ k.last_delta = np.linalg.inv(np.asarray(k.last_pose)) @ new_pose+ k.last_pose = new_pose+ # consume the priors+ self._gyro_acc, self._gyro_seen = 0.0, False+ self._counts.append(len(pts))+ del self._counts[:-COUNT_HISTORY]+ if relocating:+ self._reloc_yaw += math.atan2(corr[1, 0], corr[0, 0])+ self._reloc_n += 1+ self._reloc_left -= 1+ if self._reloc_left == 0:+ logger.info(f"lidar odom contact: relocation done over {self._reloc_n} revolutions, "+ f"the registration corrected the yaw by {math.degrees(self._reloc_yaw):+.1f} deg in total")+ self._reloc_n, self._reloc_yaw = 0, 0.0+ return new_posediff --git a/moss_dimos/sound_pack/player.py b/moss_dimos/sound_pack/player.pyindex 997ee5a..9fc5bca 100644--- a/moss_dimos/sound_pack/player.py+++ b/moss_dimos/sound_pack/player.py@@ -2,11 +2,21 @@emit() queues a cue, never drives the robot, and never waits for playback.Backend completion means the playback process exited, not proof of audibility.++Pre-roll: every cue is played with MOSS_SOUND_PREROLL_S of silence glued in+front of it (default 0.3 s, 0 = off), meant to let a Bluetooth link that went+to sleep wake on the silence rather than on the cue's first milliseconds. The glued+copies are WAV files written once per asset into MOSS_SOUND_CACHE (default+<tempdir>/moss_sound_cache) by the worker before it plays anything; an asset+whose copy cannot be written plays as it is, said once through the log."""import argparsefrom collections import OrderedDict+import hashlibimport json+import loggingimport math+import osfrom pathlib import Pathimport queueimport random@@ -15,8 +25,50 @@ import subprocessimport tempfileimport threadingimport time+import waveROOT=Path(__file__).resolve().parent+PREROLL_S=.3 # silence in front of every cue (MOSS_SOUND_PREROLL_S); 0 = off+PREROLL_MAX_S=2.0 # the longest pre-roll (every cue starts that much later): a larger MOSS_SOUND_PREROLL_S is clamped++def env_seconds(name, default, hi, env=None):+ """A duration in seconds from the environment: unset, empty, not a number or+ nan -> default; zero or below -> 0 (off); above hi -> hi."""+ raw=str((os.environ if env is None else env).get(name,'')).strip()+ try:value=float(raw)+ except ValueError:return float(default)+ if value!=value:return float(default)+ return max(0.0,min(float(hi),value))++def sound_cache_dir(env=None):+ """MOSS_SOUND_CACHE when set, else <tempdir>/moss_sound_cache."""+ raw=str((os.environ if env is None else env).get('MOSS_SOUND_CACHE','')).strip()+ return Path(raw).expanduser() if raw else Path(tempfile.gettempdir())/'moss_sound_cache'++def preroll_wav(src, seconds, cache_dir):+ """The path of `src` with `seconds` of silence in front of it, same channels, rate+ and sample width, written into cache_dir when it is not there already (the name+ carries the source's path, size and mtime, so an edited asset gets a new copy).+ Written to a temporary name then renamed: a reader never sees half a file.+ Raises OSError, EOFError or wave.Error when it cannot."""+ src=Path(src);st=src.stat()+ tag=hashlib.sha1(f'{src.resolve()}|{st.st_size}|{st.st_mtime_ns}'.encode()).hexdigest()[:12]+ out=Path(cache_dir)/f'{src.stem}-{tag}-pre{round(seconds*1000)}ms.wav'+ if out.is_file():return out+ with wave.open(str(src),'rb') as w:+ channels,width,rate=w.getnchannels(),w.getsampwidth(),w.getframerate()+ frames=w.readframes(w.getnframes())+ silence=(b'\x80' if width==1 else b'\x00')*(round(seconds*rate)*channels*width) # 8-bit WAV is unsigned: its zero is 0x80+ Path(cache_dir).mkdir(parents=True,exist_ok=True)+ tmp=out.with_name(f'{out.name}.{os.getpid()}.{threading.get_ident()}.tmp')+ try:+ with wave.open(str(tmp),'wb') as w:+ w.setnchannels(channels);w.setsampwidth(width);w.setframerate(rate)+ w.writeframes(silence+frames)+ os.replace(tmp,out)+ finally:+ if tmp.exists():tmp.unlink()+ return outdef playback_command(path, backend='auto', target=None, volume=.65):if not math.isfinite(volume) or not 0 <= volume <= 1:@@ -37,7 +89,7 @@ def playback_command(path, backend='auto', target=None, volume=.65):return cmd+[str(path)]class MossSoundPlayer:- def __init__(self, root=ROOT, config=None, dry_run=False):+ def __init__(self, root=ROOT, config=None, dry_run=False, log=None):self.root=Path(root).resolve()self.manifest=json.loads((self.root/'manifest.json').read_text())self.config=json.loads((self.root/'config.json').read_text())@@ -49,6 +101,12 @@ class MossSoundPlayer:rule=dict(rule);rule.update(self.config.get('events',{}).get(name,{}))self.rules[name]=ruleself.dry_run=dry_run;self.muted=bool(self.config['mute']);self.closed=False+ pre=self.config.get('preroll_s')+ self.preroll_s=env_seconds('MOSS_SOUND_PREROLL_S',PREROLL_S,PREROLL_MAX_S) if pre is None else float(pre)+ if not math.isfinite(self.preroll_s) or not 0<=self.preroll_s<=PREROLL_MAX_S:raise ValueError('Invalid pre-roll')+ self.cache_dir=Path(self.config['cache_dir']) if self.config.get('cache_dir') else sound_cache_dir()+ self.playable={} # asset path -> its pre-rolled copy; filled by the worker before it plays anything+ self.log=log or logging.getLogger(__name__).warningself.lock=threading.Condition();self.pending=[];self.current=Noneself.last_started={};self.last_variant={};self.last_end=-float('inf')self.ids=OrderedDict();self.status=queue.Queue(maxsize=128)@@ -124,8 +182,25 @@ class MossSoundPlayer:self._status(state,event=current['event'],sound=current['sound'],returncode=p.poll(),error=error)self.current=None;self.last_end=time.monotonic()+ def _prepare(self):+ """Write the pre-rolled copy of every asset, outside the lock (emit never waits+ on it). The dry run plays nothing and writes nothing."""+ if self.dry_run or self.preroll_s<=0:return+ failed=None+ for asset in self.manifest['assets'].values():+ if self.closed:return+ path=(self.root/asset['path']).resolve()+ if self.root not in path.parents or not path.is_file():continue+ try:self.playable[path]=preroll_wav(path,self.preroll_s,self.cache_dir)+ except Exception as exc: # a cue without its pre-roll still plays+ failed=failed or f'{path.name}: {type(exc).__name__}: {exc}'+ if failed:+ self.log(f'pre-roll copies not written in {self.cache_dir} ({failed}): those cues play without the pre-roll')+ self._status('preroll_failed',error=failed)+def _run(self):try:+ self._prepare()while True:with self.lock:now=time.monotonic()@@ -160,15 +235,16 @@ class MossSoundPlayer:if self.dry_run:self._status('simulated',event=name,sound=sound)self.last_variant[name]=sound;self.last_started[name]=now;self.last_end=now;continue- err=None+ err=None;play=self.playable.get(path,path)try:- cmd=playback_command(path,self.config['backend'],self.config.get('target'),self.volume)+ cmd=playback_command(play,self.config['backend'],self.config.get('target'),self.volume)err=tempfile.TemporaryFile()proc=subprocess.Popen(cmd,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=err)except (OSError,ValueError,RuntimeError) as exc:if err:err.close()self._status('failed',event=name,error=str(exc));continue- self.current={**item,'sound':sound,'process':proc,'stderr':err,'deadline':time.monotonic()+asset['duration_s']+4}+ self.current={**item,'sound':sound,'process':proc,'stderr':err,+ 'deadline':time.monotonic()+asset['duration_s']+(self.preroll_s if play!=path else 0)+4}self.last_variant[name]=sound;self.last_started[name]=nowself._status('started',event=name,sound=sound)except Exception as exc:diff --git a/moss_dimos/sounds.py b/moss_dimos/sounds.pyindex 3282021..07e73b0 100644--- a/moss_dimos/sounds.py+++ b/moss_dimos/sounds.py@@ -21,7 +21,12 @@ Environment: MOSS_SOUNDS (on by default; 0 = the blueprint leaves the moduleout), MOSS_SOUND_VOLUME (0..1, default from assets/sounds/config.json),MOSS_SOUND_SINK (a PulseAudio sink name or index; default = the session'sdefault sink, which is the Bluetooth speaker once it is connected),-MOSS_SOUND_BACKEND (paplay or pw-play; default: paplay when present).+MOSS_SOUND_BACKEND (paplay or pw-play; default: paplay when present),+MOSS_SOUND_KEEP_AWAKE_S (a silent clip every this many seconds, default 15,+0 = off), MOSS_SOUND_PREROLL_S (silence played in front of every cue, default+0.3 s, 0 = off), MOSS_SOUND_CACHE (where the pre-rolled copies are written,+default <tempdir>/moss_sound_cache). The keep-awake period is read when the+module starts and said in its first log line, with the pre-roll.The player needs the user's audio session: a stack launched from a loginshell or over ssh as the robot's user finds it (XDG_RUNTIME_DIR); a system@@ -46,6 +51,7 @@ from dimos.utils.logging_config import setup_loggerfrom dimos_lcm.std_msgs import Boolfrom moss_dimos import robot_profile+from moss_dimos.sound_pack.player import env_secondslogger = setup_logger()@@ -59,8 +65,10 @@ BATTERY_CRITICAL_MV = 10400 # the flight check refuses to launch below 10.8BATTERY_SAMPLES = 6 # consecutive telemetry lines (3 s at 2 Hz) below a threshold before it countsRECOVERY_WINDOW_S = 20.0 # a stall followed by motion inside this window = a recoveryRECOVERY_MIN_TICKS = 100 # encoder ticks that count as "moving again" after a stall-KEEP_AWAKE_S = 240.0 # a Bluetooth speaker sleeps after minutes of silence and the cues are rare: a silent- # 0.6 s clip every KEEP_AWAKE_S keeps it on (assets/sounds/keep_awake.wav); 0 = off+KEEP_AWAKE_S = 15.0 # default of MOSS_SOUND_KEEP_AWAKE_S: a Bluetooth speaker sleeps its link after a few tens+ # of seconds of silence and the cues are rare: a short silent clip this often, meant to keep it on+ # (assets/sounds/keep_awake.wav); 0 = off+KEEP_AWAKE_MAX_S = 3600.0 # a longer period is clamped to thisdef sound_volume(default: float, env: dict | None = None) -> float:@@ -75,6 +83,12 @@ def sound_volume(default: float, env: dict | None = None) -> float:return max(0.0, min(1.0, v))+def keep_awake_period(env: dict | None = None) -> float:+ """MOSS_SOUND_KEEP_AWAKE_S in seconds: unset or not a number -> KEEP_AWAKE_S,+ 0 or below -> 0 (off), above KEEP_AWAKE_MAX_S -> KEEP_AWAKE_MAX_S."""+ return env_seconds("MOSS_SOUND_KEEP_AWAKE_S", KEEP_AWAKE_S, KEEP_AWAKE_MAX_S, env)++def playback_backend(env: dict | None = None) -> str | None:"""The playback command: MOSS_SOUND_BACKEND when set and on the PATH, else thefirst of BACKENDS on the PATH, None when there is none."""@@ -178,10 +192,12 @@ class MossSounds(Module):self._player = Noneself._mapper = EventMapper()self._silent_reason: str | None = None+ self._keep_awake_s = KEEP_AWAKE_S@rpcdef start(self) -> None:super().start()+ self._keep_awake_s = keep_awake_period()backend = playback_backend()if backend is None:self._silent_reason = f"no playback backend on the PATH ({' / '.join(BACKENDS)})"@@ -192,7 +208,8 @@ class MossSounds(Module):config = {"backend": backend}if self._sink:config["target"] = self._sink- self._player = MossSoundPlayer(root=self._assets_dir, config=config)+ self._player = MossSoundPlayer(root=self._assets_dir, config=config,+ log=lambda text: logger.warning(f"MOSS sounds: {text}"))vol = sound_volume(self._player.volume) if self._volume is None else self._volumeself._player.set_volume(vol)except Exception as exc: # noqa: BLE001 - a broken pack never stops the stack@@ -200,23 +217,27 @@ class MossSounds(Module):logger.warning(f"MOSS sounds: player not started ({self._silent_reason}) - the rover stays silent")self._player = Nonereturn+ awake = f"every {self._keep_awake_s:g} s" if self._keep_awake_s > 0 else "off"+ preroll = f"{self._player.preroll_s:.2f} s" if self._player.preroll_s > 0 else "off"logger.info(f"MOSS sounds: up, {len(self._player.rules)} event families, backend {backend}, "- f"sink {self._sink or 'default'}, volume {self._player.volume:.2f}, assets {self._assets_dir}")+ f"sink {self._sink or 'default'}, volume {self._player.volume:.2f}, keep-awake {awake}, "+ f"pre-roll {preroll}, assets {self._assets_dir}")self._play(["boot_ready"])self._keep_awake(backend)def _keep_awake(self, backend: str) -> None:- """A silent clip every KEEP_AWAKE_S on the same output, so a Bluetooth speaker in the- bin never goes to sleep between two cues (it did on the floor, and the cues after- that went nowhere). A daemon thread, stopped with the module."""+ """A silent clip every MOSS_SOUND_KEEP_AWAKE_S seconds on the same output, so a+ Bluetooth speaker in the bin does not go to sleep between two cues (it did on the+ floor, and the cues after that went nowhere). A daemon thread, stopped with the module."""clip = self._assets_dir / "keep_awake.wav"- if KEEP_AWAKE_S <= 0 or not clip.is_file():+ period = self._keep_awake_s+ if period <= 0 or not clip.is_file():returnself._awake_stop = threading.Event()def loop() -> None:from moss_dimos.sound_pack.player import playback_command- while not self._awake_stop.wait(KEEP_AWAKE_S):+ while not self._awake_stop.wait(period):if self._player is None:returntry:diff --git a/tools/moss-jbl-connect.sh b/tools/moss-jbl-connect.shnew file mode 100755index 0000000..e9420e4--- /dev/null+++ b/tools/moss-jbl-connect.sh@@ -0,0 +1,82 @@+#!/usr/bin/env bash+# Connects the Bluetooth speaker at boot and makes it the default output of the+# robot user's audio session, so the sound pack plays on it after a reboot.+# Run by tools/moss-jbl.service (a systemd user unit); by hand it does the same:+#+# tools/moss-jbl-connect.sh+#+# The speaker must be paired and trusted once (bluetoothctl pair / trust). Its+# address comes from MOSS_JBL_MAC in the environment, else from the line+# MOSS_JBL_MAC=<address> in $MOSS_STATE_DIR/jbl.env (default+# ~/.local/state/moss/jbl.env). This file carries no address.+#+# Up to MOSS_JBL_TRIES tries (default 120), 5 s between tries: `bluetoothctl connect`+# (cut at 20 s), until it answers "Connection successful"; then the speaker's+# PulseAudio sink (bluez_sink.<address> or bluez_output.<address>, from `pactl list+# short sinks`) becomes the default sink. A try that connects but finds no sink+# connects again on the next one (the link can drop before its sink appears). The+# sink's volume is left as PulseAudio remembers it. Exit 0 once the default sink is+# set, 1 after the last try (with the reason), 2 when it cannot run (no address, a+# malformed one, a missing tool). The waits alone add up to about ten minutes; with+# the speaker off each connect also waits out its page timeout, about twenty minutes.+set -u++STATE_DIR="${MOSS_STATE_DIR:-$HOME/.local/state/moss}"+MAC="${MOSS_JBL_MAC:-}"+if [ -z "$MAC" ] && [ -r "$STATE_DIR/jbl.env" ]; then+ MAC=$(sed -n 's/^[[:space:]]*MOSS_JBL_MAC=//p' "$STATE_DIR/jbl.env" | tail -n 1 | tr -d "\"' \t\r")+fi+if [ -z "$MAC" ]; then+ echo "moss-jbl: no speaker address: set MOSS_JBL_MAC or write MOSS_JBL_MAC=<address> into $STATE_DIR/jbl.env" >&2+ exit 2+fi+if ! printf '%s' "$MAC" | grep -qE '^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$'; then+ echo "moss-jbl: MOSS_JBL_MAC is not a Bluetooth address (six hex pairs separated by colons): $MAC" >&2+ exit 2+fi+for tool in bluetoothctl pactl timeout; do+ command -v "$tool" >/dev/null 2>&1 || { echo "moss-jbl: $tool is not on the PATH" >&2; exit 2; }+done++TRIES="${MOSS_JBL_TRIES:-120}"+case "$TRIES" in ''|*[!0-9]*) TRIES=120 ;; esac+[ "$TRIES" -ge 1 ] || TRIES=1+WAIT_S=5+SINK_KEY="${MAC//:/_}"+SINK_KEY="${SINK_KEY^^}"++connected=0+reason="no answer"+for try in $(seq 1 "$TRIES"); do+ if [ "$connected" -eq 0 ]; then+ # a hung bluetoothctl ends here: the loop always moves on+ out=$(timeout 20 bluetoothctl connect "$MAC" 2>&1)+ if printf '%s\n' "$out" | grep -qE 'Connection successful|AlreadyConnected'; then+ connected=1+ echo "moss-jbl: $MAC connected (try $try of $TRIES)"+ else+ reason=$(printf '%s\n' "$out" | grep -v '^[[:space:]]*$' | tail -n 1)+ reason="bluetoothctl: ${reason:-no output}"+ fi+ fi+ if [ "$connected" -eq 1 ]; then+ # the sink appears a moment after the link+ sink=$(timeout 10 pactl list short sinks 2>/dev/null | awk -v key="$SINK_KEY" \+ 'toupper($2) ~ ("^BLUEZ_(SINK|OUTPUT)\\." key "([.]|$)") { print $2; exit }')+ if [ -n "$sink" ]; then+ if timeout 10 pactl set-default-sink "$sink"; then+ echo "moss-jbl: default sink $sink"+ exit 0+ fi+ reason="pactl set-default-sink $sink failed"+ else+ reason="connected, but no bluez sink for $MAC in pactl list short sinks"+ # connect again on the next try: the link may have dropped (PulseAudio restarted and+ # unregistered its A2DP endpoints); a speaker still connected answers success again+ connected=0+ fi+ fi+ [ "$try" -lt "$TRIES" ] && sleep "$WAIT_S"+done+echo "moss-jbl: gave up after $TRIES tries: $reason" >&2+exit 1diff --git a/tools/moss-jbl.service b/tools/moss-jbl.servicenew file mode 100644index 0000000..22b6f8f--- /dev/null+++ b/tools/moss-jbl.service@@ -0,0 +1,28 @@+# MOSS Bluetooth speaker: connected at boot and made the default output of the robot+# user's audio session (tools/moss-jbl-connect.sh), so the sound pack plays on it after+# a reboot. A systemd USER unit and a template: MOSS_DIR is the absolute path of this+# checkout. The speaker is paired and trusted once with bluetoothctl; its address lives+# only in ~/.local/state/moss/jbl.env (one line MOSS_JBL_MAC=<address>), never here.+# Install from the checkout, as the robot's user (lingering is on, so the user manager+# starts at boot without a login):+# mkdir -p ~/.config/systemd/user+# sed -e "s|MOSS_DIR|$PWD|g" tools/moss-jbl.service > ~/.config/systemd/user/moss-jbl.service+# systemctl --user daemon-reload && systemctl --user enable moss-jbl && systemctl --user restart --no-block moss-jbl+# --no-block returns at once (a oneshot unit would hold the shell until the script ends);+# the result is in journalctl --user -u moss-jbl (when it connected, or why it gave up).+# The script gives up after MOSS_JBL_TRIES tries (120, 5 s between tries: about ten minutes+# of waits, about twenty with the speaker off) and the unit fails with the reason;+# `systemctl --user restart --no-block moss-jbl` tries again (a speaker switched on late).+# After=pulseaudio.service only orders the start, and does nothing when that unit is absent.+[Unit]+Description=MOSS Bluetooth speaker: connect and make it the default sink+After=bluetooth.target pulseaudio.service++[Service]+Type=oneshot+RemainAfterExit=yes+EnvironmentFile=-%h/.local/state/moss/jbl.env+ExecStart=MOSS_DIR/tools/moss-jbl-connect.sh++[Install]+WantedBy=default.target