Skip to content

Layer 1 — Hardware Abstraction (HAL)

Part of the OpenRAL public-symbol inventory. Hand-curated; (LNN) markers are refreshed by tools/refresh_methods_linenos.py.

python/hal/src/openral_hal/protocol.py

Normative HAL protocol plus explicit optional lifecycle extensions.

  • class HAL(Protocol) (L118) — Structural protocol every HAL adapter must satisfy.
  • attr description: RobotDescription
  • connect() -> None (L135) — Open connection to robot/sim.
  • disconnect() -> None (L145) — Close connection (idempotent).
  • read_state() -> JointState (L153) — Latest joint state snapshot (hot path).
  • send_action(action: Action) -> None (L167) — Forward action chunk to controller (hot path).
  • estop() -> None (L183) — Trigger emergency stop, always raises ROSEStopRequested.
  • class LifecycleEStopHAL(Protocol) (L64) — Opt-in propagation of the generic lifecycle e-stop to downstream hardware or owned processes.
  • estop() -> None (L74) — Propagate the generic lifecycle e-stop to downstream hardware / owned processes.
  • class ResettableLifecycleEStopHAL(LifecycleEStopHAL, Protocol) (L80) — Opt-in in-process recovery contract: the robot comes back holding its present pose and accepts commands only once the hardware confirms the re-arm.
  • reset_estop() -> None (L89) — In-process recovery from a resettable e-stop.
  • class EStopObservableHAL(Protocol) (L95) — Opt-in: the HAL still reports joint state while e-stopped (its stop leaves a read path open), so the lifecycle node keeps publishing /joint_states through the latch. Never writes or energizes.
  • read_state_estopped() -> JointState (L107) — Read-only joint state during an e-stop.
  • class EStopRecovery(StrEnum) (L35) — Declares whether recovery is resettable or requires a full lifecycle restart.
  • class HALHealthReport (L43) — Cached, I/O-free health payload (message + fields) for the lifecycle diagnostics heartbeat.
  • class HALHealthProvider(Protocol) (L55) — Opt-in health-reporting protocol.
  • health() -> HALHealthReport (L58) — Cached, I/O-free diagnostics consumed by the generic lifecycle heartbeat.

python/hal/src/openral_hal/resolver.py

Builds a robot's sim or real HAL from its manifest, and the URDF joint-state wiring the deploy runtime derives from it.

  • build_hal(description, *, mode: Literal["sim","real"], transport=None, sim_env_yaml=None) -> HAL (L72) — The single seam for building a robot's sim or real HAL from its manifest, used by deploy sim/deploy run. mode picks description.hal.sim/.real (or a scene YAML via sim_env_yaml), merged under hal.parameters.defaults, with safety.joint_state_staleness_limit_s (when declared) passed as the HAL's staleness_limit_s — sim-derived HALs included — and transport on top; raises ROSConfigError/ROSCapabilityMismatch for a bad or missing entry. With sim_env_yaml the SimAttachedHAL gets openral_core.sim_scene_description(description, sim_scene_backend_options(sim_env_yaml)): the scene's control rate (what _check_time_base and the proprio publisher read) and its simulated sensors. A transport naming shared_world (+ shared_world_robot) builds a SharedWorldArmHAL (issue #666); refused unless the robot is a bare manifest-derived sim twin (mode="sim", no sim_env_yaml, hal.sim null).
  • twin_scene_composition(description, scene_composition) -> SceneComposition | None (L48) — The one rule for which MJCF composition a bare MuJoCo twin is built from: the deploy scene's own composition, else the manifest's scene_defaults.composition, else None (the bare robot MJCF). Used by deploy sim (what it forwards as scene_composition_json for a bare-twin scene) and by ManifestHALLifecycleNode._create_hal (what _compose_scene_mjcf composes into the twin's mjcf_path). A composed scene runs on the twin, never scene-attached (#683 left that fork; see 14-duplication-watch.md).
  • hal_joint_states_topic(description, *, mode, hal_node_name, override=None) -> str | None (L179) — The JointState topic the deploy runtime's Python nodes (world_state ingest + the runner's ROSPublishingHAL cache) read. override (DeployRuntime.joint_states_topic) wins; else, on mode="real" with a hal.real class exposing every RosControlDrivable member (checked on the class, not constructed — same membership _attach_ros_control_transport uses), /<hal_node_name>/joint_states, the HAL's rate-limited republish instead of the broadcaster's 0.5-1 kHz /joint_states that starves an in-process VLA of the GIL; None (= /joint_states) for serial/interbotix/sim HALs. Called by deploy_e2e.launch.py, which forwards the result as the runtime node's joint_states_topic param.
  • class UrdfJointMap (L274) — Frozen Pydantic v2 model (extra="forbid"), parallel to the manifest joints (validated: equal lengths): names (URDF joint, "" = none), scales, offsets, curves (each joint's JointSpec.urdf_curve or None; empty = none) — robot_state_publisher is sent scale * curve(q) + offset. curves_param() -> list[float] flattens curves into the HAL's urdf_joint_curves param (per joint [n, x0, u0, …], [] when none; #533).
  • curves_param() -> list[float] (L308) — curves as the HAL's flat urdf_joint_curves param.
  • ros_control_hal(description, *, mode) -> bool (L226) — Whether the HAL node wires the manifest's HAL to a RosControlTransport (mirrors _attach_ros_control_transport): mode == "real" and the hal.real class has every RosControlDrivable member, checked on the class without constructing it. hal_joint_states_topic and the deploy launch's robot_state_publisher map both gate on it. ROSConfigError on an unimportable hal.real.
  • vendor_publishes_urdf_joint_states(description, *, mode) -> bool (L253) — ros_control_hal and the hal.real class does not set urdf_joint_states_from_hal (a ComposedHAL, whose arm broadcaster covers only some joints). The deploy launch's _rsp_urdf_joint_map and the HAL node's ~/urdf_joint_states gate on it, so the OpenAMRobot lift and everything on it reach /tf on real hardware.
  • urdf_joint_map(description, urdf_xml) -> UrdfJointMap | None (L332) — Names as urdf_joint_names, plus URDF units: a mimic_joints row driven by manifest joint J that poses the link a non-<mimic> URDF joint U moves sends J's state to U through the row's multiplier / offset (the SO-101 jaw: 1.74533 f; the DROID Robotiq finger_joint: pi/4 (1 - f)) — the kernel's and self-filter's map, so /tf poses the jaw where the collision model does. None when every joint maps to itself at unit scale. The deploy launch (_rsp_urdf_joint_map) passes it to every HAL without a ros2_control transport (ros_control_hal false: any sim twin, the serial SO-101 on real) (urdf_joint_names / urdf_joint_scales / urdf_joint_offsets) and remaps robot_state_publisher onto ~/urdf_joint_states; /joint_states keeps the manifest units.
  • urdf_joint_names(description, urdf_xml) -> list[str] (L401) — The URDF joint each manifest joint's state drives (its name when the URDF declares it, else its sim_joint_name, else ""), parallel to description.joints; [] when every name already agrees. A sim HAL publishes joint states under the logical names, so a URDF that names its joints differently (the OpenArm's vendored one) left every moving link off /tf and every tf2 consumer (vision attachment leg TCP / attach link, octomap payload clearing) blind. deploy_e2e.launch.py passes the result to the sim HAL as urdf_joint_names and remaps robot_state_publisher onto the HAL's ~/urdf_joint_states. Raises ROSConfigError on unparseable XML.
  • _import_object(path: str, *, setting: str = "hal entrypoint") -> object [private] — Resolves a "module.path:Attribute" HAL entrypoint through openral_core.code_refs.import_code_ref (openral_* modules only, re-checked at the import); raises ROSConfigError if malformed/refused/missing. Reuse watch: the canonical entrypoint importer — don't hand-roll importlib in HAL callers.

python/hal/src/openral_hal/_mujoco_arm.py

Internal MuJoCo-backed HAL shared by UR / Franka / SO-100 / G1 / H1 / H2 / Rizon-4 / OpenArm / ALOHA adapters. Reads its wiring from RobotDescription.sim. Since #683 MujocoArmHAL is a SimAttachedHAL (the one sim HAL shell) whose env is a MujocoTwinRollout (mujoco_twin.py, the one MuJoCo driver: MJCF load, camera rig, time base, command composition, ctrl writes, base driving, the one stepping loop, state read, renders) or a robot's subclass of it; the shell drives it (send path, slot-group staging, idle stepper, clock, time base, estop latch). This module keeps only the twin's explicit differences — a refused second connect, the release of the model on disconnect, the raising estop — and the manifest-driven constructors. A twin has the whole SimAttachedHAL surface — the attachment API, reset_episode (an in-place MujocoTwinRollout.reset, so the bridge's MjModel stays live) and per-goal grading — so a deploy scene that composes its own MJCF (resolver.twin_scene_composition) gets the same deploy graph as a scene-attached one; only the env differs.

  • _resolve_mjcf_path(desc: RobotDescription) -> str [private] — Resolves desc.assets.mjcf to an absolute MJCF path via openral_core.assets.resolve_asset; raises ROSConfigError if unset/unresolvable. (L52)
  • _kinematic_group(joint_name, groups, *, robot) -> str [private] (L82) — Maps a joint name to its kinematic group (substring match against groups) for the G1/H1 humanoid velocity/effort/PD-gain lookup tables; raises ROSConfigError naming robot if none match.
  • class MujocoArmHAL(SimAttachedHAL) — Generic MuJoCo-backed HAL adapter for position-controlled arms and, through a rollout subclass, torque-controlled or mobile twins: a SimAttachedHAL (the one sim HAL shell, attachment API, reset_episode and per-goal grading included) around a MujocoTwinRollout (or the twin subclass a robot passes) built from its arguments (explicit env_action_dim, so openral_sim is never probed). The shell drives it: every command goes through the shell's send_action (slot groups staged in its SlotGroupStager; the twin declares steps_every_command_as_group) to the rollout's step_action_group, idle slices through its idle_step; joint state (read_joint_state), on-demand renders (read_images), mujoco_handles, sim_time_ns, last_action_ns, base_pose / base_twist, export_sim_scene and the post-step observers come through the shell's env hooks. No HALBase: the checks it shared are _base's module-level validators. _model / _data / _settle_steps are properties onto the rollout's live values. (L107)
  • __init__(description, *, twin=MujocoTwinRollout, **kwargs: Unpack[TwinKwargs]) — Init only; builds the twin rollout (MujocoTwinRollout or a robot's subclass / functools.partial of one) from kwargs (mujoco_twin.TwinKwargs, the one typed shape of the twin's wiring: mjcf_path, joint_qpos_addr, actuator_index, joint_qvel_addr, grippers, keyframe_index, seed_ctrl_from_qpos, settle_steps, gravity_enabled, staleness_limit_s, body_twist_dt_s), with backend set to this class's name; the rollout refuses a RobotDescription.name containing a path separator (it names the <name>_camrig.xml written beside the MJCF). MJCF loads at connect(). (L170)
  • connect() -> None (L210) — SimAttachedHAL.connect (its env.reset loads the twin: MJCF, camera rig, time base, twist interval, robot setup); ROSRuntimeError if already connected (the HAL Protocol's contract; a scene-attached env re-connects idempotently).
  • disconnect() -> None (L232) — SimAttachedHAL.disconnect (which resets the slot-group stager, restarting tick numbering, also after an estop), then _release_twin; idempotent.
  • _release_twin() -> None [private] — Folds the sim time the twin reached into the shell's cross-reset offset (so sim_time_ns stays monotonic across a reconnect), then MujocoTwinRollout.close and drops the scene-export cache.
  • (property) _step_while_active -> bool [private] — True while the twin is wall-paced (sim_dt_per_tick_s is None: a pinned settle_steps or no declared rate), so the bridge's wall-time idle stepper keeps /clock and the cameras alive during a skill; G1MujocoHAL / H2MujocoHAL set it False.
  • reset_to_pose(pose: list[float]) -> None — Maintenance/test snap of qpos with ctrl re-seeded (MujocoTwinRollout.reset_to_pose); gripper values are mapped through SimGripperDescription.ctrl_range so they stay in the HAL's normalized units, and a follower jaw inside a gripper's qpos_addrs (the R1 Pro's finger_joint2) keeps the leader's snap rather than its own entry. Skill startup instead uses the runner's checked ramp or MoveIt. (L251)
  • estop() -> None (L309) — SimAttachedHAL.estop (latch, discard the half-staged slot group keeping the watermark, stop the base), then the twin's explicit difference: zero ctrl, disconnect (first, so a reader on another thread is refused by the connected guard, never handed a released model), _release_twin (GL contexts closed now), and raise ROSEStopRequested (the HAL Protocol's raising stop). The latch survives the next connect: estop_latched reads True, commands are dropped (logged once) and idle does not step, until reset_estop. The lifecycle node never calls it (a sim HAL is not a LifecycleEStopHAL); its /openral/estop freezes sim physics through the bridge instead (SimSensorBridge._idle_step_tick), and calls SimAttachedHAL.stop_stale_motion at the latch and the clear.
  • health() -> HALHealthReport (L290) — HALHealthProvider for the lifecycle diagnostics heartbeat: message hal ready and one <end_effector>_position_normalized field per end-effector gripper (the Galaxea A1 real HAL's gripper_position_normalized key); no fields for a twin without one, so its diagnostics read as before. No I/O.
  • (classmethod) from_description(description, *, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5, mjcf_path_override=None) -> MujocoArmHAL — Manifest-driven constructor: builds the HAL's MJCF path, qpos/qvel/actuator maps and gripper config from description.sim, removing the need for per-robot subclasses. A manifest that supports BODY_TWIST without sim.floating_base runs on _PlanarBaseTwin. (L411)
  • (staticmethod) _sim_kwargs_for(description, *, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5, mjcf_path_override=None) -> TwinKwargs — Translates description.sim into the __init__ kwarg dict; default 1:1 joint→qpos/actuator mapping from description.joints, offset 7/6 when sim.floating_base=True. Used by from_description and _init_from_description. (L337)
  • (instance method) _init_from_description(description, *, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5, body_twist_dt_s=None, twin=MujocoTwinRollout) -> None — Shared seam every thin per-robot subclass (UR5e/UR10e, Franka, ALOHA, OpenArm, Rizon4, G1, H1, H2, SO-100, OpenAMRobot) forwards to instead of hand-rolling super().__init__(DESC, **_sim_kwargs_for(DESC, …)). (L473)
  • (the shell's _require_connected — _base.require_connected, the one guard and message — refuses calls before connect.)

python/hal/src/openral_hal/mujoco_twin.py

MujocoTwinRollout — the bare MuJoCo twin's physics behind the SimRollout face; the single MuJoCo driver of the MujocoArmHAL hierarchy (#683), plus the building blocks of the humanoid twins (_GlideTwin, _FreeBaseTwin, _S0PolicyTwin, _SoftwarePDTwin) and the R1 Pro's wheeled base (_PlanarBaseTwin). Imports mujoco lazily and never openral_sim, so a bare twin runs without the sim group.

  • module const _IDLE_STEP_CAP = 200 (L79) — Upper bound (physics steps) on how much sim time one idle_step wall-time tick may advance, so an executor stall cannot fast-forward the world by seconds.
  • joint_actuator_effort(data, dof) -> float (L85) — The one definition of sim /joint_states.effort: MuJoCo qfrc_actuator at the joint's DOF (gear/transmission applied, all actuators on the DOF summed, gravity load included). Used by MujocoTwinRollout.read_joint_state and SimAttachedHAL.read_state.
  • _gripper_command_to_raw(gripper, command) -> float [private] (L95) — Public gripper command → actuator-native value: PASSTHROUGH verbatim, NORMALISED clipped to [0, 1] and mapped affinely onto ctrl_range.
  • class TwinKwargs(TypedDict, total=False) (L103) — The one typed shape of the twin's wiring: what MujocoArmHAL.__init__ takes, MujocoArmHAL._sim_kwargs_for builds and a rollout subclass forwards (**kwargs: Unpack[TwinKwargs]); mjcf_path / joint_qpos_addr / actuator_index required.
  • class TwinStepResult(BaseModel) (L124) — Frozen Pydantic model; what SimAttachedHAL reads from one twin step: info["applied_action"], the command step_action_group applied (the composed action for a slot group, the action itself otherwise). No observation (the twin renders lazily and reads its state live).
  • class MujocoTwinRollout (L138) — A robot's own MJCF as the env of the sim HAL shell, and the one MuJoCo driver of the twin hierarchy. __init__(description, **kwargs: Unpack[TwinKwargs]); it holds no reference to its HAL. Refuses an empty joint list, a robot name that is not a file name and duplicate / unknown gripper joints. steps_every_command_as_group = True (class attribute) is its declared send route: the shell hands it every command, an ungrouped action as a group of one. Per-robot behaviour is a subclass overriding the hooks below (h1._H1Twin, h2._H2Twin / _H2AgileTwin, _GlideTwin (the default G1), g1._G1WalkTwin / _G1Gr00tTwin, openamrobot_v2._OpenAMRobotV2Twin); hold_if_uncommanded lists joints a command may leave out (they keep their ctrl target).
  • (property) action_dim -> int (L269) — One target per description.joints joint.
  • load() -> None (L273) — Loads _load_model's model (a seam; the base splices manifest cameras missing from the MJCF in (_camera_rig.rig_cameras_into_mjcf, writing <name>_camrig.xml beside it, and loads it), zeroes gravity when disabled, resets to keyframe_index, mj_forward — all on locals, assigned only once the MJCF loaded — then seeds ctrl from qpos (seed_ctrl_from_qpos), resolves the time base and the twist interval and runs _on_load; a refusal there closes the rollout, so a refused load leaves no model, clock or renders behind. Logs hal.connect. ROSConfigError without mujoco, on an unreadable MJCF, an out-of-range keyframe or a refused twist interval.
  • reset(seed=None) -> dict[str, Any] (L366) — close, then load: the twin's initial state on a fresh model (the shell's connect resets through it). Deterministic.
  • clock_id = "mujoco" — The clock id the shell's clock_authority reports.
  • (property) physics_dt_s -> float | None (L494) — The physics timestep (the shell's clock timestep while the twin is wall-paced); None unloaded.
  • (property) time_base_fields -> dict[str, str | float | int] (L503) — {backend: <the HAL class>, physics_dt_s, physics_steps} once held to the rate, for the shell's sim.time_base line.
  • step(action) -> TwinStepResult (L394) — The plain SimRollout face (required by SimEnv): a full-dof target row as one ungrouped JOINT_POSITION command, delegated to step_action_group — no command path of its own; the shell never calls it.
  • step_action_group(actions) -> TwinStepResult (L413) — The shell's command hook (a slot group, or one ungrouped action as a group of one): _compose validates it into a full-dof row and/or a planar twist, _command writes the row (_apply_targets) and drives the base (_drive_base), then ONE advance runs the period — a tick with joint and twist slots moves both inside the same control period. Reports the applied command in info["applied_action"].
  • advance(steps) -> None (L449) — The one stepping loop of the twin hierarchy: steps × (_per_step, mj_step); refreshes the starvation clock.
  • _compose(actions) -> (row | None, twist | None, applied) [private] — Splits out the twist (_split_twist); composes joint / gripper slots — or an ungrouped row naming a subset of the joints — by name (compose_slot_group_action, hold= the hold_if_uncommanded joints' ctrl targets), then _validates the command. applied is the composed command (the shell records it for a slot group; an ungrouped action is its own record).
  • _validate(action) [private] — ROSConfigError for a mode outside supported_control_modes (_base.require_supported_control_mode), a twist _planar_twist refuses, a non-JOINT_POSITION joint command (_base.require_control_mode: "<HAL> only supports joint_position"), a missing row or a row that is not one target per joint (_base.validate_action_dims).
  • _split_twist(actions) -> (twist | None, joint slots) [private] — The command's planar twist (at most one BODY_TWIST slot, _validated) and its other slots; shared by _compose and the GR00T twin's.
  • per-robot hooks [private]: _planar_twist (_floating_base.validate_planar_body_twist, differential= the manifest's base_kinematics), _command, _apply_targets (arm ctrl + grippers by write mode), _drive_base (default: ROSConfigError, no base), _action_steps (default settle_steps), _per_step (default no-op), _on_idle, _on_load (after the MJCF loads; a raise closes the rollout), _held_ctrl_targets, _require_loaded (_base.require_connected).
  • close() -> None (L464) — Closes the renderers (under render_lock; a renderer whose GL teardown fails is logged hal.renderer_close_failed, never kept) and drops model/data. Idempotent.
  • mujoco_handles() -> tuple[Any, Any] | None (L487) — Live (model, data), None before load / after close.
  • sim_time_ns() -> int | None (L516) — MjData.time in ns.
  • idle_step(wall_dt_s=None) -> bool (L522) — SimAttachedHAL's idle hook: _on_idle, then advance(round(wall_dt_s / timestep)) (min 1, max _IDLE_STEP_CAP), so the per-step hook (a PD loop, a pinned base) keeps running while the last command holds; False before load / after close.
  • hold_present_pose() -> None (L1123) — Every non-gripper joint's actuator targets its current position (gripper ctrl kept: it is not a joint position, and a held object stays held). For SimAttachedHAL.stop_stale_motion at an e-stop latch and its clear (openral#700 item 1).
  • read_joint_state() -> JointState (L549) — SimAttachedHAL's joint-state hook: live state in description.joints order, grippers by read_mode (a PASSTHROUGH gripper reports its qvel, a normalised one 0), efforts by joint_actuator_effort. A gap above staleness_limit_s since the twin last stepped, loaded, snapped or was read logs a one-shot hal.read_state.starved WARNING (re-armed by a healthy read) — the data is live, so never ROSPerceptionStale.
  • read_images() -> dict[str, NDArray] (L610) — SimAttachedHAL's render hook: the manifest's RGB SensorSpecs off the live MJCF, keyed by sensor name, each from the MJCF camera sim_camera_name, else (a composed scene renamed it, e.g. the OpenArm tabletop's wrist_*) the camera named after the sensor with a one-shot hal.read_images.camera_fallback warning per sensor, at its own intrinsics resolution (one cached mujoco.Renderer per resolution, offscreen buffer grown to fit). Skips a missing camera / render error with a one-shot warning; {} when not loaded, without RGB sensors or after a renderer failure. Holds render_lock.
  • reset_to_pose(pose) -> None (L708) — Snaps qpos (velocities zeroed), mj_forward, re-seeds ctrl to hold it: position actuators from qpos (_hold_qpos_in_ctrl), grippers through apply_gripper_targets (their public→native mapping); a finger tied to a snapped gripper joint by an MJCF joint equality is snapped with it (_snap_equality_followers: joint1 evaluated from joint2, or joint2 solved for a linear coupling), so the WidowX mirror finger never starts violating its constraint. ROSConfigError on a wrong length or a gripper with no actuator index.
  • apply_arm_targets(targets) -> None (L809) — Each non-gripper joint's target into its actuator's ctrl.
  • apply_gripper_targets(targets) -> None (L820) — Each joint gripper's command into ctrl (and its mirror actuator, negated, _write_gripper_ctrl); ROSConfigError for a gripper with no actuator index.
  • end_effector_gripper_positions() -> dict[str, float] (L1028) — Each end-effector gripper's (a sim.grippers[] entry with end_effector, no manifest joint) normalised position by read_mode, keyed by end-effector name; {} unloaded. Feeds MujocoArmHAL.health.
  • _split_end_effector_grippers(actions) -> (gripper commands, other slots) [private] — Splits the GRIPPER_POSITION slots _gripper_of resolves off a command before _compose; refuses a mode outside supported_control_modes, an empty gripper, a value outside [0, 1] (as the real HAL of such a robot does) or an unknown ee_name. step_action_group writes them after the rest of the command is validated and written.
  • _gripper_of(action, *, lone) -> SimGripperDescription | None [private] — The gripper a GRIPPER_POSITION slot drives: an end-effector gripper by ee_name (or the only one); a joint gripper only for a lone action (ee_name names the gripper joint, the slot-group rule; or a declared end effector — the name the safety kernel bounds the command by — driving the one gripper joint on its EndEffectorSpec.parent_link; or any end effector with exactly one joint gripper), so a bare twin executes the mode it advertises. None in a slot group: compose_slot_group places it, after _split_end_effector_grippers has rewritten an end-effector ee_name to that gripper joint (the same resolution, _gripper_joint_named).
  • _gripper_joint_named(name) -> str | None [private] — The joint gripper an ee_name names: the joint itself, or the one gripper joint on a declared end effector's parent_link.
  • _require_joint_gripper_open_unit(joint) -> None [private] — _require_open_unit for the end effector that owns gripper joint (same name, or its parent_link), so naming a gripper by its joint cannot skip the convention check. A PASSTHROUGH jaw whose end effector declares raw_joint_rad passes: it writes joint units verbatim (OpenAMR, Anvil).
  • _check_gripper_actuators(nu) -> None [private] — At load, refuses a gripper with no actuator index or a primary / mirror index outside the model (>= nu), so a mixed command can never write its arm row and then fail on a gripper.
  • _require_open_unit(ee_name) -> None [private] — Refuses an end effector whose declared command_convention is not normalized_open_unit (the twin writes [0, 1] opening only); checked for every end-effector gripper at construction and for a lone joint-gripper command.
  • _resolve_time_base() -> None [private] (L1167) — Called by load (issue #358): with no pinned settle_steps and a declared description.control_rate_hz, derives the physics steps per action via openral_core.physics_steps_per_tick (shrinking opt.timestep so the period is a whole number of steps, logged as hal.time_base.timestep_shrunk) and declares sim_dt_per_tick_s; the shell alone holds it to the rate (check_time_base) and logs sim.time_base. A pinned count is honoured and logged as hal.time_base.pinned; a manifest without a rate keeps the legacy single step (hal.time_base.unresolved) — neither is timing-faithful and both stay wall-paced (sim_dt_per_tick_s = None).
  • _resolve_twist_interval() -> None [private] — Called by load after the time base: body_twist_dt_s (what one BODY_TWIST integrates a base by, and the G1 walker's steps per walk command) is the control period — sim_dt_per_tick_s, or settle_steps × timestep while wall-paced — so a base moves at the commanded speed on the sim clock. An explicit value is honoured on a wall-paced twin only; on a timing-faithful one, one that differs from the period by more than TIME_BASE_TOL is refused (ROSConfigError).
  • private: _hold_qpos_in_ctrl, _gripper_actuator_index, _write_gripper_ctrl, _reset_gripper_qpos, _snap_equality_followers, _read_gripper_value, _read_images_locked
  • class _GlideTwin(MujocoTwinRollout) [private] — ADR-0087's upright kinematic glide (the default G1 twin; H2's base): _per_step writes the pin into the free joint (write_base_pin) before every physics step, then the next block's hook; the pin is captured from qpos on first use after a load and KEPT across reset_to_pose (recapturing it would read the free joint one step after the pin was written, lower by that step's fall); BODY_TWIST slides it by body_twist_dt_s (integrate_planar_twist); read_base_pose is the pin.
  • class _PlanarBaseTwin(MujocoTwinRollout) [private] (L1541) — A wheeled base on the MJCF's base_x / base_y / base_yaw joints that are not manifest joints (the R1 Pro): _on_load finds them (absent: ROSConfigError) and takes their qpos as the pose; _per_step writes the pose into them, velocity zeroed, before every physics step; BODY_TWIST slides it by body_twist_dt_s (integrate_planar_twist, holonomic); read_base_pose is the pose. MujocoArmHAL.from_description picks it for a manifest that supports BODY_TWIST without sim.floating_base.
  • class _FreeBaseTwin(MujocoTwinRollout) [private] — read_base_pose off the free joint (capture_base_pin(qpos)): the one free-base reader of the G1 walker and GR00T WBC twins; ROSRuntimeError unloaded.
  • class _S0PolicyTwin(_FreeBaseTwin) [private] — The shared part of a free-base twin a sim-only S0 policy balances (G1 _G1Gr00tTwin, H2 _H2AgileTwin). Class attrs s0_name, fall_pelvis_height_m, fall_tilt_rad (45°). _load_model adds an s0_floor plane (MjSpec recompile) when the MJCF has no world plane; _enable_ground_contact switches a visual-only plane's collision bits on; _bind_torso (no torso_link: ROSConfigError); _latch_if_fallen (pelvis below / tilt beyond → fallen, ctrl zeroed, hal.<robot>.s0_controller.fall_detected CRITICAL) / _raise_if_fallen (ROSSafetyViolation); step_action_group raises before and after the period once fallen; read_base_twist is the held _s0_command; _on_idle zeroes it.
  • class _SoftwarePDTwin(MujocoTwinRollout) [private] — A position loop in software over torque (motor) actuators (H1, H2): __init__(description, *, pd_gains, **kwargs); _on_load precomputes index arrays, gains and the ctrlrange once; a command's row becomes the target (_apply_targets, never ctrl); _per_step writes clip(kp (target - q) - kd dq, ctrlrange) vectorised, actions and idle slices alike; no target (no torque) before the first command unless hold_pose_on_load; reset_to_pose zeroes ctrl (the base's qpos re-seed would be N·m) and makes the snapped pose the target; a reload clears it.

python/hal/src/openral_hal/_base.py

Shared HAL mixin — _connected flag, a default disconnect, and the module-level validators every HAL, the sim HAL shell and the MuJoCo twin share (one place, one message each).

  • class HALBase — Non-ABC mixin every adapter subclasses. (L111)
  • disconnect() -> None (L126) — Flag-and-log default (guard on _connected, log.info("hal.disconnect", ...), clear the flag). Idempotent. Adapters holding a real resource (SDK handle, MuJoCo buffers, USB port) override it; AlohaHAL and RosControlHAL use the default as-is.
  • private: _require_connected, _validate_action_dims — thin wrappers over the module validators below.
  • require_connected(connected, backend, operation) -> None (L53) — The one "not connected" refusal (ROSRuntimeError: ".() called while not connected (before connect() or after disconnect()). Call connect() first."); used by HALBase, SimAttachedHAL._require_connected and MujocoTwinRollout._require_loaded.
  • require_supported_control_mode(description, action) -> None (L69) — ROSConfigError for a mode outside the manifest's supported_control_modes (empty: any); used by RosControlHAL, UnitreeHgRealHAL and MujocoTwinRollout.
  • require_control_mode(action, allowed, backend) -> None (L83) — ROSConfigError (" only supports ") for any other mode.
  • validate_action_dims(action, joint_count, robot) -> None (L95) — ROSConfigError for a joint_targets row that is not one target per joint.
  • resolve_staleness_limit_s(description, override) -> float (L22) — A real HAL's joint-state freshness window: override when not None, else description.safety.joint_state_staleness_limit_s; ROSConfigError when neither exists. Replaces every real HAL's constructor default (audit C F3): used by RosControlHAL, AlohaHAL and SO100FollowerHAL.
  • _raw_floats(raw: dict[str, object], key: str, width: int) -> list[float] [private] — Shared read_state decode: raw[key] as floats if it's a list, else width zeros. Used by AlohaHAL.read_state and RosControlHAL.read_state.

python/hal/src/openral_hal/_camera_rig.py

Generic sim camera rig — splice manifest cameras into a bare-arm MJCF for deploy sim.

  • rig_cameras_into_mjcf(xml: str, sensors: list[SensorSpec]) -> tuple[str, bool] (L112) — For each RGB or depth SensorSpec with a sim_placement whose camera is missing from xml under both sim_camera_name and name (a depth sensor's camera is what the sim bridge ray-casts and renders its registered colour from), splices a <camera> into its parent_body (wrist) or <worldbody> (overhead), plus minimal staging (visual-only floor + fill light) when the MJCF has none. Returns (xml, changed) — changed=False when no rigging is needed, so an already-composed MJCF passes through unchanged. Idempotent; raises ROSConfigError when a sensor's parent_body is missing. Called by MujocoTwinRollout.load (from MujocoArmHAL.connect).
  • module const _STAGING_FLOOR: str (L74) — Visual-only (contype=0 conaffinity=0) ground-plane <geom> XML fragment spliced in by _ensure_staging so a bare-arm deploy twin's cameras have a surface to see.

python/hal/src/openral_hal/_real_description.py

Internal helper to derive a real-hardware RobotDescription from a sim baseline.

  • make_real_description(base, *, sdk_kind) -> RobotDescription — model_copy(update={"sdk_kind": sdk_kind}); the hal entrypoints (hal.sim / hal.real) are inherited from base. (L48)

python/hal/src/openral_hal/_sensor_wiring.py

Resolve sensor catalog ids into SensorSpec / SensorBundle and attach them to a RobotDescription copy — the shared helper behind every per-robot *_with_sensors(...) factory (franka_panda_with_sensors, ur5e_with_sensors, ur10e_with_sensors, so100_with_sensors).

  • SensorRequest = str | tuple[str, Mapping[str, Any]] (L23) — Either a bare catalog id ("intel/realsense_d435") or an (id, kwargs) pair forwarding kwargs to the catalog factory.
  • with_sensors(description, requests, *, default_parent_frame=None) -> RobotDescription (L28) — Deep-copies description and appends catalog-resolved sensors/bundles (via openral_sensors.CATALOG.build); each request's parent_frame defaults to default_parent_frame or description.base_frame. Raises KeyError for an unknown catalog id.

python/hal/src/openral_hal/franka_panda.py

HAL adapter for the Franka Emika Panda 7-DoF arm (sim, MuJoCo).

  • class FrankaPandaHAL(MujocoArmHAL) — Franka Panda HAL (MuJoCo-backed). Thin manifest-driven wrapper around MujocoArmHAL; __init__ forwards to self._init_from_description(FRANKA_PANDA_DESCRIPTION, …). (L286)
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5) (L318)
  • _panda_joint_specs() -> list[JointSpec] (L123)
  • module const _PANDA_ARM_JOINT_NAMES: list[str] (L53) — 7 arm joint names, upstream panda_jointN naming.
  • module const _PANDA_GRIPPER_JOINT_NAME = "panda_gripper" (L63) — synthetic 1-DoF gripper channel, normalized like SO-100's.
  • module const _PANDA_JOINT_NAMES: list[str] (L65) — arm + gripper, full manifest joint order.
  • module const _PANDA_SIM_JOINT_NAMES: dict[str, str] (L75) — manifest joint name → native MJCF joint name, used by SimAttachedHAL.read_state's name resolution.
  • module const _PANDA_POSITION_LIMITS: dict[str, tuple[float, float]] (L88) — per-joint position limits (Franka FR3/Panda data sheet, rad).
  • module const _PANDA_VELOCITY_LIMITS: dict[str, float] (L99) — per-joint velocity limits (rad/s).
  • module const _PANDA_EFFORT_LIMITS: dict[str, float] (L110) — per-joint torque limits (Nm).
  • const FRANKA_PANDA_DESCRIPTION = RobotDescription(...) (L177) — sim baseline; sdk_kind="open", hal.sim=None (build_hal derives MujocoArmHAL from the manifest) + hal.real="openral_hal.franka_panda_real:FrankaPandaRealHAL"; an in-code mirror of robots/franka_panda/robot.yaml, which is the runtime source of truth. All MuJoCo wiring (MJCF URI, joint→qpos/actuator maps, gripper config) lives in FRANKA_PANDA_DESCRIPTION.sim. The real-HW companion FRANKA_PANDA_REAL_DESCRIPTION lives in franka_panda_real.py.
  • franka_panda_with_sensors(catalog_ids=None) -> RobotDescription — Copy of FRANKA_PANDA_DESCRIPTION with catalog sensors attached; None defaults to the wrist-mounted RealSense D435i reference loadout. (L257)

python/hal/src/openral_hal/franka_panda_real.py

Real-hardware HAL adapter for the Franka Emika Panda over the FCI.

  • module const _DEFAULT_FRANKA_CONTROLLER: str = "franka_arm_controller" (L58)
  • module const _DEFAULT_FRANKA_JOINT_STATE_TOPIC: str = "/joint_states" (L63)
  • module const _DEFAULT_FRANKA_ERROR_RECOVERY: str = "/error_recovery" (L70) — the franka_msgs/action/ErrorRecovery name recorded for the operator; never called by estop().
  • class FrankaPandaRealHAL(RosControlHAL) — Production adapter for a physical Panda over franka_ros2 / FCI. Takes description= (loaded manifest; None → FRANKA_PANDA_REAL_DESCRIPTION). Subclasses RosControlHAL (the UR shape) so it is structurally RosControlDrivable and the lifecycle node attaches the production RosControlTransport under hal_mode:=real; the earlier composed wrapper forwarded only the five HAL Protocol methods, exposed none of the drivable surface, and was therefore never wired — a real Panda deploy published every command into _default_publish. (L89)
  • __init__(*, fci_ip='172.16.0.2', controller_name='franka_arm_controller', joint_state_topic='/joint_states', command_topic=None, error_recovery_action='/error_recovery', publish_fn=None, state_fn=None, staleness_limit_s=None, description=None) (L165) — staleness_limit_s=None reads the manifest's safety.joint_state_staleness_limit_s.
  • estop_recovery = RESTART_REQUIRED — stopRobot() ends the FCI session; the reflex is cleared and the FCI re-armed by the operator.
  • fci_ip -> str [@property] (L199)
  • error_recovery_action -> str [@property] — franka_ros2's franka_msgs/action/ErrorRecovery the operator runs before re-arming; recorded, never called by estop() (it clears a reflex — a recovery, not a stop). (L204)
  • connect() -> None — Logs the FCI target, then the base connect. (L210)
  • estop() — Inherited, not overridden: deactivating franka_arm_controller through controller_manager is the stop — franka_hardware's on_deactivate calls libfranka's stopRobot(). The earlier override published a dict to /error_recovery/goal, an undeclared topic the transport refused, so it was a silent no-op; it is gone.
  • Inherits description (= FRANKA_PANDA_REAL_DESCRIPTION), controller_name, disconnect, read_state, send_action, command_bindings, attach_transport, attach_controller_stop, reset_estop (refuses: RESTART_REQUIRED) from RosControlHAL.
  • const FRANKA_PANDA_REAL_DESCRIPTION = make_real_description(FRANKA_PANDA_DESCRIPTION, sdk_kind="closed_with_api") (L83) — inherits the shared hal; what robots/franka_panda/robot.yaml mirrors.

python/hal/src/openral_hal/sawyer_real.py

Real-hardware HAL adapter for the Rethink Sawyer 7-DoF arm.

  • module const _SAWYER_JOINT_NAMES: tuple[str, ...] (L66) — 7 arm joint names.
  • module const _SAWYER_POSITION_LIMITS: dict[str, tuple[float, float]] (L79)
  • module const _SAWYER_VELOCITY_LIMITS: dict[str, float] (L89)
  • module const _SAWYER_EFFORT_LIMITS: dict[str, float] (L99)
  • module const _DEFAULT_SAWYER_CONTROLLER: str = "sawyer_arm_controller" (L223)
  • module const _DEFAULT_SAWYER_JOINT_STATE_TOPIC: str = "/robot/joint_states" (L228)
  • module const _DEFAULT_SAWYER_ESTOP_TOPIC: str = "/robot/set_super_stop" (L237)
  • class SawyerRealHAL(RosControlHAL) — Production adapter for a physical Sawyer over intera_sdk / sawyer_robot. Takes description= (loaded manifest; None → SAWYER_REAL_DESCRIPTION). Subclasses RosControlHAL for the same reason as FrankaPandaRealHAL: the composed wrapper it replaced was not RosControlDrivable, so the lifecycle node never attached the production transport to it. (L243)
  • __init__(*, hostname='sawyer.local', controller_name='sawyer_arm_controller', joint_state_topic='/robot/joint_states', command_topic=None, estop_topic='/robot/set_super_stop', publish_fn=None, state_fn=None, staleness_limit_s=None, description=None) (L317) — staleness_limit_s=None reads the manifest's window.
  • hostname -> str [@property] (L351)
  • connect() -> None (L355)
  • estop_recovery = RESTART_REQUIRED — the super stop is cleared by /robot/set_super_reset + re-enable, an operator step.
  • (property) estop_topic -> str — /robot/set_super_stop, intera's super-stop topic. (L370)
  • vendor_stop_topics() -> list[str] — [estop_topic], declared so the transport creates its std_msgs/Empty publisher at wire-up. (L376)
  • _vendor_stop(seam) -> str — After the base deactivated sawyer_arm_controller, publishes intera's super stop (RobotEnable.stop()'s topic: "Simulate an e-stop button being pressed. Robot must be reset to clear the stopped state"). The topic carries no service ack; the acknowledged half is the controller deactivation, and the HIL gate reads /robot/state.stopped.
  • Inherits description (= SAWYER_REAL_DESCRIPTION), controller_name, disconnect, read_state, send_action, command_bindings, attach_transport, attach_controller_stop, estop, reset_estop (refuses: RESTART_REQUIRED) from RosControlHAL.
  • _sawyer_joint_specs() -> list[JointSpec] (L110)
  • const SAWYER_DESCRIPTION = RobotDescription(...) (L153) — sim baseline; sdk_kind="open", hal.sim=None (no MuJoCo HAL adapter today) + hal.real="openral_hal.sawyer_real:SawyerRealHAL".
  • const SAWYER_REAL_DESCRIPTION = make_real_description(SAWYER_DESCRIPTION, sdk_kind="closed_with_api") (L213) — inherits the shared hal; what robots/sawyer/robot.yaml mirrors.

python/hal/src/openral_hal/panda_mobile.py

In-process digital-twin HAL for the panda_mobile embodiment (Franka 7-DoF arm on a holonomic 3-DoF base). Built by build_hal for the manifest-driven ManifestHALLifecycleNode and by tests; ROS node entrypoint is the generic packages/openral_hal_node/.

  • const PANDA_MOBILE_BASE_JOINT_NAMES: list[str] — Base joints [base_x, base_y, base_yaw], derived from PANDA_MOBILE_DESCRIPTION.base_joints (not hardcoded). (L84)
  • const PANDA_MOBILE_JOINT_NAMES: list[str] — Full 11-DoF order: base (3) + arm (7, role-derived) + gripper (1, role-derived) — all from the description. (L100)
  • const PANDA_MOBILE_DESCRIPTION: RobotDescription — Canonical RobotDescription, loaded from robots/panda_mobile/robot.yaml at module import. Single source of truth for joint metadata + sim_joint_name overrides; the arm/base/gripper name constants above derive from it via JointSpec.role. (L77)
  • class PandaMobileHAL — In-process digital-twin HAL, PandaMobileHAL(*, initial_pose=None, dt_s=0.05, description=None). description is the loaded manifest (build_hal threads it, so panda_mobile_vslam reports its own sensors); None falls back to robots/panda_mobile/robot.yaml. Joint layout (base from base_joints, arm/gripper by role) is read per instance from it. Routes BODY_TWIST → planar Euler integration of (vx, vy, wz); routes JOINT_POSITION → 7-vec arm targets or 11-vec base+arm+gripper targets. (L121)
  • connect() -> None (L198) — Idempotent; flips the connected flag.
  • disconnect() -> None (L202) — Idempotent; clears the connected flag.
  • read_state() -> JointState (L206) — Fresh 10-DoF snapshot; raises ROSConfigError if called before connect().
  • send_action(action: Action) -> None (L219) — Applies the action to in-memory state; accepts JOINT_POSITION / BODY_TWIST / CARTESIAN_DELTA / GRIPPER_POSITION, each reading its matching Action field. No-ops while e-stop is latched. Raises ROSConfigError for an unsupported mode or a missing/mis-shaped payload.
  • estop() -> None (L276) — Latch the e-stop flag; subsequent send_action calls no-op until reset_estop.
  • reset_estop() -> None (L287) — Clear the e-stop latch; caller asserts the cause has been resolved.
  • (property) estop_latched -> bool (L292)
  • (property) base_pose -> tuple[float, float, float] (L297) — Current base (x, y, yaw) for tests / odom publishers.
  • (property) base_twist -> tuple[float, ...] (L302) — Last commanded base body twist (vx, vy, vz, wx, wy, wz); zeroed once a non-BODY_TWIST action is sent, and reads zero once no BODY_TWIST arrived for _TWIST_STALE_PERIODS (2) control periods — the base only moves on a command, so a stopped stream is a still base.
  • module const _PANDA_MOBILE_ARM_JOINT_NAMES (L88) — the 7 Franka arm joint names within the 11-DoF panda_mobile order.
  • module const _PANDA_MOBILE_GRIPPER_JOINT_NAME (L96) — the 1-DoF gripper joint name.
  • module const _PLANAR_TWIST_EPS (L113) — tolerance for detecting a non-planar BODY_TWIST component.
  • (removed: the base_sim_joint_names re-export wrapper — callers now import openral_core.extract_base_sim_joint_names directly.)

python/hal/src/openral_hal/depth_cloud.py

Reusable, robot-agnostic depth-camera → sensor_msgs/PointCloud2 plumbing for deploy-sim HAL nodes (octomap_server source → kernel world-collision check). Pure SensorSpec adapters + the ROS msg builder; the ray-cast synth lives in openral_sim.backends.depth_camera. - module const _OPTICAL_IN_MJCAM (L39) — REP-103 optical frame (x right, y down, z forward) expressed in the MuJoCo camera frame, as a diagonal flip-y/z matrix. - module const _MIN_EYE_DISTANCE_M = 1e-6 (L42) — degenerate eye→lookat distance below which azimuth/elevation are undefined. - module const _VIEWER_LOOKAT_LIFT_M = 0.7 (L47) — deploy-viewer orbit-pivot lift off the floor onto the robot body. - module const _VIEWER_PULLBACK_M = 2.0 (L48) — deploy-viewer eye pullback so cluttered mobile-manip scenes show the whole robot. - module const _VIEWER_CAMERA_PREFS (L254) — default prefer substrings for preferred_viewer_camera_id ("agentview", "top", "frontview", "front"). - is_depth_sensor(spec) -> bool — True when spec.modality in ("depth", "point_cloud") and it carries pinhole intrinsics (required to back-project). (L54) - module const BODY_TO_OPTICAL_QUAT_XYZW = (-0.5, 0.5, -0.5, 0.5) (L66) — REP-103 body frame → its optical child, rpy (-π/2, 0, -π/2). - depth_optical_frame_id(spec) -> str (L69) — The optical frame a depth sensor's sim raster, cloud and registered colour are stamped in: spec.frame_id when it is already an *_optical_frame, else its REP-103 child <frame_id>_optical_frame (a body-convention camera mount like the ZED's zed_camera_link). Stamping optical data with the body frame rotated every consumer's geometry. - mjcf_camera_name(spec) -> str — Resolves the backing MJCF <camera> name: spec.metadata["mjcf_camera"] if set (the sim camera name can differ from the ROS sensor name), else spec.name. (L92) - robot_self_body_ids(model, sim_joint_names) -> frozenset[int] — Every MJCF body sharing a first-_-token prefix with one of the robot's sim_joint_names (mobilebase0/robot0/gripper0). Passed as synthesize_depth_image(exclude_body_ids=…) so the depth raster self-filters the robot out of its own world map. (L143) - depth_synth_kwargs(spec, *, max_range_default, render_size=None) -> dict — Maps a depth SensorSpec to depth-synth kwargs (intrinsics + min/max_range_m, falling back to max_range_default); with render_size, intrinsics are rescaled via openral_core.scale_intrinsics_to to match the render resolution. (L105) - resolve_base_body_name(model, *, description=None) -> str | None — Resolves the MJCF body backing the robot's base_frame (first base joint's prefix + _base, else mobilebase0_base/base/robot0_base/base_link); None if none exist. Backs the depth self-filter anchor and viewer fallback — not the TF/extrinsic parent, which is resolve_base_frame_body_name. (L175) - resolve_base_frame_body_name(model, *, description=None) -> str | None — Resolves the MJCF body whose pose base_frame actually carries on /tf (ADR-0095): tries the base joint's _support body (robosuite's arm-mount plate) before delegating to resolve_base_body_name. They differ only on robosuite/RoboCasa mobile manipulators, whose chassis root sits well below the arm mount MobileBaseBridge publishes as base_link; fixed-base arms resolve identically either way. (L211) - preferred_viewer_camera_id(model, *, prefer=("agentview","top","frontview","front")) -> int — Picks the MJCF camera the viewer should open from: first camera name matching a prefer substring, else the first declared camera, else -1 if none. Consumed by initial_viewer_camera. (L257) - initial_viewer_camera(*, model, data, description=None) -> tuple[tuple[float,float,float], float, float, float] — Opening free-camera pose (lookat, distance, azimuth_deg, elevation_deg) for the viewer (always mjCAMERA_FREE, so mouse orbit/zoom stay live). Eye placed at the preferred_viewer_camera_id camera with orbit pivot on the robot base when one exists, else delegates to base_aligned_free_camera. (L410) - apply_robosuite_visual_geomgroups(opt, model) -> bool — For a robosuite/RoboCasa model, hides collision shells (geomgroup 0) and shows textured visual geoms (group 1) so mujoco.viewer renders textures instead of collision boxes. Gated on a robosuite signature, not geom counts (dm_control/gym-aloha put visuals in group 0). Used by sim run --view. (L297) - base_aligned_free_camera(*, model, data, base_body_name=None, azimuth_offset_deg=135.0, elevation_deg=-25.0, distance_scale=2.0, max_distance_m=3.5) -> tuple[tuple[float,float,float], float, float, float] — Fallback free-camera framing for camera-less models: centres on the robot base, offset by its world yaw, at distance_scale × model.stat.extent capped at max_distance_m. Falls back to model.stat.center with no yaw when base_body_name is absent. (L328) - camera_optical_tf_to_base(*, model, data, camera_name, base_body_name) -> tuple[tuple[float,float,float], tuple[float,float,float,float]] — Live (translation_xyz, quat_xyzw) of the camera optical frame (REP-103) expressed in the base body, for broadcasting base_frame → <camera>_optical_frame. Raises ROSConfigError if camera/body absent. (L464) - pointcloud2_from_points_xyz(points, *, frame_id, stamp=None, rgb=None) -> PointCloud2 — Packs an (N, 3) float32 array into an unordered XYZ-float32 sensor_msgs/PointCloud2, the layout octomap_server's cloud_in expects; with rgb each point also carries the PCL rgb field. (L516) - cloud_from_depth_frame(depth, rgb, k, optical_in_base, *, max_planar_range_m=None) -> tuple[NDArray[np.float32], NDArray[np.uint8] | None] (L585) — A registered RGB-D frame as a base_frame cloud: every measured pixel lifted through k (the points_from_depth_grid pinhole convention, rays cached per raster size and K by _pixel_rays, float32) and moved by optical_in_base, each point coloured by the pixel it came from (None when rgb is not an (H, W, 3) raster of the depth's size); max_planar_range_m keeps base-plane XY distances within the sensor range. Matches Isaac's Camera.get_pointcloud on the same frame to a median 0.85-1.8 mm (point counts identical). - depth_image_from_grid(depth, *, frame_id, stamp=None) -> Image — Packs an (H, W) float32 metric-depth raster into a 32FC1 sensor_msgs/Image (0.0 = no measurement) for nvblox's projective depth integrator. (L642) - points_from_depth_grid(depth, *, fx, fy, cx, cy, clearing=None, max_range_m=None) -> NDArray[np.float32] — Back-projects an (H, W) metric-depth raster into an (N, 3) optical-frame cloud, dropping 0.0 pixels. clearing re-adds the self-filter's clearing rays at max_range_m so OctoMap can clear cells behind the robot's silhouette; without it those cells can never clear. Raises ROSConfigError on a shape mismatch or a marked mask with no max_range_m. (L679) - depth_grid_from_image(msg) -> NDArray[np.float64] — Inverse of depth_image_from_grid: decodes a driver's depth Image into an (H, W) metre raster, accepting 32FC1 (metres) and 16UC1 (millimetres, rescaled). Raises ROSConfigError on an unsupported encoding or a length mismatch. Used by VisionAttachmentBridge to read real wrist-camera depth. (L787) - camera_info_from_intrinsics(*, width, height, fx, fy, cx, cy, frame_id, stamp=None, distortion_model="plumb_bob", d=()) -> CameraInfo — Builds a sensor_msgs/CameraInfo for a synthesised image — K=[fx,0,cx;0,fy,cy;0,0,1], identity R, P mirroring K (no baseline); distortion defaults to zero plumb_bob (MuJoCo ray-cast has none), a renderer with a lens (Isaac) passes its distortion_model + d (none → zero plumb_bob; empty d → that model's zero coefficients, so an equidistant fisheye stays one). Callers pass the stride-scaled intrinsics so the model matches the rasterised image. (L834) - intrinsics_from_camera_info(msg) -> IntrinsicsPinhole — Inverse of camera_info_from_intrinsics, duck-typed: fx=k[0], fy=k[4], cx=k[2], cy=k[5] at the message's width/height. How a consumer projects through the driver's live calibration instead of a manifest's nominal intrinsics (OpenArm ZED Mini: fx 1498.18 published vs 960 declared, Thor cell 2026-10-02). Raises ROSConfigError on a missing / non-9 k, a non-positive focal length or a zero resolution (the all-zero uncalibrated default). Used by segmenter_node.projection_geometry. (L895) - resample_mask_nearest(mask, shape) -> NDArray[np.bool_] — Nearest-neighbour resample of a boolean mask on pixel centres (floor((r + 0.5) * H_src / H_dst)), to bring an RGB-resolution mask onto the same camera's depth raster before backproject_masked_depth. Raises ROSConfigError on a non-2-D mask, non-positive shape, or aspect ratios differing by >1 % (a different crop, not a different resolution). (L944)

python/hal/src/openral_hal/aloha.py

HAL adapter for the Trossen ALOHA bimanual setup, plus the MuJoCo digital twin.

  • class AlohaHAL(HALBase) — Real-hardware adapter for the 14-DoF ALOHA over the Interbotix XS SDK. Takes description= (loaded manifest; None → ALOHA_REAL_DESCRIPTION). Stays on HALBase, not RosControlHAL: the driver owns the bus, like SO100FollowerHAL. Its command topics are ros2_control names a real ALOHA does not expose, so send_action reports success and moves nothing — issue #250 holds the xs_sdk wire contract and the on-rig checks needed before changing the defaults. Its e-stop, by contrast, targets what a real ALOHA does expose: estop_recovery = RESTART_REQUIRED, and estop() cuts torque on every arm namespace through an attached InterbotixStopSeam. (L414)
  • __init__(*, left_arm_controller=..., right_arm_controller=..., left_gripper_controller=..., right_gripper_controller=..., joint_state_topic='/joint_states', arm_namespaces=('follower_left', 'follower_right'), publish_fn=None, state_fn=None, staleness_limit_s=None, stop_timeout_s=5.0, description=None) — staleness_limit_s=None reads the manifest's window (0.2 s, formerly a code-only default). — The former estop_topic (/aloha/estop, a broadcast for a watchdog node that does not exist in this repo) is gone; arm_namespaces names the xs_sdk robots the stop torques off. (L487)
  • arm_namespaces() -> list[str] — The xs_sdk robot namespaces the stop torques off; the InterbotixStoppable surface the lifecycle node reflects on. (L525)
  • attach_torque_stop(seam) -> None — Bind the InterbotixStopSeam after construction (build_hal runs before any ROS node exists); rejects a non-seam with ROSConfigError. (L529)
  • (property) last_stop_report -> DownstreamStopReport | None — The DownstreamStopReporting surface the lifecycle heartbeat and FATAL log read. (L543)
  • connect() -> None (L549)
  • read_state() -> JointState (L566)
  • send_action(action) -> None — Splits the 14-D action 4-ways across per-arm + per-gripper controllers. (L592)
  • estop() -> None — Drop the connection flag first, then torque_enable(cmd_type='group', name='all', enable=false) on every arm namespace (each attempted even if an earlier one refused), record a DownstreamStopReport (stopped only when every arm acknowledged; controller_states per arm torque_off / torque_unknown), raise ROSEStopRequested. Torque off leaves the ViperX arms limp (no brakes) — the same outcome as the rig's hardware e-stop and the only stop xs_sdk offers. (L656)
  • private: _require_connected, _cut_torque
  • class InterbotixStopSeam(Protocol) — torque_enable(robot_name, *, group, enable, timeout_s) -> TriggerReport; production InterbotixXSTransport, unit lane SimTorqueSeam. (L386)
  • torque_enable(robot_name, *, group, enable, timeout_s) -> TriggerReport — /<robot_name>/torque_enable with cmd_type='group'; success is the call completing. (L394)
  • class InterbotixStoppable(Protocol) — arm_namespaces() + attach_torque_stop(seam); what the lifecycle node's _attach_interbotix_transport reflects on. (L402)
  • arm_namespaces() -> list[str] (L405)
  • attach_torque_stop(seam) -> None (L409)
  • class AlohaMujocoHAL(MujocoArmHAL) — MuJoCo digital twin for the 14-DoF bimanual ALOHA; thin manifest-driven wrapper around MujocoArmHAL (bimanual amendment). All wiring lives in ALOHA_DESCRIPTION.sim: gym_aloha:bimanual_viperx_transfer_cube URI, explicit joint_qpos_addr / actuator_index (left arm 0-5, left gripper 6, right arm 8-13, right gripper 14 — skipping the negative-finger slots), two grippers on a normalized [0, 1] channel (0 closed, 1 open; NORMALISED writes, AFFINE_LOW_HIGH reads, mapped onto the finger range [0.021, 0.057] m) with mirror_actuator_index (positive finger + negative finger), keyframe_index: 0 (seeds the fingers inside that range). (L735)
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5) — Forwards to self._init_from_description(ALOHA_DESCRIPTION, …). (L773)
  • _aloha_joint_specs() -> list[JointSpec] (L171)
  • _default_publish(topic, msg) -> None (L723)
  • module const _ALOHA_LEFT_ARM_JOINTS: tuple[str, ...] (L116) — left-arm joint names, ViperX 300 order.
  • module const _ALOHA_LEFT_GRIPPER_JOINT: str (L124) — left gripper joint name.
  • module const _ALOHA_RIGHT_ARM_JOINTS: tuple[str, ...] (L125) — right-arm joint names.
  • module const _ALOHA_RIGHT_GRIPPER_JOINT: str (L133) — right gripper joint name.
  • module const _ALOHA_JOINT_NAMES: tuple[str, ...] (L135) — full 14-DoF joint order: left arm + left gripper + right arm + right gripper.
  • module const _PI: float = 3.14159 (L147) — truncated π matching the YAML manifest's string form, used by _ALOHA_ARM_POSITION_LIMITS so the manifest-vs-HAL drift guard stays byte-equal.
  • module const _ALOHA_ARM_POSITION_LIMITS: dict[str, tuple[float, float]] (L148) — per-joint-group position limits from the ViperX 300 data sheet.
  • module const _ALOHA_GRIPPER_POSITION_LIMITS: tuple[float, float] (L160)
  • module const _ALOHA_ARM_AXIS: dict[str, tuple[float, float, float]] (L161) — per-joint-group rotation axis.
  • module const _DEFAULT_LEFT_ARM_CONTROLLER: str (L363) — AlohaHAL's default left-arm xs_sdk controller name.
  • module const _DEFAULT_RIGHT_ARM_CONTROLLER: str (L364) — default right-arm controller name.
  • module const _DEFAULT_LEFT_GRIPPER_CONTROLLER: str (L365) — default left-gripper controller name.
  • module const _DEFAULT_RIGHT_GRIPPER_CONTROLLER: str (L366) — default right-gripper controller name, matching the udev-pinned CAN dev-id convention.
  • module const _DEFAULT_ALOHA_JOINT_STATE_TOPIC: str (L370) — default /joint_states topic.
  • module const _DEFAULT_ALOHA_ARM_NAMESPACES: tuple[str, str] (L378) — the xs_sdk robot namespaces estop torques off (follower_left, follower_right).
  • module const _TORQUE_GROUP_ALL = "all" (L379) — the TorqueEnable group name covering every joint of one arm.
  • const ALOHA_DESCRIPTION = RobotDescription(...) (L218) — sim baseline; sdk_kind="open", hal.sim="openral_hal.aloha:AlohaMujocoHAL" + hal.real="openral_hal.aloha:AlohaHAL".
  • const ALOHA_REAL_DESCRIPTION = make_real_description(ALOHA_DESCRIPTION, sdk_kind="closed_with_api") (L351) — inherits the shared hal; what robots/aloha_bimanual/robot.yaml mirrors.

python/hal/src/openral_hal/ur.py

HAL adapters for the Universal Robots UR5e and UR10e arms (sim, MuJoCo).

  • class UR5eHAL(MujocoArmHAL) — UR5e HAL (MuJoCo-backed). Thin manifest-driven wrapper; __init__ forwards to self._init_from_description(UR5e_DESCRIPTION, …). (L345)
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5) (L371)
  • class UR10eHAL(MujocoArmHAL) — UR10e HAL (MuJoCo-backed). Same shape as UR5eHAL. (L389)
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5) (L401)
  • ur5e_with_sensors(catalog_ids=None) -> RobotDescription (L289)
  • ur10e_with_sensors(catalog_ids=None) -> RobotDescription (L315)
  • _ur_joint_specs(velocity_limits, effort_limits) -> list[JointSpec] (L120)
  • module const _UR_JOINT_NAMES: list[str] (L59) — 6 arm joint names, shared by UR5e/UR10e.
  • module const _UR5E_POSITION_LIMITS: dict[str, tuple[float, float]] (L70) — shared by UR5e and UR10e (same joint range family).
  • module const _UR5E_VELOCITY_LIMITS: dict[str, float] (L79)
  • module const _UR5E_EFFORT_LIMITS: dict[str, float] (L89)
  • module const _UR10E_VELOCITY_LIMITS: dict[str, float] (L100)
  • module const _UR10E_EFFORT_LIMITS: dict[str, float] (L110)
  • const UR5e_DESCRIPTION = RobotDescription(...) (L158) — sim manifest; all MuJoCo wiring lives in UR5e_DESCRIPTION.sim.
  • const UR10e_DESCRIPTION = RobotDescription(...) (L223) — sim manifest; all MuJoCo wiring lives in UR10e_DESCRIPTION.sim.

python/hal/src/openral_hal/ur_real.py

Real-hardware HAL adapters for UR5e / UR10e via ros2_control + ur_robot_driver (URCap / RTDE).

  • class UR5eRealHAL(_URRealHAL) — Real UR5e via ur_robot_driver. Takes description= (loaded manifest; None → UR5e_REAL_DESCRIPTION). (L197)
  • class UR10eRealHAL(_URRealHAL) — Real UR10e via ur_robot_driver. Takes description= (loaded manifest; None → UR10e_REAL_DESCRIPTION). (L254)
  • class _URRealHAL(RosControlHAL) — Shared real-HW base (controller / topic defaults + deadman_topic + dashboard_stop_service). estop_recovery = RESTART_REQUIRED. (L87)
  • vendor_stop_services() -> list[str] — [dashboard_stop_service] (default /dashboard_client/stop). (L171)
  • _vendor_stop(seam) -> str — After the base deactivated scaled_joint_trajectory_controller, calls the dashboard stop (std_srvs/Trigger), which stops the external_control program on the pendant so the robot performs a controlled stop and the driver's control connection ends; a refused Trigger raises ROSRuntimeError so the report reads unacknowledged. Recovery: operator restarts the program (/dashboard_client/play + resend_robot_program), relaunches the HAL node, re-aligns. (L175)
  • module const _UR_CONTROLLER_NAME: str (L60) — default ur_robot_driver JointTrajectoryController name.
  • module const _UR_JOINT_STATE_TOPIC: str (L61)
  • module const _UR_DEADMAN_TOPIC: str (L62)
  • module const _UR_DASHBOARD_STOP_SERVICE: str (L69) — default ur_robot_driver dashboard stop service (std_srvs/Trigger).
  • const UR5e_REAL_DESCRIPTION = make_real_description(UR5e_DESCRIPTION, sdk_kind="closed") (L76) — inherits the shared hal; what robots/ur5e/robot.yaml mirrors.
  • const UR10e_REAL_DESCRIPTION = make_real_description(UR10e_DESCRIPTION, sdk_kind="closed") (L81) — inherits the shared hal; what robots/ur10e/robot.yaml mirrors.

python/hal/src/openral_hal/so100_follower.py

SO100FollowerHAL — wraps lerobot's SO-100 follower arm USB driver.

  • module const _SO100_JOINT_NAMES: list[str] (L84) — canonical joint order, matching lerobot's bus motor dict order.
  • module const _RESET_MAX_RAD_S = 0.5 (L99) — reset_to_pose ramp speed cap.
  • module const _RESET_MIN_S = 1.0 (L100) — reset_to_pose ramp minimum duration.
  • module const _RESET_STEP_HZ = 30.0 (L101) — reset_to_pose ramp waypoint rate.
  • module const _RESET_DEADBAND_RAD (L104) — below this max joint delta the arm counts as already at the target and the ramp is skipped.
  • module const _ESTOP_VENDOR_STOP (L113) — "torque_off (IEC 60204-1 category 0)": the stop category, named in every DownstreamStopReport so a change of category is a visible decision (issue #526).
  • module const _ESTOP_TORQUE_RETRIES = 5 (L116) — retries per servo for the e-stop's Torque_Enable write and read-back (matches lerobot's own MotorsBus.disconnect).
  • module const _TORQUE_DISABLED = 0 (L118) — Feetech Torque_Enable value for torque off.
  • class SO100FollowerHAL — HAL adapter wrapping lerobot's SO-100/SO-101 follower. Takes description= (the loaded manifest, so an SO-101 deploy reports so101_follower); None falls back to SO100_DESCRIPTION. Declares estop_recovery = RESETTABLE and implements EStopObservableHAL: after a proven torque-off (every servo reads back off) its E-stop keeps the motor bus open read-only, so read_state_estopped() keeps the arm visible, and reset_estop() re-arms the torque watcher, sets Goal_Position := Present_Position (read back) and enables torque (read back) before accepting commands; any failure cuts torque again. An unproven stop closes the bus and reset_estop() refuses: restart the lifecycle node. Implements DownstreamStopReporting. (L372)
  • __init__(port='/dev/ttyUSB0', *, calibrate_on_connect=False, id=None, calibration_dir=None, max_relative_target=None, staleness_limit_s=None, robot=None, description=None) (L424) — staleness_limit_s=None reads the manifest's window.
  • (property) last_stop_report -> DownstreamStopReport | None — The DownstreamStopReporting surface the lifecycle node reads (ERROR "completed" vs FATAL); None before the first e-stop and after connect(). (L481)
  • connect() -> None — Open USB serial connection; builds lerobot's config with disable_torque_on_disconnect=True set explicitly (the category-0 stop, not a library default) and clears last_stop_report. On the real bus it installs _hold_pose_on_torque_enable and arms a FeetechTorqueWatcher (bus ids + baud rate) before lerobot's connect() enables torque; a watcher that fails to arm is a ROSRuntimeError and nothing is energized (issue #545). (L491)
  • disconnect() -> None — Close USB, disable motor torque (idempotent); then retires the torque watcher: clean (q) when lerobot's disconnect returned, fail-closed (pipe closed, watcher cuts torque itself) when it raised. (L631)
  • _require_torque_watcher() -> None [private] — Called before every bus write (send_action, each reset_to_pose waypoint): if the armed watcher has exited, logs hal.torque_watcher.lost and calls estop() (raises ROSEStopRequested). No-op without a watcher. (L650)
  • _stop_torque_watcher(*, clean: bool) -> None [private] — Retire _torque_watcher (if any) via FeetechTorqueWatcher.stop. estop() calls it with clean=report.stopped. (L672)
  • read_state() -> JointState — Joint state in radians. (L680)
  • read_state_estopped() -> JointState — EStopObservableHAL: joint state through the read-only session a proven e-stop keeps (get_observation only, never a write); ROSRuntimeError without one. (L697)
  • send_action(action: Action) -> None — Forward one step to the SO-100 motor bus. (L734)
  • reset_to_pose(pose: list[float]) -> None — Explicit maintenance/test ramp from current → target (speed-capped _RESET_MAX_RAD_S, never shorter than _RESET_MIN_S and never sped up for a large move, _RESET_STEP_HZ waypoints). Refuses (ROSConfigError, before any bus write) a non-finite value or one outside the loaded manifest's position_limits — never clips. The lifecycle node exposes it at /openral/<robot>/reset_to_pose; skill startup uses the runner's safety-kernel path. (L765)
  • estop() -> None — Drop the connection flag first, then _cut_torque(), record the DownstreamStopReport, raise ROSEStopRequested whose message says whether the stop was acknowledged. A failure is never suppressed. (L837)
  • _cut_torque(robot) -> DownstreamStopReport [private] — Writes Torque_Enable=0 to every servo (lerobot's MotorsBus.write waits for the status packet) and reads it back, attempting every servo even after a failure (controller_states per servo torque_off / torque_on / torque_unknown). stopped only when every servo read back torque off; not connected, or a robot with no motor bus to verify, is stopped=False. Proven, the session stays open (detail notes "bus kept open read-only"); otherwise robot.disconnect(), and a close failure is part of the failure. (L882)
  • reset_estop() -> None — ResettableLifecycleEStopHAL: after a proven stop, re-arm the torque watcher (real bus; outside the bus lock, aborting if an estop() landed meanwhile), Goal_Position := Present_Position read back (_hold_pose_on_torque_enable), enable torque and read Torque_Enable back on every servo; only then connected again. Any failure cuts torque again and raises ROSRuntimeError: proven, the session is kept (arm observable); not proven, it is closed and last_stop_report records an unacknowledged stop; no session (unproven stop) refuses: restart. (L964)
  • _require_connected(operation: str), _obs_to_positions(obs) [@staticmethod], _action_to_lerobot(action)
  • _joint_values_to_lerobot(step) -> dict[str, float] (module-level) — THE single manifest-order → lerobot {"<joint>.pos": …} unit conversion (rad→deg arm joints, [0,1]→[0,100] gripper); both _action_to_lerobot and the reset_to_pose ramp route through it so a calibration/range change can never apply to one actuation path and not the other. (L302)
  • _deg_to_rad(deg) -> float (L297)
  • _rad_to_deg(rad) -> float (L322)
  • _hold_pose_on_torque_enable(bus) -> None (L327) — Wraps lerobot's bus.enable_torque (the call configure()'s torque_disabled() block re-enables torque through) so every torque-on first writes Goal_Position := Present_Position per servo, reads it back, and raises ROSRuntimeError (torque never enabled) on a mismatch. An STS3215 enabling torque drives to its goal register, which reads 0 after power-up (bench SO-101), so without this a connect could jump. Installed by connect() on the real bus.
  • const SO100_DESCRIPTION = RobotDescription(...) (L123)
  • so100_with_sensors(catalog_ids=None) -> RobotDescription — Copy of SO100_DESCRIPTION with catalog sensors attached; None defaults to the LeRobot reference loadout (["logitech/c920"]). (L266)

python/hal/src/openral_hal/feetech_torque_watcher.py

Out-of-process torque-off for a Feetech servo bus when the HAL process dies (issue #545, hazard-log Entry 081). Stdlib + scservo_sdk + structlog only; spawned by file path with python -P so it never pays the openral_hal import.

  • cut_torque(port: str, servo_ids: Sequence[int], baudrate: int, *, open_retries: int = _OPEN_RETRIES) -> dict[int, str] (L86) — Open port (up to open_retries tries), write Torque_Enable=0 (register 40, protocol 0) to every id with _TORQUE_RETRIES tries each and read it back; per id torque_off / torque_on / torque_unknown: <why>, every id attempted. Raises OSError if the port never opens.
  • main(argv=None) -> int (L182) — Watcher entry point: --port --baudrate --ids --parent-pid. Ignores SIGINT/SIGHUP, prints armed, then waits on the parent's pidfd (0.1 s getppid() poll without one) and on stdin: q → exit 0 without touching the bus; parent death or EOF without q → cut_torque (on EOF from a HAL still alive whose port will not open — lerobot>=0.7's rustypot bus holds the tty exclusively — _kill_parent SIGKILLs the HAL, logs hal.torque_watcher.killing_hal_holding_port, and the reopen gets the _KILL_WAIT_S budget), log hal.torque_watcher.torque_off / ..._unproven / ..._port_unavailable, exit 0 / 1 / 2.
  • class FeetechTorqueWatcher (L239) — Handle on a running watcher (proc).
  • spawn(port, servo_ids, baudrate, *, armed_timeout_s=10.0) -> FeetechTorqueWatcher [@classmethod] (L251) — Start the watcher in its own session for the calling process and wait for armed; RuntimeError (watcher killed) otherwise.
  • (property) alive -> bool — True while the watcher process has not exited (non-blocking poll). (L292)
  • stop(*, clean: bool, timeout_s=5.0) -> int | None (L296) — clean=True sends q (caller proved torque off); clean=False closes the pipe so the watcher cuts torque itself. Returns the exit code, None if it had to be killed.

python/hal/src/openral_hal/galaxea_a1.py

Real Galaxea A1 HAL (its MuJoCo twin is the manifest-driven MujocoArmHAL, #740). OpenRAL stays ROS 2 / Python 3.12; the operator's official ROS 1 Noetic SDK runs out of process behind a literal IPv4-loopback JSON-lines sidecar. No vendor source, binary, or message package is distributed.

  • class GalaxeaA1HAL(HALBase) (L611) — Six-axis joint-position + normalized-gripper adapter. Takes description= (loaded manifest; None keeps GALAXEA_A1_DESCRIPTION). read_state/send_action use a cached snapshot/latest target so network I/O stays off the hot path. Commands fail closed on stale state/status, unaccepted motor bits, non-finite values, target misalignment, or an excessive feedback-relative step. estop asks the sidecar to stop its owned ROS 1 stack, records a DownstreamStopReport (DownstreamStopReporting), and always raises ROSEStopRequested.
  • connect() -> None (L743) — Connect to the sidecar (sends the hello handshake with joint names/limits/timeouts/masks); requires one complete fresh snapshot. Raises ROSRuntimeError if already connected.
  • disconnect() -> None (L778) — Close the sidecar transport idempotently.
  • read_state() -> JointState (L783) — Return the latest non-stale six-joint feedback snapshot.
  • send_action(action: Action) -> None (L795) — Queue one validated joint or normalized-gripper target; raises ROSConfigError for an unsupported control mode.
  • health() -> HALHealthReport (L850) — Cached hardware health for the lifecycle diagnostics heartbeat (sidecar address, feedback/status ages, motor status, relay state, staged/forwarded targets).
  • (property) last_stop_report -> DownstreamStopReport | None (L735) — Report of the last estop(); None before the first and after connect().
  • estop() -> None (L872) — Drop the connection flag first, then stop the sidecar-owned ROS 1 stack (bounded, SIGINT then SIGKILL). The sidecar's estopped confirmation is the acknowledgement (stopped=True, joint_tracker/serial_driver/roscore = exited); a refusal, timeout or link drop is recorded as stopped=False with the error as detail — never escaping as anything but ROSEStopRequested, which it always raises.
  • module const _JOINT_NAMES (L71) — six arm_jointN names.
  • module const _JOINT_LIMITS (L72) — per-joint (min, max) position limits, official A1 URDF.
  • module const _JOINT_ORIGINS_XYZ (L80) — per-joint URDF origin translation, transcribed from the official A1 URDF.
  • module const _JOINT_ORIGINS_RPY (L88) — per-joint URDF origin rotation, transcribed from the official A1 URDF.
  • module const _PROTOCOL_VERSION = 1 (L96) — sidecar wire-protocol version sent in the hello handshake.
  • module const _ESTOP_SIDECAR_PROCESSES (L101) — ("joint_tracker", "serial_driver", "roscore"), what the sidecar's e-stop stops; named in the DownstreamStopReport.
  • module const _ESTOP_VENDOR_STOP (L102) — "ros1_sidecar_estop", the report's vendor_stop label.
  • module const _GRIPPER_STATUS_INDEX (L97) — index of the gripper's status code within the sidecar's status array.
  • module const _MAX_TCP_PORT = 65536 (L98) — upper bound accepted for the sidecar's loopback TCP port.
  • module const _MAX_STATUS_MASK = 0xFFFFFFFF (L103) — bit-mask upper bound for a motor status/error mask.
  • const GALAXEA_A1_DESCRIPTION (L106) — The A1 RobotDescription (real HAL + the twin's sim: block), mirrored by robots/galaxea_a1/robot.yaml: official A1 URDF joint names/limits, assets.urdf galaxea:a1, sidecar deadlines, motor masks, 0..104 mm normalized gripper mapping, and calibrated D455 front / D405 wrist RGB observation contracts. Collision primitives are absent until their redistribution/lowering provenance is cleared.
  • tools/galaxea_a1_ros1_sidecar.py — Python-3.8 ROS 1 process owning roscore, signal_arm/single_arm_node.launch, and the official mobiman/jointTracker_demo_node binary. A sidecar-owned relay is the sole publisher to /arm_joint_command_host, gated LOCKED → ARMING → ACTIVE (aligned to target + feedback before forwarding); a gripper command while not ACTIVE is refused fail-closed. A lease timeout, malformed command, stale feedback, motor fault, disconnect, or e-stop stops the whole owned process group.
  • tools/run_galaxea_a1_sidecar.sh — Docker launcher requiring an explicit operator-provided image and SDK path; mounts both read-only, claims only the selected serial device. --check-only verifies image, SDK files, cache, serial ownership, loopback port, container name, and process lock without opening the serial device or starting a container.

Galaxea A1 hardware bring-up and the LingBot-VA rSkill deploy runbook moved to robots/galaxea_a1/README.md.

python/hal/src/openral_hal/h1.py

MuJoCo digital twin for the Unitree H1 humanoid (Menagerie MJCF). Contract validator only — falls without an S0 cerebellum, so gravity must stay disabled in closed-loop tests. Unlike G1/UR/Franka/SO-100, the H1 menagerie ships torque actuators, so this HAL runs a software PD position loop every physics step.

  • class H1MujocoHAL(MujocoArmHAL) — Takes description= (loaded manifest; None → H1_DESCRIPTION). 19-DoF humanoid HAL driving mujoco_menagerie/unitree_h1/h1.xml (legs + torso + arms, no wrists); thin manifest-driven wrapper around MujocoArmHAL. Its rollout (_H1Twin) makes a command's row the PD target and computes tau = kp*(target - q) - kv*dq every physics step clamped to ctrlrange, so the public action contract stays "position targets in radians" — mirroring how unitree_sdk2 wraps torque control in a position loop on real hardware. (L345)
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5) (L387)
  • class _H1Twin(_SoftwarePDTwin) [private] — The H1's rollout: mujoco_twin._SoftwarePDTwin with no torque before the first command; reset_to_pose makes the snapped pose the target and a reconnect clears it.
  • module const _H1_LEFT_LEG_JOINTS: tuple[str, ...] (L85) — left-leg joint names.
  • module const _H1_RIGHT_LEG_JOINTS: tuple[str, ...] (L92) — right-leg joint names.
  • module const _H1_TORSO_JOINTS: tuple[str, ...] (L99) — torso joint name(s).
  • module const _H1_LEFT_ARM_JOINTS: tuple[str, ...] (L100) — left-arm joint names.
  • module const _H1_RIGHT_ARM_JOINTS: tuple[str, ...] (L106) — right-arm joint names.
  • module const _H1_JOINT_NAMES: tuple[str, ...] (L112) — full 19-DoF joint order (legs + torso + arms).
  • module const _H1_POSITION_LIMITS: dict[str, tuple[float, float]] (L127) — per-joint position limits.
  • module const _H1_EFFORT_LIMITS: dict[str, float] (L154) — per-joint actuator effort ceiling used to clamp the software PD loop's torque.
  • module const _H1_VELOCITY_LIMITS_BY_GROUP: dict[str, float] (L181) — per-kinematic-group velocity limits.
  • module const _H1_KP_BY_GROUP: dict[str, float] (L316) — per-kinematic-group PD proportional gain.
  • module const _H1_KV_BY_GROUP: dict[str, float] (L324) — per-kinematic-group PD derivative gain.
  • _h1_group(joint_name) -> str — Return the kinematic group token (hip / knee / ankle / torso / shoulder / elbow) for joint_name. (L194)
  • _h1_parent_child(joint_name) -> tuple[str, str] — Return (parent_link, child_link) for an H1 joint. (L199)
  • _h1_joint_specs() -> list[JointSpec] — Build the 19 JointSpecs from the joint-name tuples + the per-joint limit tables. (L235)
  • _h1_pd_gains() -> dict[str, tuple[float, float]] — Per-joint (kp, kv) for the software PD loop (kv = 0.05*kp; kp sized so a 1-rad error roughly saturates each actuator's ctrlrange). (L327)
  • const H1_DESCRIPTION = RobotDescription(...) (L258) — Sim baseline; sdk_kind="open", hal.sim="openral_hal.h1:H1MujocoHAL", hal.real=None (sim-only). In-code mirror of robots/h1/robot.yaml (the runtime source; build_hal passes it as description=); drift-guarded against robots/h1/robot.yaml.

python/hal/src/openral_hal/h2.py

MuJoCo digital twin for the Unitree H2 humanoid on Unitree's official unitree_mujoco MJCF (asset ref unitree:h2). 31 joints in unitree_sdk2 motor order; gravity-on twin with a software PD over the MJCF's torque motor actuators that also runs during idle_step; by default the free joint is pinned upright (ADR-0087 glide), s0_controller="agile_velocity" runs NVIDIA WBC-AGILE as a sim-only S0 on the unpinned base. Real hardware is unitree_real.UnitreeHgRealHAL (H2_REAL_DESCRIPTION).

  • H2S0Controller = Literal["none", "agile_velocity"] (L106) — the s0_controller choices.
  • class H2MujocoHAL(MujocoArmHAL) — __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5, body_twist_dt_s=None, s0_controller="none", description=None); description=None → H2_DESCRIPTION. "none": on connect, lowers the pin so the lowest foot-sphere surface sits on z = 0, zeroes ctrl and captures the hold targets from qpos. "agile_velocity": resolves + SHA-checks the AGILE bundle (h2_agile_velocity_config) and runs _H2AgileTwin. Refuses an unknown controller, an S0 with gravity off, a missing / mismatched bundle (ROSConfigError). (L655)
  • s0_controller -> H2S0Controller (property) (L753) — the active S0 mode.
  • s0_fallen -> bool (property) (L758) — the AGILE fall latch (torques cut).
  • s0_clamp_counts -> dict[str, int] (property) (L763) — policy ticks whose target was clamped to the MJCF joint range, per joint.
  • class _H2AgileTwin(_S0PolicyTwin, _SoftwarePDTwin) [private] (L425) — agile_velocity: _on_load checks the policy rate divides the timestep, enables the floor, stands the default pose with the feet on z = 0; every decimation-th physics step _policy_tick feeds the policy (free-joint qvel[3:6], quat as xyzw, held command, 31 joints by name), clamps its 14 targets to jnt_range (counted, first clamp per joint logged hal.h2.s0_controller.target_clamped) and writes targets + kp/kd into the software PD; the other 17 joints use the policy's training gains. _compose refuses a policy joint or a whole-vector row (ROSCapabilityMismatch); reset_to_pose re-seats the base upright on the floor and re-arms; fall guard from _S0PolicyTwin (pelvis < 0.6 m).
  • _lowest_foot_z(model, data) -> float [private] (L398) — world z of the lowest foot-sphere surface (no foot sphere: ROSConfigError).
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5, body_twist_dt_s=None, description=None) (L442) — body_twist_dt_s=None is one control period (MujocoTwinRollout._resolve_twist_interval).
  • class _H2Twin(_GlideTwin, _SoftwarePDTwin) [private] (L363) — The H2's rollout, both building blocks: the glide pin then the PD every physics step (actions and idle slices), the loaded pose held from load on (hold_pose_on_load); _on_load lowers the pin so the lowest foot-sphere surface sits on z = 0 and zeroes ctrl (no foot sphere: ROSConfigError); the pin is kept across reset_to_pose, as on the G1.
  • module const _H2_JOINT_NAMES: tuple[str, ...] (L126) — the 31 joints in SDK motor-index order (legs 0–11, ankle roll before pitch; waist 12–14; arms 15–28; head 29–30).
  • module const _H2_LIMITS: dict[str, tuple[float, float, float, float]] (L146) — (lower, upper, effort, velocity) per joint, verbatim from unitree_ros H2.urdf @ 41dec58c.
  • module const _H2_PARENT_CHILD: dict[str, tuple[str, str]] (L183) — URDF (parent_link, child_link) per joint.
  • module const _H2_MJCF_TREE_ORDER / _H2_QPOS_ADDR: dict[str, int] (L244) — MJCF tree order (head between waist and arms) and the joint→qpos map it implies; qvel is qpos − 1. Carried into H2_DESCRIPTION.sim.joint_qpos_addr / joint_qvel_addr.
  • module const _H2_PD_BY_GROUP / _H2_WRIST_PD (L326) — PD (kp, kd): body from unitree_rl_mjlab h2_constants.py @ 1425b15f, head from unitree_sdk2 h2_ankle_swing_example.cpp @ 8e1b9275.
  • _h2_joint_specs() -> list[JointSpec] (L218) — Build the 31 JointSpecs.
  • _h2_pd_gains() -> dict[str, tuple[float, float]] (L343) — Per-joint (kp, kd).
  • const H2_DESCRIPTION = RobotDescription(...) (L254) — Sim baseline of robots/h2/robot.yaml (sdk_kind="open"; the manifest mirrors H2_REAL_DESCRIPTION); hal.real = UnitreeHgRealHAL with robot_model: h2 / s0_policy: agile_velocity, action_spec.control_freq_hz=50; assets unitree:h2 for both URDF and MJCF, supported_control_modes=[joint_position, body_twist], tags h2/unitree_h2/humanoid/mobile_base, no sensors (unverified upstream).

python/hal/src/openral_hal/_h2_agile_velocity.py

The H2 AGILE LEAPP export stepped on onnxruntime as the C++ InferenceController does (feedback tensors looped, seeded from the bundle's safetensors) — the H2 twin's sim-only S0 and the unit rollout test's runner.

  • const AGILE_LICENSE_POSTURE = RSkillLicensePosture.NVIDIA_OPEN_MODEL (L35).
  • h2_agile_velocity_config() -> Path (L43) — resolve_leapp_config of config/h2/policies/agile_velocity.yaml (SHA-256 pins verified; missing bundle → ROSConfigError naming the hf download).
  • class LeappVelocityPolicy (L53) — __init__(leapp_yaml): loads the spec, ONNX session and feedback seed; refuses a bundle whose quat / command / joint element names differ from the mapped layout. Attributes obs_joint_names, action_joint_names, default_joint_pos, default_kp, default_kd, frequency_hz, last_outputs.
  • reset() -> None (L149) — re-seed the feedback tensors.
  • step(*, ang_vel_b, quat_xyzw, command, joint_pos, joint_vel) -> tuple[targets, kp, kd] (L154) — one tick, in action_joint_names order; non-finite output → ROSConfigError.

python/hal/src/openral_hal/_unitree_h2_assets.py

Fetches Unitree's official H2 description files at pinned commits, each beside its own meshes, with per-file SHA-256 — backs the unitree:h2 asset ref.

  • ensure_h2_urdf() -> Path (L304) — unitree_ros @ 41dec58c robots/h2_description/H2.urdf + 34 meshes into $OPENRAL_CACHE_DIR/unitree_h2/unitree_ros/<sha>/…. Raises ROSConfigError on a failed download or digest mismatch (nothing installed).
  • ensure_h2_mjcf() -> Path (L315) — unitree_mujoco @ 1eb6642e unitree_robots/h2/h2_mujoco.xml (+ scene.xml, 32 meshes); returns a derived bare-robot MJCF (h2_mujoco.openral-<hash>.xml) with Unitree's URDF wrist-pitch fix applied (_derive_mjcf; fails closed if the pinned body moved). Same failure contract.
  • const UNITREE_ROS_SHA: str (L55) — pinned unitreerobotics/unitree_ros commit.
  • const UNITREE_MUJOCO_SHA: str (L57) — pinned unitreerobotics/unitree_mujoco commit.

python/hal/src/openral_hal/_simpler_assets.py

Fetches SimplerEnv's Google robot URDF (google_robot_meta_sim_fix_fingertip.urdf) + the 34 meshes it names from the Apache-2.0 simpler-env/ManiSkill2_real2sim at a pinned commit with per-file SHA-256 (nothing vendored) — backs the simpler: asset ref.

  • ensure_simpler_file(name) -> Path (L128) — The URDF name (only google_robot_meta_sim_fix_fingertip.urdf) @ cd45dd27 into $OPENRAL_CACHE_DIR/simpler/<sha>/, keeping the repository layout so its relative mesh refs resolve. Raises ROSConfigError on another name, a failed download or a digest mismatch.
  • const MANISKILL2_REAL2SIM_SHA: str (L26) — pinned simpler-env/ManiSkill2_real2sim commit (the submodule SimplerEnv 52a5088 pins).

python/hal/src/openral_hal/_galaxea_a1_assets.py

Fetches Galaxea's A1 URDF + 9 STL meshes from the unlicensed userguide-galaxea/robot_descriptions at a pinned commit with per-file SHA-256 (nothing vendored) — backs the galaxea:a1 asset ref.

  • ensure_a1_urdf() -> Path (L64) — a1_description/ @ 72008ea9 into $OPENRAL_CACHE_DIR/galaxea_a1/<sha>/; returns a derived urdf/a1.urdf whose package://mobiman/urdf/A1/meshes/ refs are rewritten to ../meshes/. Raises ROSConfigError on a failed download or digest mismatch.
  • ensure_a1_mjcf() -> Path (L214) — The MuJoCo twin MJCF (issue #740), compiled from ensure_a1_urdf() through MjSpec into galaxea_a1/<sha>/derived-<module-source hash>/a1.xml: the vendor's fixed gripper1_axis / gripper2_axis turned into the prismatic slides their own <axis> / <limit 0..0.03> declare, sim-only <position> actuators (arm_joint1..6 + gripper on gripper1_axis, each clamped at the URDF effort), an <equality> coupling gripper2_axis to it, joint damping/armature and contact excludes (the two fingers, base_link/arm_seg1). The gains say nothing about the real A1 loop. Raises ROSConfigError when the fetch fails or mujoco is missing.
  • const GALAXEA_DESCRIPTIONS_SHA: str (L44) — pinned userguide-galaxea/robot_descriptions commit.

python/hal/src/openral_hal/_robotwin_aloha_agilex_assets.py

Range-reads RoboTwin 2.0's aloha-agilex URDF + its 34 meshes out of embodiments.zip (MIT HF dataset TianxingChen/RoboTwin2.0) at a pinned revision, per-file SHA-256 — backs the robotwin:aloha_agilex asset ref.

  • fetch_aloha_agilex_files() -> Path (L181) — Downloads every pinned file not yet cached into $OPENRAL_CACHE_DIR/robotwin_aloha_agilex/<rev12>/ (the archive's own layout, so relative mesh refs resolve) and drops the .verified stamp; presence only. Raises ROSConfigError when huggingface_hub is missing or a remote archive read fails (each read wrapped by _remote), and a bare OSError for a local cache write, so the resolver maps them to AssetFetchError / AssetRefError.
  • ensure_aloha_agilex_urdf() -> Path (L223) — Fetches, then verifies every SHA-256 (skipped once .verified exists) and returns arx5_description_isaac.urdf; a mismatching file is deleted. Raises ROSConfigError.
  • ensure_aloha_agilex_mjcf() -> Path (L569) — The MuJoCo twin MJCF (robotwin:aloha_agilex as an mjcf), compiled from the URDF via MjSpec and cached under derived-<module-source hash>/: wheels, castors and the rear lr_/rr_ arms welded, COLLADA visuals dropped where the link has other geometry, else converted to a 4 mm-decimated OBJ beside the MJCF (box2_Link, the frame carrying the arms, #760; the *_castor_link housings; camera_link1/2), raising ROSConfigError on COLLADA outside the handled subset, one <position> actuator per manifest joint in manifest order at ARM_JOINT_RANGES (finger joint7 at the URDF's 0..0.04765 m), forces clamped at EFFORT_LIMIT, an <equality> joint8 = joint7 per gripper (RoboTwin's config.yml mimic), and base/link1 + finger contact excludes. Sim-only gains. Raises ROSConfigError when the fetch fails or mujoco is not installed.
  • const ARM_JOINT_RANGES: tuple[tuple[float, float], ...] (L259) — joint1..6 ranges, in lock-step with robots/aloha_agilex/robot.yaml (asserted by python/core/tests/test_assets.py).
  • const EFFORT_LIMIT: float (L268) — actuator force clamp, the manifest's effort_limit.
  • const ROBOTWIN_ASSETS_REVISION: str (L52) — pinned dataset commit.

python/hal/src/openral_hal/_robosuite_assets.py

Composes a robosuite (>= 1.5, MIT) robot with its default base and grippers into one MJCF, as robosuite.robots.Robot.load_model does — backs the robosuite:<robot> asset ref (panda_mobile's PandaOmron).

  • compose_robot_mjcf(name) -> Path (L35) — create_robot + robot_base_factory(default_base) + one gripper_factory(default_gripper[arm], idn="0_<arm>") per arm (robosuite's own idns, so joints are mobilebase0_* / robot0_* / gripper0_right_*); makes every group-1 (visual) geom non-colliding (robosuite leaves the Omron torso column collidable, so visual-only viewers dropped it, #760); writes $OPENRAL_CACHE_DIR/robosuite/<version>-<install-path hash>-<module-source hash>/<name>.xml once (the pinned clone and the PyPI wheel share a version), meshes pointing into the installed package. Raises ROSConfigError without robosuite >= 1.5 or for an unregistered name.

python/hal/src/openral_hal/_behavior_r1pro_assets.py

Fetches BEHAVIOR-1K's R1 Pro URDF and visual meshes (behavior-1k/omnigibson-robot-assets, MIT HF dataset) at a pinned revision and derives a loadable copy, and the deploy-sim MJCF twin built from it — backs the behavior:r1pro asset ref (urdf and mjcf).

  • ensure_r1pro_urdf() -> Path (L89) — Derived URDF at $OPENRAL_CACHE_DIR/behavior_r1pro/<rev12>/r1pro.urdf; downloads models/r1pro/urdf/{r1pro.urdf,meshes/*} on first use. Raises ROSConfigError when huggingface_hub is missing or the download fails.
  • derive_urdf(urdf_xml, urdf_dir) -> str (L69) — Mesh filenames made absolute (joined, not resolved: HF snapshot files are extension-less blob symlinks) and every <collision> whose mesh is absent dropped (upstream references unshipped meshes/collision/*-col-*.obj).
  • ensure_r1pro_mjcf() -> Path (L228) — The MuJoCo twin at $OPENRAL_CACHE_DIR/behavior_r1pro/<rev12>/mjcf/<sha16>/r1pro.xml (key: this module's source + the derived URDF): every visual mesh doubled as a convex-hull collision geom (group 3, contype 2 / conaffinity 1), swerve steer/wheel joints fixed, planar base_x/base_y/base_yaw on base_link (qpos 0..2), 20 <position> actuators (torso, arms, finger_joint1; forcerange = URDF effort), a finger_joint2 = finger_joint1 equality per hand, a checker floor. Raises ROSConfigError on a failed fetch or a missing / refusing mujoco.
  • const BEHAVIOR_ASSETS_REVISION: str (L56) — pinned dataset commit, the one the r1pro manifest's limits came from.

python/hal/src/openral_hal/_floating_base.py

Shared planar-base helpers for the sim HAL shell and the MuJoCo twins: the one planar-twist rule and tolerance, the one holonomic integrator, and the ADR-0087 pin read/write (the glide twin itself is mujoco_twin._GlideTwin). Sim-only.

  • type alias BasePin = tuple[float, float, float, float] (L35) — (x, y, yaw, z0) the free joint is pinned to.
  • capture_base_pin(qpos) -> BasePin (L43) — (x, y, yaw, z) from a free joint's qpos[0:7].
  • integrate_planar_twist(pin, vx, vy, wz, dt) -> BasePin (L55) — Euler-integrate a body-frame planar twist (rotated into world by the current yaw; yaw wrapped): the one holonomic integrator (the glide pin, the shell's qpos base path). The OpenAMRobot's exact arc stays its own: a differential model.
  • write_base_pin(data, pin) -> None (L73) — Write the upright pose into qpos[0:7] and zero qvel[0:6].
  • validate_planar_body_twist(action, backend, *, differential=False) -> tuple[float, float, float] (L84) — The one planar-twist rule (the shell's _check_twists, every twin's _planar_twist): (vx, vy, wz); raises ROSConfigError for an empty or wrong-width row, a non-zero linear-z / angular-x / angular-y, or (differential) a non-zero vy (returned as 0.0) — beyond PLANAR_TWIST_EPS.
  • const PLANAR_TWIST_EPS = 1e-9 (L40) — The one tolerance of that rule (float noise, not a command): panda_mobile's and the real Unitree HAL's value; it replaced the shell's and the OpenAMRobot twin's 1e-6.

python/hal/src/openral_hal/_pinned_files.py

Single-file pinned download with SHA-256 verification and atomic install, shared by _g1_walking and _unitree_h2_assets (the clone-based fetchers use _pinned_clone).

  • sha256_file(path) -> str (L30) — Streamed hex SHA-256 of a file.
  • fetch_pinned_file(url, expected_sha256, destination, *, what, user_agent=...) -> None (L47) — Reuse a verified cached file, else download to a per-process temp file, verify, os.replace into place. Raises ROSConfigError on download failure, digest mismatch, or a cache directory / install error (fail-closed). Reuse watch: the canonical single-file pinned fetcher.
  • is_download_failure(exc) -> bool (L118) — whether a urllib.error.URLError / TimeoutError / ConnectionError is in the __cause__ chain: separates "could not download" (skippable missing dependency; unitree: → AssetFetchError) from a SHA-256 mismatch or cache error (never skipped; unitree: → AssetRefError).

python/hal/src/openral_hal/flexiv_rizon4.py

MuJoCo digital twin for the Flexiv Rizon 4 — 7-DoF cobot with whole-body force sensitivity (0.1 N). Structurally identical to the UR / Franka sim HALs: position actuators, no gripper, no floating base, no PD-loop overrides — a clean MujocoArmHAL subclass.

  • class Rizon4MujocoHAL(MujocoArmHAL) — 7-DoF HAL driving mujoco_menagerie/flexiv_rizon4/flexiv_rizon4.xml via MujocoArmHAL. Thin manifest-driven wrapper; __init__ forwards to self._init_from_description(RIZON4_DESCRIPTION, …). (L180)
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5) (L211)
  • _rizon4_joint_specs() -> list[JointSpec] — Build the 7 JointSpecs from the joint-name tuple + per-joint limit tables. (L111)
  • module const _RIZON4_JOINT_NAMES: tuple[str, ...] (L65) — 7 arm joint names.
  • module const _RIZON4_POSITION_LIMITS: dict[str, tuple[float, float]] (L80)
  • module const _RIZON4_VELOCITY_LIMIT: float (L94)
  • module const _RIZON4_EFFORT_LIMITS: dict[str, float] (L100)
  • const RIZON4_DESCRIPTION = RobotDescription(...) (L132) — Sim baseline; sdk_kind="open", hal.sim=None (derived MujocoArmHAL), hal.real=None (sim-only). In-code mirror of robots/rizon4/robot.yaml; drift-guarded against robots/rizon4/robot.yaml.

python/hal/src/openral_hal/openarm.py

MuJoCo digital twin for the Enactic OpenArm v2 bimanual humanoid arm. Thin manifest-driven MujocoArmHAL subclass (two sim.grippers entries) — v2's native <position> actuators with per-class PD baked into the MJCF mean the HAL just writes target → ctrl and steps, no software PD loop needed.

  • class OpenArmMujocoHAL(MujocoArmHAL) (L0) — 16-DoF (7 arm + 1 gripper per side) bimanual HAL driving enactic/openarm_mujoco/v2/openarm_v20_bimanual.xml; thin manifest-driven wrapper around MujocoArmHAL. All wiring (MJCF URI fetched via ensure_openarm_v2_mjcf, joint/actuator maps, gripper config) lives in OPENARM_DESCRIPTION.sim. (L486) ADR-0102 slot-group reassembly, the stale-tick guard and last_committed_tick are inherited from MujocoArmHAL.send_action (this class held its own copy until 2026-09-24).
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5) — Forwards to self._init_from_description(OPENARM_DESCRIPTION, …). (L524)
  • _openarm_arm_joint_specs(names, position_limits, side) -> list[JointSpec], _openarm_gripper_joint_spec(name, side, position_limits) -> JointSpec, _openarm_joint_specs() -> list[JointSpec] (L167, L190, L206)
  • module const _OPENARM_LEFT_ARM_JOINTS: tuple[str, ...] (L106) — left-arm joint names.
  • module const _OPENARM_RIGHT_ARM_JOINTS: tuple[str, ...] (L107) — right-arm joint names.
  • module const _OPENARM_LEFT_GRIPPER_JOINT: str (L108) — left gripper joint name.
  • module const _OPENARM_RIGHT_GRIPPER_JOINT: str (L109) — right gripper joint name.
  • module const _OPENARM_JOINT_NAMES: tuple[str, ...] (L111) — full 16-DoF joint order.
  • module const _OPENARM_LEFT_ARM_POSITION_LIMITS: dict[str, tuple[float, float]] (L122)
  • module const _OPENARM_RIGHT_ARM_POSITION_LIMITS: dict[str, tuple[float, float]] (L131)
  • module const _OPENARM_LEFT_GRIPPER_POSITION_LIMITS: tuple[float, float] (L143)
  • module const _OPENARM_RIGHT_GRIPPER_POSITION_LIMITS: tuple[float, float] (L144)
  • module const _OPENARM_ARM_EFFORT_LIMITS: dict[str, float] (L150)
  • module const _OPENARM_GRIPPER_EFFORT_LIMIT: float (L166)
  • module const _OPENARM_ARM_VELOCITY_LIMIT: float (L169)
  • module const _OPENARM_GRIPPER_VELOCITY_LIMIT: float (L170)
  • const OPENARM_DESCRIPTION = RobotDescription(...) (L250) — Shared baseline for sim and real (name="openarm_v2", 16 revolute joints). sdk_kind="open" (the whole real path — openarm_can + openarm_ros2 — is Apache-2.0, unlike UR/Franka's closed vendor runtime). hal.sim=None (derived MujocoArmHAL, so the manifest's head_zed sensor and collision_geometry reach the twin) + hal.real_bringup="openral_hal_openarm:real_bringup.launch.py". One flat hal.parameters.defaults block serves both entrypoints; build_hal drops the keys each constructor doesn't accept. Drift-guarded against robots/openarm/robot.yaml.

python/hal/src/openral_hal/openarm_real.py

Real-hardware adapter for the Enactic OpenArm v2. Commands openarm_bringup's ros2_control stack (750 Hz) rather than SocketCAN directly: Skill → Action → this adapter → four command topics → controller_manager → openarm_hardware SystemInterface → openarm_can → SocketCAN → Damiao motors.

  • module const _LEFT_ARM_CONTROLLER: str (L92) — default left-arm JointTrajectoryController name.
  • module const _LEFT_GRIPPER_CONTROLLER: str (L93) — default left-gripper controller name.
  • module const _RIGHT_ARM_CONTROLLER: str (L94) — default right-arm controller name.
  • module const _RIGHT_GRIPPER_CONTROLLER: str (L95) — default right-gripper controller name, matching the udev-pinned CAN dev-id convention.
  • module const _JOINT_STATE_TOPIC: str (L96)
  • module const _LEFT_CAN_INTERFACE: str (L97) — default left CAN interface name.
  • module const _RIGHT_CAN_INTERFACE: str (L98) — default right CAN interface name.
  • class OpenArmRealHAL(GroupedRosControlHAL) (L113) — 16-DoF real-HW adapter, same action layout as OpenArmMujocoHAL: four groups (left arm 7, left gripper 1, right arm 7, right gripper 1) on GroupedRosControlHAL, which owns the all-or-nothing fan-out, the read-by-name read_state and ADR-0102 slot groups. Adds bus preflight (connect() refuses a missing/wrong-type/down CAN link rather than reporting connected over a dead bus). estop_recovery = RESETTABLE.
  • __init__(description=None, *, left_can_interface='openarm_left', right_can_interface='openarm_right', left_arm_controller=..., left_gripper_controller=..., right_arm_controller=..., right_gripper_controller=..., joint_state_topic='/joint_states', publish_fn=None, state_fn=None, staleness_limit_s=None, require_can_links=True) — Rejects a manifest that is not 16-joint or whose joints lack sim_joint_name (the URDF joint name, i.e. the logical→ros2_control mapping).
  • connect() -> None (L220) — Bus preflight (openral_core.can.preflight_can_links) then delegates to RosControlHAL.connect; refuses a CAN link that is missing, is not a CAN device, or is down.
  • estop_recovery = RESETTABLE — the deactivated controllers hold and the CAN bus stays configured, so the inherited reset_estop re-activates all four through the same controller_manager seam and reconnects only once the manager confirms every one active.
  • health() -> HALHealthReport (L253) — Cached per-bus state from connect(); performs no I/O.
  • const OPENARM_REAL_DESCRIPTION = make_real_description(OPENARM_DESCRIPTION, sdk_kind="open") (L110) — Shares kinematics, safety envelope and HAL entrypoints with the sim baseline.

python/hal/src/openral_hal/_slot_group.py

Reassembles a slot-dispatched inference tick into one whole-robot command (ADR-0102): _dispatch_slots emits one Action per non-discard slot (four for OpenArm v2 bimanual), each published separately through the safety kernel, so a HAL that commands one vector must recombine them.

  • module const GRIPPER_MODES (L50) — (GRIPPER_POSITION, GRIPPER_BINARY), the modes composed from Action.gripper + ee_name rather than from a joint row.
  • compose_slot_group(actions, joint_names, *, hold=None) -> list[float] (L64) — Merges one tick's slots into a full-dof target row, addressing by name (never position): JOINT_* slots via Action.joint_names, gripper slots via ee_name. hold (joint → kept target) fills the joints a group may leave uncommanded (a mobile base and lift under an arms-only skill). Raises ROSConfigError for an unnamed joint slot, an unknown joint/end-effector, a joint claimed twice, or any other joint left uncommanded; the placement itself is slot_group_targets, after refusing any mode it cannot place.
  • slot_group_targets(actions, joint_names) -> list[float | None] (L124) — compose_slot_group's placement with the same strictness for a group that need not cover every joint: skips jointless slots (BODY_TWIST, Cartesian, FOOT_PLACEMENT, COMPOSITE_MODE; private _JOINTLESS_MODES), returns None for uncommanded joints, and raises ROSConfigError for any unreadable joint-addressing slot (no payload / ee_name / joint_names, unknown name, row too short, a non-position joint-space mode) or a joint written twice — so a None means "not commanded", never "commanded unreadably". Used by sim_attached.gripper_targets_action.
  • compose_slot_group_action(group, joint_names, *, hold=None) -> Action — compose_slot_group wrapped into the one-step full-dof JOINT_POSITION Action (joint_position_command) that MujocoArmHAL and OpenArmRealHAL apply. (L225)
  • joint_position_command(row, first) -> Action (L248) — A one-step full-dof JOINT_POSITION action of row, stamped like first (stamp, confidence; no tick fields): the composed command a HAL applied for a slot group (compose_slot_group_action, the GR00T WBC twin's S0 + arm row).
  • refuse_stale_tick(tick, last_committed) -> int — The session-less slot-group tick rule (hazard log Entry 036), applied by TickWatermark only to actions with no runner_session_id (0): raises ROSRuntimeError ("stale slot group") when 0 < tick <= last_committed (a replayed group of an already-committed tick), EXCEPT tick == 1 while last_committed > 1, a restarted runner's fresh numbering, which is adopted by returning 0. SlotGroupStager only checks with it and moves its watermark on commit, so one delayed tick-1 slot of the old runner cannot drop the watermark before a new group is applied. A replay of tick 1 after tick 1 committed is refused. Reached through TickWatermark.check. (L268)
  • class TickWatermark (L319) — The committed (runner_session_id, tick_index) every slot-group HAL refuses replays against (Entry 036 Amendment 3). Same session: tick <= tick watermark is refused, tick 1 included. A different non-zero session is a new runner: admitted, adopted only by commit (never by check, so a stray slot cannot move it), and on adoption the old session is retired — every later action carrying it raises ("superseded"). Session-less 0 falls back to refuse_stale_tick. reset() (disconnect) clears the watermark but keeps retired sessions refused. Attributes tick, session. Held by SlotGroupStager (so by every HAL that stages).
  • check(tick, *, session) -> None (L361) — Raise on a replay; the watermark does not move.
  • commit(tick, *, session) -> None (L384) — Record an applied (session, tick); retires the previous session on a change.
  • reset() -> None (L391) — Clear the watermark, keep the retired set.
  • class SlotGroupStager (L397) — Buffers at most one tick, keyed by (runner_session_id, tick_index), and holds the committed watermark (TickWatermark). stage(action) -> list[Action] | None returns the group when the last slot lands, else None; it first refuses a replay (TickWatermark.check); the watermark moves, and a new runner session is adopted, only on commit(group). admit(action) / commit_tick(action) apply the same watermark to UNGROUPED ticked actions (the runner's starting-pose ramp and approach share its tick counter), so a restarted runner's ramp renumbers the HAL instead of leaving its first policy tick under the old watermark. discard() (E-stop) keeps the watermark, so a pre-stop tick replayed after the stop is refused; reset() (disconnect) clears it. A tick change mid-group raises ROSRuntimeError rather than committing survivors and leaving one arm stale; the slot that exposed it opens the new tick instead of being dropped with it. A slot of the staged tick that declares another group size than its first slot discards the tick and raises (never released short — a real HAL would dispatch a partial tick — nor overrun; #683). A slot from a different non-zero runner session instead drops the old session's partial tick silently (logged hal.slot_group.stale_partial_dropped) — a dead run's half tick is nobody's loss. The one staging machine: used by SimAttachedHAL (so by every MujocoArmHAL twin and every scene-attached backend), GroupedRosControlHAL and ComposedHAL.
  • admit(action: Action) -> None (L480) — Check an ungrouped ticked action against the watermark before it is applied (TickWatermark.check); the watermark does not move.
  • commit_tick(action: Action) -> None (L507) — Record that an ungrouped action was applied: moves the watermark to its (runner_session_id, tick_index) when ticked, and always records it as last_applied_action.
  • stage(action, *, group_size=None) -> list[Action] | None (L541) — see above; group_size overrides action.tick_group_size (a sim backend that steps a fixed-size group of ungrouped slots), and is what a later slot of the tick is compared against.
  • pending -> int [@property] (L438) — count of slots in flight.
  • staged -> tuple[Action, ...] [@property] (L443) — the slots in flight, in arrival order.
  • last_committed_tick -> int [@property] — tick of the last group committed (0 = none since reset). (L448)
  • last_committed_session -> int [@property] — its runner_session_id (0 = none / session-less). (L453)
  • commit(group, *, applied: Action | None) -> None — record that a released group was applied as applied (the composed command sent, None when it cannot be stated); call only after the apply succeeded (the lifecycle node acks this tick). (L468)
  • last_applied_action -> Action | None [@property] — the command the last commit / commit_tick applied (None since reset; discard keeps it). The one accessor the stager-backed HALs expose as their own last_applied_action. (L458)
  • discard() -> int — drop the buffered slots, keep the watermark (estop latch / clear); returns how many slots were dropped. (L517)
  • reset() -> None (L531) — drop the buffered slots, the watermark and last_applied_action (disconnect).

python/hal/src/openral_hal/anvil_openarm_v2.py

MuJoCo digital twin for the Anvil OpenARM 2.0 — Anvil Robotics' manufactured variant of the standard OpenArm v2. Differs from the Enactic v2 twin only in two joint ranges (J1, J6) and a wrist support bracket, baked into the fetched MJCF, so the HAL stays a thin manifest-driven subclass.

  • class AnvilOpenArmV2MujocoHAL(MujocoArmHAL) — 16-DoF (7 arm + 1 gripper per side) bimanual HAL driving models/anvil_openarm_bimanual.xml from the pinned bensonlee5/anvil-openarm-mujoco clone. All wiring lives in ANVIL_OPENARM_V2_DESCRIPTION.sim. Structurally identical to OpenArmMujocoHAL — the Anvil-ness is entirely in the asset. (L372)
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5) — Forwards to self._init_from_description(ANVIL_OPENARM_V2_DESCRIPTION, …). (L413)
  • _anvil_arm_joint_specs(names, position_limits, side) -> list[JointSpec], _anvil_gripper_joint_spec(name, side, position_limits) -> JointSpec, _anvil_joint_specs() -> list[JointSpec] (L160, L184, L204)
  • module const _ANVIL_LEFT_ARM_JOINTS: tuple[str, ...] (L89) — left-arm joint names.
  • module const _ANVIL_RIGHT_ARM_JOINTS: tuple[str, ...] (L90) — right-arm joint names.
  • module const _ANVIL_LEFT_GRIPPER_JOINT: str (L91) — left gripper joint name.
  • module const _ANVIL_RIGHT_GRIPPER_JOINT: str (L92) — right gripper joint name.
  • module const _ANVIL_LEFT_ARM_POSITION_LIMITS: dict[str, tuple[float, float]] (L103) — left-arm per-joint position limits, incl. the Anvil-specific J1/J6 ranges.
  • module const _ANVIL_RIGHT_ARM_POSITION_LIMITS: dict[str, tuple[float, float]] (L112) — right-arm per-joint position limits.
  • module const _ANVIL_LEFT_GRIPPER_POSITION_LIMITS: tuple[float, float] (L122)
  • module const _ANVIL_RIGHT_GRIPPER_POSITION_LIMITS: tuple[float, float] (L123)
  • module const _ANVIL_ARM_EFFORT_LIMITS: dict[str, float] (L128) — per-joint effort limit table.
  • module const _ANVIL_GRIPPER_EFFORT_LIMIT: float (L144)
  • module const _ANVIL_ARM_VELOCITY_LIMIT: float (L148)
  • module const _ANVIL_GRIPPER_VELOCITY_LIMIT: float (L149)
  • const ANVIL_OPENARM_V2_DESCRIPTION = RobotDescription(...) (L217) — Sim baseline (name="anvil_openarm_v2", 16 revolute joints, Anvil's J1/J6 ranges, two wrist RGB SensorSpecs). sdk_kind="open", hal.sim=None (derived MujocoArmHAL), hal.real=None (sim-only; a real driver wrapper is a tracked follow-up). Drift-guarded against robots/anvil_openarm_v2/robot.yaml.

python/hal/src/openral_hal/openamrobot_v2.py

MuJoCo digital twin for OpenAMRobot 2.0 (differential base + DOLD lift + two OpenArm v2 arms). The joint path is the stock manifest-driven MujocoArmHAL; the class adds the wheel-driven base.

  • class OpenAMRobotV2MujocoHAL(MujocoArmHAL) — 20-DoF (3 planar base, lift, 2 × (7 arm + gripper)) twin of the MJCF openarm:openamrobot_v2 builds. The base rolls on upstream's two drive wheels: BODY_TWIST sets their speeds for (vx, wz), held until the next twist and ramped to zero after 0.5 s of sim time without one (diff_drive_controller's timeout); a non-zero vy/vz/wx/wy raises ROSConfigError (the planar rule with the manifest's base_kinematics: differential). base_pose is wheel odometry, base_twist the wheels' measured speed; the base joints' qpos (read_state) is the simulated ground truth. Every other mode takes the joint path (the lift and arms through sim.actuator_index; the base joints are unactuated); a tick with arm and twist slots moves both in one control period. A slot group leaving the role: base / torso joints uncommanded (a 16-D OpenArm rSkill's tick) leaves the wheels and holds the lift (hold_if_uncommanded); an uncommanded arm/gripper joint is still refused. (L295)
  • __init__(*, description, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5, body_twist_dt_s=None) — description is required (build_hal threads the loaded manifest; no in-code mirror). body_twist_dt_s must be one control period (an explicit value off it is refused at connect, MujocoTwinRollout._resolve_twist_interval); the wheel-driven base does not integrate over it. (L331)
  • class _OpenAMRobotV2Twin(MujocoTwinRollout) [private] (L52) — The rollout: _on_load reads the wheel radius (collision cylinder) and half-track (joint anchors) off the compiled model and zeroes odometry; _drive_base sets the target (vx, wz); _per_step integrates odometry from the wheel angles, applies the 0.5 s command timeout and ramps the wheels' twist to the target by upstream's DiffDrive limits (diff_drive_accel_limits) before writing the wheel speeds; read_base_pose / read_base_twist are wheel odometry and the measured twist (ROSRuntimeError unloaded); hold_present_pose (e-stop) also stops the wheels at once; _held_ctrl_targets adds the unactuated base joints at their qpos; _compose refuses (ROSConfigError) a joint row whose base entry sits more than 0.05 m / rad from the measured base (the base has no actuator); reset_to_pose stops the wheels and restarts odometry at the snapped base. _on_load refuses gravity off (the wheels grip only under the base's weight) and reads each wheel's own radius.

python/hal/src/openral_hal/composed.py

One robot HAL composed from part HALs that each own a disjoint set of its joints, by name: an existing arm HAL on a base, without re-implementing either (OpenAMRobot 2.0's real HAL is OpenArmRealHAL + PlatformBaseHAL + HeldJointsHAL).

  • class ComposedHAL — ComposedHAL(*, description, parts, staleness_limit_s=None, **overrides); parts from hal.parameters.defaults.parts, each a ComposedPartSpec (a robot part is built from its own manifest; description threaded when the constructor names it); staleness_limit_s and every override reach the parts whose constructor takes them, over their params. Every joint owned by exactly one part, else ROSConfigError. read_state merges parts by name (oldest stamp; effort only when every part measures it, else empty, never zero-filled) and caches the positions; read_state_estopped (EStopObservableHAL) merges the same way during an e-stop, reading each observable part through its read-only path and the others by read_state (any unreadable part raises, so the node skips the tick); joint rows (padded to robot dof or one per name) are split and re-padded per part; ADR-0102 slot groups are staged here and each part receives only its slots as a group of that size (last_applied_action fills uncommanded joints from the cached read, never a fresh one); GRIPPER_* by ee_name; BODY_TWIST to the part with base_joints. Every share is first refused (ROSRuntimeError) when its part's own e-stop latch is set (estop_latched: a sim part, whose latch would drop the share while the composite acknowledged it), then offered to its part's optional check_action, so a held lift or twist-only base refuses before any part moves. estop stops every part and raises ROSEStopRequested, or re-raises the first part's other error (later ones noted). urdf_joint_states_from_hal = True. Exposes base_pose/base_twist, slot-watermark members, discard_staged_slots, attach_ros_node, and the RosControlDrivable/ControllerStoppable/DownstreamStopReporting members, merged over its ros2_control parts on one controller_manager (the OpenArm arms, a RosControlHAL lift on lift_controller): bindings, joint names and controllers concatenated (a shared topic or joint refused, one joint-state topic required), attach_transport hands each part its own joints by name (_project_state), estop_recovery is RESETTABLE only when every part is, reset_estop re-arms every sim part (a non-ros2_control part with reset_estop) and, when all are RESETTABLE, every ros2_control part (no resettable part at all: ROSConfigError), last_stop_report merges the parts' reports (stopped only when all were acknowledged, detail naming the non-ros2_control parts; None without a ros2_control part or before every report exists; estop_recovery is then absent). (L190)
  • read_state_estopped() -> JointState — The merged state during an e-stop, read-only per part (see above). (L368)
  • connect() — Connect every part; a failure disconnects the ones already up. (L307)
  • disconnect() — Disconnect every part (idempotent per the protocol). (L319)
  • estop() — Stop every part, then raise. (L325)
  • _dispatch(shares) -> None — Every share's optional check_action first, then the sends; a send failing once a part already took its share (or a part's own ROSEStopRequested mid-send) logs hal.composed.partial_dispatch with the cause and stops every part (estop), so the tick is never half-applied.
  • read_state() — Every part's state merged into description.joints order, by name. (L359)
  • send_action(action) — Route action to the part(s) that own what it commands (see module doc). (L416)
  • base_pose [@property] — The base part's (x, y, yaw). (L556)
  • base_twist [@property] — The base part's last body twist. (L564)
  • last_committed_tick [@property] — Tick of the last slot group applied here (all parts). (L572)
  • last_committed_session [@property] — Runner session of that tick. (L577)
  • last_applied_action [@property] — The last whole-robot command applied (a slot group composed, see send_action). (L582)
  • discard_staged_slots() — Drop half-staged slots here and in every part that stages its own. (L586)
  • attach_ros_node(node) — Hand the lifecycle node to every part that needs one (e.g. a ROS base). (L595)
  • command_bindings() — The arm part's controller command topics. (L622)
  • ros2_control_joint_names() — The arm part's URDF joint names on /joint_states. (L632)
  • joint_state_topic [@property] — The arm part's JointState topic. (L640)
  • attach_transport() — Wire the arm part to the live ros2_control transport. (L650)
  • controller_names() — Controllers /openral/estop deactivates (the arm part's). (L667)
  • vendor_stop_services() — The arm part's vendor stop services. (L671)
  • vendor_stop_topics() — The arm part's vendor stop topics. (L675)
  • attach_controller_stop(seam) — Give the arm part the controller-stop seam. (L679)
  • estop_recovery [@property] — How the arm part recovers from an e-stop (the only part with motors to re-arm). (L685)
  • reset_estop() — Re-arm the arm part after an e-stop. (L700)
  • last_stop_report [@property] — The arm part's downstream stop report, marked as covering the arm only. (L733)
  • class ComposedPartSpec(BaseModel) — One parts entry: entry, robot?, joints?, params; unknown keys refused, robot or joints required. (L85)
  • class HeldJointsHAL — HeldJointsHAL(*, description, positions): a part for joints with no command or state interface (the real OpenAMRobot lift); reports the declared positions and refuses any command that would move them (check_action, which ComposedHAL asks first). (L115)
  • check_action(action) -> None — Refuses anything but a JOINT_POSITION equal to the declared positions; send_action is this check. (L171)
  • connect() — Nothing to open; the declared positions are the state. (L149)
  • disconnect() — Idempotent. (L153)
  • read_state() — The declared positions, stamped now. (L157)
  • send_action(action) — Accept only a joint target equal to the declared position. (L167)
  • estop() — Nothing to de-energise here; report the stop like every HAL. (L185)

python/hal/src/openral_hal/platform_base.py

A mobile base driven by its own platform stack, through its odometry and twist topics.

  • class PlatformBaseHAL — PlatformBaseHAL(*, description, odom_topic="/odom", cmd_vel_topic=None, staleness_limit_s=0.5): joints are the three base_joints, positioned at the odometry pose; with cmd_vel_topic=None it is odometry-only (no publisher; a zero BODY_TWIST is a no-op, a non-zero one raises ROSCapabilityMismatch in check_action); with a topic, BODY_TWIST → geometry_msgs/Twist (non-zero vy refused on a differential base; check_action refuses every other mode, without publishing); stale or absent odometry raises ROSPerceptionStale; effort is empty (unmeasured); disconnect destroys its subscription and publisher on the node; estop publishes zero twist (when it has a publisher) and raises. Needs attach_ros_node(node) before connect. (L56)
  • check_action(action) -> tuple[float, ...] — Refuses a non-BODY_TWIST or an unactuable twist and returns the twist; publishes nothing, needs no connection. (L206)
  • attach_ros_node(node) — Create the odometry subscription and twist publisher on node. (L97)
  • connect() — Require the node; odometry freshness is checked at read_state. (L122)
  • disconnect() — Stop the base and release; idempotent. (L131)
  • base_pose [@property] — The latest odometry (x, y, yaw). (L151)
  • base_twist [@property] — The latest odometry body twist. (L156)
  • read_state() — The base joints at the odometry pose. (L172)
  • send_action(action) — Publish a BODY_TWIST; refuse other modes and, on a diff base, any vy. (L192)
  • estop() — Command zero twist, then raise. (L235)

python/hal/src/openral_hal/_openamrobot_v2_assets.py

Build the OpenAMRobot 2.0 MJCF from the vendored robots/openamrobot_v2/openamrobot_v2.urdf (upstream ships no MJCF). The base rolls on upstream's drive wheels.

  • ensure_openamrobot_v2_mjcf(urdf_path=OPENAMROBOT_V2_URDF) -> str — Imports the URDF with MuJoCo's compiler (package:// meshes via resolve_package_uri, OpenArm .dae visuals swapped for their collision .stl), adds unactuated base_x/base_y/base_yaw and base_z joints on base_footprint, an integrated-velocity actuator on each drive wheel (left/right_wheel_joint_vel, after the position actuators), frictionless caster spheres, gravity compensation for everything on the lift carriage, one <position> actuator per non-base manifest joint (OpenArm v2 motor-class gains; stiff lift), armature from the vendored sim_dynamics_openarm_v2.yaml, the mimic-finger equalities, wrist_left/wrist_right cameras on the URDF optical frames, the head ZED camera spliced in from the manifest's sim_placement and a checker floor the robot's geoms collide with. Robot geoms collide with the world, not each other. Cached under $OPENRAL_CACHE_DIR/openamrobot_v2/<sha>/, keyed on the URDF, this module's source, the dynamics profile and the mesh pins; atomic write. Raises ROSConfigError for a missing URDF, an unresolvable mesh or a MuJoCo compile error. Resolved through resolve_asset("openarm:openamrobot_v2", "mjcf"). (L311)
  • compose_openamrobot_v2_walls_mjcf(sinking_boxes=None) -> tuple[str, Path] — Scene composition hook: the twin inside a 20 m x 20 m walled room (inner faces at +/-9.9 m) with three asymmetric pillars (_ROOM_WALLS), a ground-truth world for odometry, /scan and SLAM. sinking_boxes ([[x, y], ...]) adds 0.2 x 0.2 x 2 m boxes on spring-driven vertical slides that leave the lidar plane ~80 s of sim time after connect (gravity-compensated, so the spring alone sets the fall), a costmap clearing target. Returns (xml, meshdir). Used by scenes/deploy/openamrobot_v2_walls.yaml and openamrobot_v2_walls_clearing.yaml. (L384)
  • const OPENAMROBOT_V2_URDF: Path (L68) — the vendored URDF in the repo checkout.
  • const UPSTREAM_URDF: Path (L72) — upstream's own expansion, vendored unmodified (tools/openamrobot_v2_urdf.py).
  • const BASE_Z_JOINT: str (L88) — the passive vertical slide on base_footprint that lets gravity load the wheels.
  • const WHEEL_JOINTS: tuple[str, str] (L90) — upstream's drive-wheel joints, left then right.
  • diff_drive_accel_limits(urdf_path=UPSTREAM_URDF) -> tuple[float, float] (L112) — (m/s², rad/s²) from upstream's Gazebo DiffDrive plugin in the vendored upstream URDF; the twin ramps wheel commands by them. ROSConfigError when the file cannot be read or parsed, or the plugin or a limit is missing. Read at the twin's load, not construction.

python/hal/src/openral_hal/_openamrobot_platform_assets.py

Fetch openamrobot_description (the OpenAMRobot base meshes) from openAMRobot/openamr-platform-sw (MIT code, CERN-OHL-P-2.0 CAD).

  • ensure_openamrobot_description() -> Path (L29) — Idempotently clones the platform repo at the commit openamr-upperbody-sw pins and returns ros2/src/openamrobot_description. Raises ROSConfigError when the clone fails or the package is missing. Registered in PUBLIC_ROS_PACKAGES.

python/hal/src/openral_hal/_pinned_clone.py

  • fetch_pinned_clone(repo_url, sha, repo_dir, *, submodule=None, what=…) -> None — The shared staged-clone + atomic-rename dance for pinned-SHA asset fetchers: shallow clone into a staging dir, checkout the pinned SHA, optional submodule init, os.rename into place (loser of a concurrent race discarded). Raises ROSConfigError when git is missing or any step fails. Reuse watch: the canonical pinned-clone fetcher. (L30)

python/hal/src/openral_hal/_anvil_openarm_v2_assets.py

Vendor the Anvil OpenARM 2.0 MJCF from bensonlee5/anvil-openarm-mujoco — no upstream package ships the Anvil variant.

  • ensure_anvil_openarm_v2_mjcf() -> str — Idempotently clones bensonlee5/anvil-openarm-mujoco at a pinned SHA, initialises its mesh submodule, and returns the bimanual MJCF path. Raises ROSConfigError if git is missing or the clone/submodule init fails. Mirrors _openarm_v2_assets.ensure_openarm_v2_mjcf plus the submodule step. (L60)
  • module const _ANVIL_PINNED_SHA: str (L40) — bump when the generator or the local Anvil spec changes.
  • module const _ANVIL_REPO_URL: str (L41) — the pinned clone's URL.
  • module const _ANVIL_MJCF_REL: str (L42) — the bimanual MJCF's path within the clone.
  • module const _ANVIL_MESH_SUBMODULE: str = "upstream/openarm_mujoco" (L46) — mesh submodule the generated MJCF's meshdir points into; initialised by ensure_anvil_openarm_v2_mjcf.

python/hal/src/openral_hal/_openarm_description_assets.py

Fetch Enactic's public openarm_description ROS package (Apache-2.0) — the package://openarm_description/... meshes robots/openarm/openarm.urdf references — for hosts without a ROS workspace that builds it.

  • ensure_openarm_description() -> Path (L30) — Idempotently clones enactic/openarm_description at a pinned SHA into $OPENRAL_CACHE_DIR/openarm_description/<sha>/ and returns the package root. Raises ROSConfigError when the clone fails or has no package.xml. Registered in openral_hal.ros_package_overlay.PUBLIC_ROS_PACKAGES (Isaac import + Foxglove asset fetch).

python/hal/src/openral_hal/_makermods_metal_assets.py

Fetch the MakerMods Metal arm's metal_description package from makermods-robotics/metal-python-ros at a pinned SHA and derive the single-arm and two-arm station URDF / MJCF at runtime. Upstream ships no LICENSE file, so nothing is vendored; backs the makermods:<metal|metal_station> asset scheme (openral_core.assets._resolve_makermods).

  • const METAL_PINNED_SHA: str (L59) — the pinned upstream commit (master at 2026-09-16); bump deliberately, never a branch.
  • const STATION_ARM_SPACING_M: float (L72) — 0.612 m (±0.02) base-to-base spacing of the two Metal Arm Station arms, measured from the real station's makermods/pen_holder_bi_20260723_161553 recordings (MakerMods publishes none; modelled symmetric); update together with robots/makermods_metal_station/robot.yaml.
  • ensure_metal_description() -> Path (L134) — Idempotently clones the pinned repo into $OPENRAL_CACHE_DIR/makermods_metal/<sha>/ (via _pinned_clone.fetch_pinned_clone) and returns the metal_description package root (package.xml, urdf/, meshes/). Raises ROSConfigError when git is missing, the clone fails, or the pinned tree lacks the package / metal_with_gripper.urdf. Registered in openral_hal.ros_package_overlay.PUBLIC_ROS_PACKAGES.
  • fetch_metal_clone() -> Path (L119) — The fetch step alone: clones the pinned repo into $OPENRAL_CACHE_DIR/makermods_metal/<sha>/ if needed and returns its root. Its ROSConfigError is the host's (offline / no git), which openral_core.assets reports as AssetFetchError; every later layout or derive failure is an AssetRefError.
  • ensure_metal_urdf() -> Path (L224) — The single-arm URDF rooted at base_link (upstream world link and its fixed joint dropped), written once into $OPENRAL_CACHE_DIR/makermods_metal/derived-<sha12>-<key>/, where <key> is a sha256 of this module's source, so any change to the derive step invalidates the cache. Mesh refs stay package://metal_description/…. Raises ROSConfigError (from ensure_metal_description).
  • ensure_metal_station_urdf() -> Path (L236) — The two-arm station URDF: left_ / right_ prefixed copies of the arm on fixed left_mount / right_mount joints at y = ±STATION_ARM_SPACING_M/2 under root station_base. Raises ROSConfigError.
  • ensure_metal_mjcf() -> Path (L370) — The single-arm MJCF, MuJoCo-compiled from the derived URDF (serialised through MjSpec.to_xml, not the process-global mj_saveLastXML) plus OpenRAL's sim-only <position> actuators (joint1..6 + driven finger joint8), joint damping/armature, contact excludes, and an <equality> coupling finger joint7 = −joint8 (the upstream <mimic>). The gains say nothing about the real Damiao CAN loop. Raises ROSConfigError when the fetch fails or mujoco is not installed.
  • ensure_metal_station_mjcf() -> Path (L382) — The two-arm station MJCF (same derivation, per-arm prefixes; left actuators first). Raises ROSConfigError.

python/hal/src/openral_hal/ros_package_overlay.py

Make fetched public ROS description packages resolvable by ROS tools (resource_retriever in foxglove_bridge), which find package:// roots only through the ament index.

  • PUBLIC_ROS_PACKAGES: dict[str, Callable[[], Path]] (L48) — known public description packages → fetcher returning the package root (openarm_description → ensure_openarm_description, metal_description → ensure_metal_description, openamrobot_description → ensure_openamrobot_description). The one registry; openral_sim.backends.isaac_sim._fetch_public_package reads it.
  • fetch_public_package(pkg) -> Path | None (L76) — the known public package's root (fetched if needed), None for any other.
  • public_package_overlay(urdf_xml) -> Path | None (L95) — an ament prefix at $OPENRAL_CACHE_DIR/ament_overlay registering every public package the URDF's package:// URIs name that no AMENT_PREFIX_PATH entry indexes; None when none is needed. deploy_e2e.launch.py prepends it to foxglove_bridge's AMENT_PREFIX_PATH so the 3D panel can fetch the URDF meshes.
  • SIM_SCENE_PACKAGE: str (L41) — openral_sim_scene, the package the Isaac sidecar writes the console's Sim scene GLB into (platform#133); deploy_e2e.launch.py registers it in the bridge's overlay on a sim deploy (_sim_scene_package), so a viewer fetches the GLB as package://openral_sim_scene/<sha12>.glb.
  • SIM_SCENE_LIMIT_BYTES: int (L44) — 10 MB: a larger Sim scene GLB is not written; the topic carries a note and the console greys the layer out.
  • sim_scene_package_root() -> Path (L69) — $OPENRAL_CACHE_DIR/sim_scene, created: the root of SIM_SCENE_PACKAGE.

python/hal/src/openral_hal/_openarm_v2_assets.py

Vendor the upstream enactic/openarm_mujoco v2 MJCF until robot_descriptions bumps its own pin to match.

  • ensure_openarm_v2_mjcf() -> str — Idempotently clones enactic/openarm_mujoco at a pinned v2 SHA into $OPENRAL_CACHE_DIR/openarm_v2/<sha>/, returns the bimanual MJCF path. Raises ROSConfigError when git is missing or the clone fails. Mirrors the pattern used by python/sim/src/openral_sim/backends/so100_robosuite/_assets.py. (L57)
  • module const _OPENARM_V2_PINNED_SHA: str (L40) — bump to track upstream v2 updates.
  • module const _OPENARM_REPO_URL: str (L41) — the pinned clone's URL.
  • module const _OPENARM_V2_MJCF_REL: str (L42) — the bimanual MJCF's path within the clone.

python/hal/src/openral_hal/g1.py

MuJoCo digital twin for the Unitree G1 humanoid. The default stock-Menagerie path provides joint-contract validation + ADR-0087 kinematic glide; s0_controller selects a sim-only S0: "playground_walk" (= walking_enabled=True, ADR-0089's pinned MuJoCo Playground ONNX policy + MJCF) or "gr00t_wbc" (NVIDIA GR00T Decoupled WBC on the unpinned Menagerie twin, arms left to S1).

  • G1S0Controller = Literal["none", "playground_walk", "gr00t_wbc"] (L117) — the s0_controller choices.
  • class G1MujocoHAL(MujocoArmHAL) — 29-DoF humanoid HAL; takes description= (loaded manifest; None → G1_DESCRIPTION). Default mode drives mujoco_menagerie/unitree_g1/g1.xml; playground_walk swaps in the pinned policy-tuned MJCF + ONNX controller; gr00t_wbc keeps the Menagerie MJCF, converts its position actuators to torque motors in memory and never pins the base. Floating-base joint remains implicit world state. (L803)
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5, body_twist_dt_s=None, walking_enabled=False, s0_controller=None, description=None) (L857) — s0_controller=None resolves from walking_enabled; a contradicting pair, an unknown value, or an S0 with gravity off raise ROSConfigError. body_twist_dt_s=None is one control period (MujocoTwinRollout._resolve_twist_interval; an explicit value off it is refused at connect). gr00t_wbc fetches its weights here and logs the nvidia_open_model weight posture (hal.g1.s0_controller).
  • s0_controller -> G1S0Controller (property) (L950) — the active S0 mode.
  • s0_fallen -> bool (property) (L955) — the GR00T WBC fall latch (torques cut).
  • (s0_controller="none" runs mujoco_twin._GlideTwin, ADR-0087's glide.)
  • class _G1WalkTwin(_FreeBaseTwin, _GlideTwin) [private] — playground_walk (ADR-0089): _on_load resets to the knees_bent keyframe and initializes the G1WalkingController (no keyframe: ROSConfigError); a BODY_TWIST runs the policy for round(body_twist_dt_s / timestep) physics steps (_action_steps; one control period unless a wall-paced twin pinned another) with the base free; a tick that carries a twist AND joint / gripper slots is refused before anything moves (ROSConfigError: the walker drives all 29 actuators, so the joint slots would be acknowledged and never applied); joint commands and idle slices keep the glide pin, recaptured where the walk stopped (_on_idle also resets the policy state); read_base_pose is the live free base (_FreeBaseTwin).
  • class _G1Gr00tTwin(_S0PolicyTwin) [private] — gr00t_wbc: _on_load validates the Menagerie layout and the 50 Hz decimation (physics_steps_per_tick), converts the position actuators to torque motors and enables ground contact (ROSConfigError otherwise); _compose splits a tick into the held (vx, vy, wz) command and arm targets (_split_twist; a leg / waist joint or a whole-vector row: ROSCapabilityMismatch) and reports a slot group as the full [S0 targets + arm targets] command (joint_position_command); _per_step runs the 50 Hz policy, fall detection and the 29-joint PD; fall guard, _on_idle and read_base_twist from _S0PolicyTwin (step_action_group adds a debug log); reset_to_pose re-seats the base upright and clears the policy history and the fall latch.
  • module consts _FALL_PELVIS_HEIGHT_M, _FALL_TILT_RAD (L121) — GR00T WBC fall thresholds (0.5 m, 45°).
  • module const _G1_LEFT_LEG_JOINTS: tuple[str, ...] (L132) — left-leg joint names.
  • module const _G1_RIGHT_LEG_JOINTS: tuple[str, ...] (L140) — right-leg joint names.
  • module const _G1_WAIST_JOINTS: tuple[str, ...] (L148) — waist joint names.
  • module const _G1_LEFT_ARM_JOINTS: tuple[str, ...] (L153) — left-arm joint names.
  • module const _G1_RIGHT_ARM_JOINTS: tuple[str, ...] (L162) — right-arm joint names.
  • module const _G1_JOINT_NAMES: tuple[str, ...] (L171) — full 29-DoF joint order (legs + waist + arms).
  • module const _G1_POSITION_LIMITS: dict[str, tuple[float, float]] (L196) — per-joint position limits.
  • module const _G1_VELOCITY_LIMITS_BY_GROUP: dict[str, float] (L233) — per-kinematic-group velocity limits.
  • module const _G1_EFFORT_LIMITS: dict[str, float] (L244) — per-joint effort limits keyed by side-less joint name (Unitree g1_29dof.urdf vendor ratings).
  • _g1_group(joint_name) -> str — Return the kinematic group token (hip / knee / ankle / waist / shoulder / elbow / wrist) for joint_name. (L267)
  • _g1_parent_child(joint_name) -> tuple[str, str] — Return (parent_link, child_link) for a G1 joint, following the menagerie URDF convention. (L272)
  • _g1_joint_specs() -> list[JointSpec] — Build the 29 JointSpecs from the joint-name tuples and the per-joint limit tables. (L322)
  • const G1_DESCRIPTION = RobotDescription(...) (L350) — Sim baseline; sdk_kind="open", hal.sim="openral_hal.g1:G1MujocoHAL", hal.real=None (sim-only); in-code mirror — build_hal passes the loaded robots/g1/robot.yaml as description=. Advertises supported_control_modes=[joint_position, body_twist], mobile_base in embodiment_tags, and a forward head RGB camera so BODY_TWIST nav skills (InternVLA-N1) match. All MuJoCo wiring lives in G1_DESCRIPTION.sim; drift-guarded against robots/g1/robot.yaml.

python/hal/src/openral_hal/_g1_walking.py

ADR-0089's private, sim-only walking implementation.

  • _download(relative_path, expected_sha256, destination, *, root=_RAW_ROOT, label=...) -> None (L44) — the pinned-commit + per-file SHA-256 fail-closed fetch (delegates to _pinned_files.fetch_pinned_file); root lets _g1_gr00t_wbc reuse it for another pinned repo.
  • ensure_g1_walking_assets() -> tuple[str, str] (L67) — downloads four files from pinned MuJoCo Playground commit 43d180a, verifies SHA-256, links the cached Menagerie meshes, flattens the included MJCF, and returns (mjcf_path, policy_path).
  • module const _PINNED_SHA: str (L18) — pinned MuJoCo Playground commit.
  • module const _RAW_ROOT: str (L19) — raw-GitHub root URL derived from _PINNED_SHA.
  • module const _ASSETS: dict[str, str] (L20) — the four pinned-asset relative paths mapped to their expected SHA-256 hex digests, verified by ensure_g1_walking_assets.
  • class G1WalkingController (L111) — 50 Hz CPU ONNX inference over 500 Hz MuJoCo physics; builds the upstream 103-D observation, validates the 29-D finite output, scales/clips joint targets, and persists gait phase/action history.
  • initialize(data: mujoco.MjData) -> None (L140) — Capture data.qpos[7:] as the standing default-angle reference, then reset_state().
  • reset_state() -> None (L144) — Zero the last-action history and gait phase, reset the decimation counter.
  • apply(model: mujoco.MjModel, data: mujoco.MjData, command: tuple[float, float, float]) -> None (L149) — Every _CONTROL_DECIMATION-th physics step, build the 103-D observation (base linear velocity, gyro, projected gravity, command, joint-angle delta, joint velocity, last action, phase sin/cos), run the ONNX policy, and scale/clip/apply the resulting joint targets.

python/hal/src/openral_hal/_g1_gr00t_wbc.py

Sim-only port of NVIDIA GR00T Decoupled WBC's MuJoCo runner (NVlabs/GR00T-WholeBodyControl @ 1e1ec4f5) — the G1 gr00t_wbc S0. Code Apache-2.0; weights NVIDIA Open Model License.

  • module const GR00T_WBC_PINNED_SHA (L55) — pinned upstream commit.
  • module const GR00T_WBC_LICENSE_POSTURE (L57) — the weights' RSkillLicensePosture.NVIDIA_OPEN_MODEL.
  • class Gr00tWbcAssets (L112) — frozen dataclass: verified walk_onnx, balance_onnx, license_text paths.
  • ensure_gr00t_wbc_assets() -> Gr00tWbcAssets (L120) — fetch / reuse the two ONNX files (Git LFS media URL) and the licence text into $OPENRAL_CACHE_DIR/g1_gr00t_wbc/<sha>/, each SHA-256-verified via _g1_walking._download; ROSConfigError on failure.
  • position_actuators_to_torque_motors(model) -> None (L155) — in-memory conversion of position actuators to unit-gain torque motors (actuatorfrcrange still clamps).
  • gr00t_wbc_observation(*, command, base_height, torso_rpy, base_quat_wxyz, base_ang_vel_body, joint_pos, joint_vel, last_action) -> NDArray[float32] (L172) — one 86-D frame in the upstream layout.
  • class Gr00tWbcController (L231) — loads Walk + Balance (signature-checked input[B,516] -> output[B,15]), keeps the 6-frame history and last action.
  • reset() -> None (L284) — zero history and last action.
  • policy_input(frame) -> NDArray[float32] (L291) — append a frame, return the [1, 516] input (oldest first).
  • step(data, *, command, base_height=0.74, torso_rpy=(0,0,0)) -> NDArray[float64] (L296) — one 50 Hz step: Balance when ‖command‖ ≤ 0.05 else Walk; returns 0.25·a + S0_DEFAULT_ANGLES; used_walk records the net.
  • module const S0_JOINT_COUNT (L77) — 15 policy-owned joints (12 legs + 3 waist).
  • module const S0_DEFAULT_ANGLES (L92) — stance the action offsets from.
  • module const S0_KP (L97) — leg/waist PD stiffness (upstream sim gains).
  • module const S0_KD (L100) — leg/waist PD damping.
  • module const ARM_KP (L105) — arm PD stiffness (GR00T real-robot MOTOR_KP).
  • module const ARM_KD (L106) — arm PD damping (MOTOR_KD).
  • module const CONTROL_RATE_HZ (L108) — 50 Hz policy rate.
  • module const DEFAULT_BASE_HEIGHT_M (L89) — 0.74 m height command.
  • module const WALK_COMMAND_THRESHOLD (L83) — 0.05 Balance/Walk switch.

python/hal/src/openral_hal/so100_mujoco.py

MuJoCo digital twin for the SO-100 follower arm (Menagerie MJCF).

  • class SO100MujocoHAL(MujocoArmHAL) — SO-100 follower MuJoCo HAL, driving mujoco_menagerie's trs_so_arm100/so_arm100.xml with the same 6-DoF action layout as SO100FollowerHAL. Maps lerobot-style joint names to the Menagerie joints and normalises the revolute Jaw range [-0.174, 1.75] to [0, 1]. (L65)
  • __init__(*, mjcf_path=None, settle_steps=None, gravity_enabled=True, staleness_limit_s=0.5) (L106)

python/hal/src/openral_hal/so100_sim.py

SO100DigitalTwin — in-process simulator for the SO-100 follower arm.

  • module const _JOINT_NAMES: list[str] (L37) — canonical joint order, mirrors lerobot's SO100Follower motor dict.
  • module const _DEFAULT_POSITIONS: dict[str, float] (L48) — default joint positions in lerobot's native units (degrees; gripper [0, 100], mid-range).
  • class SO100DigitalTwinConfig(RobotConfig) — Config for the digital twin. (L59) field: initial_positions
  • class SO100DigitalTwin(Robot) — In-process digital twin. (L76)
  • __init__(config) (L101)
  • observation_features() -> dict[str, type] — One float per joint pos. (L116)
  • action_features() -> dict[str, type] — One float per target. (L125)
  • is_connected -> bool [@property] (L134)
  • is_calibrated -> bool [@property] — Always True. (L139)
  • connect(calibrate=True) -> None — Activate (no serial port opened). (L146)
  • calibrate() -> None — No-op. (L154)
  • configure() -> None — No-op. (L158)
  • get_observation() -> RobotObservation — Lerobot-native units. (L162)
  • send_action(action) -> RobotAction — Apply position cmd, update state. (L175)
  • disconnect() -> None — Deactivate (idempotent). (L194)

python/hal/src/openral_hal/ros_control.py

RosControlHAL — ros2_control-backed HAL adapter, plus the typed downstream e-stop seam every ros2_control robot stops through (issue #295).

  • class ControllerKind(StrEnum) — Which ros2_control controller sits behind one command topic, and therefore which message type commands it: JOINT_TRAJECTORY (trajectory_msgs/JointTrajectory — every ros2_control robot in this repo, OpenArm's 1-DoF grippers included) and FORWARD_COMMAND (std_msgs/Float64MultiArray, the forward_command_controller family; no in-repo robot yet), JOINT_COMMAND_TRAJECTORY (isaac_ros_deploy_interfaces/JointCommandTrajectory, NVIDIA's ForwardJointCommandController — the Unitree upper body) and TWIST (geometry_msgs/Twist from the command dict's twist, NVIDIA InferenceController's velocity source). Declared rather than assumed because publishing the wrong type is silent — DDS never delivers it, so the arm does not move and nothing logs an error. Re-exported from openral_hal. (L80)
  • class ControllerSwitchReport — Frozen dataclass: acknowledged outcome of one controller_manager switch. ok is the service's verdict and the post-switch confirmation (every controller listed in the requested state); states is what list_controllers reported per name; detail names what did not move. (L131)
  • class TriggerReport — Frozen dataclass: success + message of one std_srvs/Trigger-shaped vendor call. (L148)
  • class DownstreamStopReport — Frozen dataclass: what a HAL knows about its last downstream stop — stopped (only when controller deactivation and the vendor stop were acknowledged; a local latch never counts), controllers, controller_states, vendor_stop (service/topic label or ""), detail. fields() flattens it for /diagnostics (downstream_stop=acknowledged|unacknowledged, …). Produced by RosControlHAL, AlohaHAL, SO100FollowerHAL (per-servo torque off) and GalaxeaA1HAL (sidecar processes); the fleet conformance test requires every hal.real adapter to report. Read by the lifecycle node, which logs FATAL on an unacknowledged stop. (L156)
  • fields() -> dict[str, str] — Flattens the report for /diagnostics and the log line: downstream_stop=acknowledged|unacknowledged, downstream_controllers, downstream_controller_states, downstream_vendor_stop, downstream_stop_detail. (L175)
  • class ControllerStopSeam(Protocol) — What a transport must expose for a ros2_control HAL to stop its controllers: deactivate_controllers(names, *, timeout_s), activate_controllers(names, *, timeout_s) (both → ControllerSwitchReport), call_trigger(service, *, timeout_s) -> TriggerReport, publish_empty(topic). Production: RosControlTransport; unit lane: SimTransport. (L189)
  • deactivate_controllers(names, *, timeout_s) -> ControllerSwitchReport — The stop: switch every named controller to inactive and confirm. (L202)
  • activate_controllers(names, *, timeout_s) -> ControllerSwitchReport — The RESETTABLE re-arm: switch to active and confirm. (L208)
  • call_trigger(service, *, timeout_s) -> TriggerReport — One declared std_srvs/Trigger vendor service. (L214)
  • publish_empty(topic) -> None — One std_msgs/Empty on a declared vendor-stop topic. (L218)
  • class ControllerSwapSeam(Protocol) — runtime-checkable: a stop seam that can swap_controllers(*, deactivate, activate, timeout_s) -> ControllerSwitchReport in ONE switch_controller request. Needed by a robot whose hardware releases unclaimed joints (Unitree hg: motor mode 0 = zero torque), where plain deactivation would drop a standing humanoid. Implemented by RosControlTransport and SimTransport; UnitreeHgRealHAL.attach_controller_stop refuses a seam without it. (L224)
  • swap_controllers(*, deactivate, activate, timeout_s) -> ControllerSwitchReport — Hand-over in one STRICT switch, confirmed by listing; states carries the listing even when refused (a BEST_EFFORT swap drops an activation that cannot happen yet applies the deactivations — the joints released; review of #571). (L246)
  • activate_controllers(names, *, timeout_s) -> ControllerSwitchReport — The retry after a swap whose activation failed inside the switch (#566): controller_manager keeps the deactivations under either strictness and has no rollback (4.48.1). (L260)
  • controller_states(*, timeout_s) -> dict[str, str] — The pre-check's listing (#566). (L266)
  • configure_controller(name, *, timeout_s) -> bool — The pre-check's configure of an unconfigured holding controller (#566). (L270)
  • class ControllerStoppable(Protocol) — The stop-side counterpart of RosControlDrivable: controller_names(), vendor_stop_services(), vendor_stop_topics(), attach_controller_stop(seam). The lifecycle node refuses to configure a RosControlDrivable real HAL that is not also this; RosControlHAL answers all four. Pinned per manifest by tests/unit/test_real_hal_estop_fleet_conformance.py. (L276)
  • controller_names() -> list[str] — Every controller_manager controller estop must deactivate. (L288)
  • vendor_stop_services() -> list[str] — std_srvs/Trigger services the vendor stop calls. (L292)
  • vendor_stop_topics() -> list[str] — std_msgs/Empty topics the vendor stop publishes on. (L296)
  • attach_controller_stop(seam) -> None — Bind the ControllerStopSeam at wire-up. (L300)
  • class DownstreamStopReporting(Protocol) — last_stop_report -> DownstreamStopReport | None property; what the lifecycle heartbeat and FATAL log read. (L306)
  • (property) last_stop_report -> DownstreamStopReport | None (L310)
  • class RosControlHAL — ros2_control-backed HAL adapter. Implements LifecycleEStopHAL with estop_recovery = RESTART_REQUIRED by default (the conservative policy; OpenArm opts into RESETTABLE). (L337)
  • __init__(description, controller_name, *, joint_state_topic='/joint_states', command_topic=None, publish_fn=None, state_fn=None, staleness_limit_s=None, stop_timeout_s=5.0) (L400) — staleness_limit_s=None reads description.safety.joint_state_staleness_limit_s via resolve_staleness_limit_s (no constructor default; refused when undeclared). Reads the control rate from description.action_spec.control_freq_hz (the field the runner ticks at and the recorder stamps as fps; every committed ros2_control manifest declares 30 Hz); refuses to construct with ROSConfigError naming the field when it is missing or not positive, so build_hal(mode="real") and the lifecycle node's configure stop there (issue #303).
  • attach_transport(publish_fn, state_fn, stamp_fn=None) -> None — Bind a live transport after construction; build_hal runs before any ROS node exists, so a real deployment cannot pass one to __init__. stamp_fn is the transport's per-message arrival clock and is what makes the staleness check a freshness check rather than a time-since-connect check. Rejects a non-callable stamp_fn at wire-up. (L457)
  • attach_controller_stop(seam) -> None — Bind the ControllerStopSeam (same rationale as attach_transport); rejects a non-seam at wire-up with ROSConfigError. (L496)
  • controller_names() -> list[str] — Every controller_manager controller estop deactivates; [controller_name] by default, overridden by the bimanual OpenArm alongside command_bindings. (L519)
  • vendor_stop_services() -> list[str] — std_srvs/Trigger services and std_msgs/Empty topics the vendor stop uses; declared up front so the transport creates the clients/publishers at wire-up and refuses an undeclared name loudly. Empty in the base. (L528)
  • vendor_stop_topics() -> list[str] — std_msgs/Empty topics the vendor stop publishes on, declared for the same reason. Empty in the base; Sawyer overrides. (L537)
  • (property) last_stop_report -> DownstreamStopReport | None (L542)
  • command_bindings() -> dict[str, ControllerKind] — Every controller topic this HAL publishes to, each with the wire format its controller speaks; one entry becomes one typed transport publisher. Insertion order is the send_action fan-out order. This is the override point for a new robot — overridden by the bimanual OpenArm (4 topics, all JOINT_TRAJECTORY). (L546)
  • command_topics() -> list[str] — Derived from command_bindings() so the topic list and the declared formats cannot drift; override command_bindings, not this. (L560)
  • ros2_control_joint_names() -> list[str] — Joint names in ros2_control's namespace, action order; what /joint_states is keyed by. Overridden where URDF names differ from manifest names (OpenArm). (L568)
  • (property) joint_state_topic -> str — The aggregated sensor_msgs/JointState topic this HAL reads. (L578)
  • (property) controller_name -> str — Name of the primary ros2_control controller this HAL commands (the one command_topic defaults from). Hoisted here from the Franka / Sawyer wrappers so every subclass answers it. (L583)
  • connect() -> None (L589)
  • disconnect() -> None — inherited from HALBase (flag-and-log default; no extra teardown needed).
  • read_state() -> JointState — Age is measured from stamp_fn() when a transport supplied one, else from connect(). (L609)
  • send_action(action) -> None — Publish JointTrajectory; carries joint_names so no transport keeps a second copy of the mapping, and time_from_start_s from time_from_start_s(action). (L664)
  • time_from_start_s(action) -> float — Trajectory deadline horizon / action_spec.control_freq_hz: a chunk is reached just as its replacement is due; the transport spreads the chunk's rows evenly up to it. Issue #303: at 30 Hz that default re-planned a steep segment every 33 ms and amplified each step between targets. (L698)
  • estop() -> None — Idempotent once acknowledged: before reset_estop, a second call (a ComposedHAL stopping every part after one stopped itself, or the lifecycle latch after the HAL's own stop) re-raises with the stored report rather than re-deactivating inactive controllers, which a STRICT switch refuses; an unacknowledged stop is retried, and so is one after a re-arm that failed (reset_estop raised, so it may have activated controllers): the failed re-arm's listing narrows the retry to controllers not listed inactive, so a STRICT switch is not asked to deactivate inactive ones. Otherwise: Drop the connection flag first (nothing more leaves this HAL), then _stop_downstream(), then raise ROSEStopRequested whose message says whether the downstream stop was acknowledged. The outcome lives in last_stop_report, not the exception type, so the HAL Protocol's "always ROSEStopRequested" holds. With no seam attached the report is stopped=False / "no controller stop seam attached" — never a claimed stop. (L721)
  • _stop_downstream() -> DownstreamStopReport [private] — Deactivates controller_names() through the seam (STRICT switch + listing confirmation), then runs _vendor_stop; both are attempted even if the first fails, so the report names everything that did and did not acknowledge. (L780)
  • _stop_switch(seam, names) -> ControllerSwitchReport [hook] — The switch estop performs; plain deactivate_controllers by default, overridden by UnitreeHgRealHAL to swap in freeze_controller. Exceptions it raises are folded into the report by _stop_downstream. (L850)
  • _vendor_stop(seam) -> str [hook] — Vendor-specific stop beyond controller deactivation; returns its label for the report or raises a ROSError. Base: none (for a plain ros2_control robot deactivation is the stop; for franka_hardware it is what calls libfranka's stopRobot()). Overridden by UR (dashboard stop Trigger) and Sawyer (super-stop Empty). (L863)
  • _vendor_reset(seam) -> None [hook] — Vendor re-arm before controllers are re-activated; no-op by default. (L875)
  • reset_estop() -> None — Only for RESETTABLE adapters: _vendor_reset, then activate_controllers through the seam, and only once the manager confirms every controller active is the HAL marked connected again. Raises ROSRuntimeError for a RESTART_REQUIRED policy ("in-process reset is forbidden"), a missing seam, or an unacknowledged re-activation — so the lifecycle latch can never clear ahead of the vendor reset. (L879)
  • private: _require_connected, _validate_action

  • class GroupedRosControlHAL(RosControlHAL) — RosControlHAL whose joints split across several JointTrajectoryControllers (bimanual arms). Subclasses declare only groups — (controller_name, n_joints) in action order, summing to the joint count (else ROSConfigError) — and their own preflight. ros2_control names come from each joint's sim_joint_name, else its name. Base of OpenArmRealHAL; robots/rizon_dual uses it directly (hal.real: openral_hal.ros_control:GroupedRosControlHAL, groups from hal.parameters.defaults), so a ros2_control robot whose controllers split only by joint range needs no Python class. Rejects zero-width or duplicate groups. Opt-in frozen_state_limit_s: a group whose positions and velocities stay bit-identical longer than that makes read_state raise ROSPerceptionStale (an interface that stops updating a faulted or E-stopped arm yet returns OK keeps its last values flowing with fresh stamps); rizon_dual sets 0.5 s, and connect / reset_estop restart it. read_state takes one sample per call and raises when it carries no joint names (matching is by name, never by position) or no position for every name. An ungrouped action whose joint_names leave any joint unnamed (a one-arm row padded to full width, tick_group_size 1) is refused before anything is published: its padding would drive the unnamed arm, and skipping that controller would leave it on an older trajectory. A partial command must arrive as a slot group. A publish failing after an earlier controller took its target logs the cause and stops every controller (estop); the tick is not committed. (L933)

  • __init__(description, *, groups, joint_state_topic='/joint_states', publish_fn=None, state_fn=None, staleness_limit_s=None) (L983)
  • ros2_control_joint_names() -> list[str] — URDF names in action-vector order. (L1035)
  • command_bindings() -> dict[str, ControllerKind] — One /<controller>/joint_trajectory per group, all JOINT_TRAJECTORY, in fan-out order. (L1039)
  • controller_names() -> list[str] — Every group's controller; estop deactivates them all. (L1043)
  • read_state() -> JointState — Matches /joint_states by ros2_control name into manifest order; raises naming the missing joints rather than zero-filling; an absent/wrong-length effort channel yields effort=[], never zeros. (L1047)
  • send_action(action) -> None — All-or-nothing fan-out: every group's message (own slice, own joint_names, shared time_from_start_s) is built before any is published. ADR-0102 slot groups are staged (SlotGroupStager) and composed by compose_slot_group_action first; an ungrouped ticked action is checked against the same watermark (admit / commit_tick). A standalone gripper action raises ROSConfigError (nowhere to route it). (L1152)
  • connect() -> None — The base connect; the frozen-group check restarts from the next sample. (L1252)
  • disconnect() -> None — Also resets the stager and its watermark. (L1257)
  • reset_estop() -> None — The base re-arm, then the frozen-group check restarts. (L1262)
  • (property) last_applied_action -> Action | None — The command last published (the composed action for a slot group); fed to the grasp trigger. (L1268)
  • (property) last_committed_tick -> int — Tick of the last slot group published (0 = none since disconnect). (L1278)
  • (property) last_committed_session -> int — runner_session_id of last_committed_tick. (L1283)
  • discard_staged_slots() -> int — SlotGroupStager.discard (watermark kept); called on every /openral/estop latch and /openral/estop_cleared. (L1287)
  • estop() -> None — Discards the half-staged tick (watermark kept), then the base stop: every controller deactivated and confirmed. (L1298)

python/hal/src/openral_hal/ros_control_transport.py

Production rclpy transport shared by every real RosControlHAL robot.

  • class RosControlDrivable(Protocol) — runtime-checkable, structural: what a HAL must expose to be driven by RosControlTransport (command_bindings, ros2_control_joint_names, joint_state_topic, attach_transport). The lifecycle node's wiring gates on this, not on isinstance(hal, RosControlHAL), so a ros2_control robot that reimplements the fan-out on HALBase rather than inheriting can opt in by shape instead of being silently skipped. Non-method member (joint_state_topic is a property) so isinstance works but issubclass raises — gate with isinstance. (L91)
  • command_bindings() -> dict[str, ControllerKind] (L104) — see RosControlHAL.command_bindings.
  • ros2_control_joint_names() -> list[str] (L108) — see RosControlHAL.ros2_control_joint_names.
  • (property) joint_state_topic -> str (L113)
  • attach_transport(publish_fn, state_fn, stamp_fn=None) -> None (L117) — see RosControlHAL.attach_transport.
  • class RosControlTransport — Bridges one RosControlHAL to live ros2_control topics and implements ControllerStopSeam over controller_manager. Built only from what the HAL reports about itself (command_bindings(), ros2_control_joint_names(), joint_state_topic), so a one-controller UR and the four-controller bimanual OpenArm are one code path and a new robot needs no transport code. Wired automatically by the lifecycle node under hal_mode:=real. Reuse watch: the canonical real-HW ros2_control bridge — do not hand-roll publishers in a per-robot HAL. (L139)
  • __init__(node, *, command_topics, joint_names, joint_state_topic='/joint_states', command_kinds=None) — Refuses an empty topic or joint list, and a command_kinds entry naming a topic not in command_topics (a typo there would silently leave the real topic on the JOINT_TRAJECTORY default). Topics absent from command_kinds default to JOINT_TRAJECTORY. (L168)
  • publish(topic, msg) -> None — One command dict → the message type this topic's declared ControllerKind calls for. Publishes the chunk's final step only (a point is an absolute target the controller interpolates toward). Raises on a topic the HAL never declared, and on a payload it cannot express (no joint_targets key — e.g. a {"position": …} gripper command): dropping that quietly would be a silent no-op on the actuation path. An empty joint_targets list is the distinct, benign "nothing to send this tick". (L309)
  • state() -> dict[str, object] — Newest joint state projected onto the HAL's joint order; merged by name, never index, since split controllers publish independently. An unheard joint's position/velocity read 0.0; effort is [] unless every joint carried an effort value. (L432)
  • last_arrival() -> float — time.monotonic() of the newest message; 0.0 before the first. Feeds RosControlHAL.attach_transport(stamp_fn=...). (L457)
  • deactivate_controllers(names, *, timeout_s) -> ControllerSwitchReport — The stop. controller_manager/switch_controller with deactivate_controllers=names, strictness=STRICT, then list_controllers to confirm every name reads inactive; ok is both. Discovery, the switch and its confirmation share one timeout_s deadline, so a stalled manager cannot stretch the stop past the budget. A deactivated JointTrajectoryController holds its last position command (zeroes velocity / effort), drops late trajectories (its subscriber goes inactive) and writes nothing until re-activated — verified against ros2_controllers jazzy, which is also why an empty trajectory is not used as a stop: ROS 2 rejects it ("Empty trajectory received"). (L463)
  • activate_controllers(names, *, timeout_s) -> ControllerSwitchReport — Mirror for a RESETTABLE re-arm; confirms active. (L476)
  • swap_controllers(*, deactivate, activate, timeout_s) -> ControllerSwitchReport — ControllerSwapSeam: one switch_controller request with both lists, STRICT — a controller that cannot make its transition (an activate one not inactive, a deactivate one not active) refuses the whole request, where BEST_EFFORT dropped the activation and still deactivated (verified on 4.48.1: ok=True, chain inactive, holding controller unconfigured); ok only when the listing shows every deactivate name inactive and every activate name active. (L482)
  • call_trigger(service, *, timeout_s) -> TriggerReport — One declared std_srvs/Trigger (UR /dashboard_client/stop); ROSConfigError for an undeclared service, success=False when absent or unanswered; discovery and the call share one timeout_s deadline. (L508)
  • publish_empty(topic) -> None — One std_msgs/Empty on a declared vendor-stop topic (Sawyer /robot/set_super_stop); ROSConfigError for an undeclared one. (L540)
  • configure_controller(name, *, timeout_s) -> bool — controller_manager/configure_controller (client created at wire-up); True when the manager says ok. ControllerSwapSeam's pre-check: the STRICT swap is refused whole while its holding controller is unconfigured. (L557)
  • controller_states(*, timeout_s) -> dict[str, str] — {name: state} from list_controllers; {} if the manager did not answer; discovery and the call share one timeout_s deadline. The lifecycle node logs a warning at wire-up when the HAL's controllers are not yet listed active. (L576)
  • close() -> None — Destroy the helper node the service clients live on (lifecycle cleanup). (L589)
  • __init__ also takes controller_names, trigger_services, empty_topics (from hal.controller_names() / vendor_stop_services() / vendor_stop_topics()) and controller_manager='/controller_manager'. Service calls run on a private helper node + executor because the e-stop callback runs on the lifecycle node's single-threaded executor and a future issued from inside a callback can only complete if something else spins the client.
  • seen_joints() -> set[str] (L762)
  • missing_joints() -> list[str] (L766)
  • private: _time_from_start_s(msg, topic) — the chunk deadline the HAL supplied; no fallback — a command without a positive time_from_start_s raises ROSConfigError (a fixed 100 ms constant in its place is the defect of issue #303). publish turns every chunk row into a JointTrajectoryPoint, evenly spaced up to that deadline, so the controller interpolates through the chunk's shape (a single-row tick is one point at one control period). _on_joint_state
  • module const _COMMAND_DEPTH = 1 (L131) — command QoS depth (RELIABLE, VOLATILE, shallow — CLAUDE.md §2).
  • module const _STATE_DEPTH = 10 (L136) — state QoS depth.
  • module const _TWIST_DIM = 6 (L87) — components of a TWIST command.
  • module const _STRICT = 2 (L84) — controller_manager_msgs/SwitchController.STRICT: a switch that cannot fully apply is refused rather than partially applied — every switch this transport sends, the swap included.
  • _left(deadline) -> float — Seconds left before a time.monotonic() deadline, floored at zero; every stop-seam phase (wait_for_service, the call, the confirmation) is budgeted through it. (L812)
  • _message_type(kind) -> type — The one place a ControllerKind becomes a ROS message class. Adding an enum member without extending this raises at wire-up rather than publishing a plausible-but-wrong type onto the actuation path; tests/unit/test_ros_control_transport.py::test_every_controller_kind_maps_to_a_message_type pins that. (L817)

python/hal/src/openral_hal/unitree_real.py

Real-hardware adapter for the Unitree hg humanoids (G1, H2). NVIDIA owns S0: a whole-body ONNX policy runs as isaac_ros_deploy's C++ InferenceController on isaac_ros_robots' unitree_hg_ros2_control; this HAL commands the upper body and a base velocity only. Bringup: packages/openral_hal_unitree.

  • const G1_REAL_DESCRIPTION (L121) — make_real_description(G1_DESCRIPTION, sdk_kind="closed_with_api") (unitree_sdk2's prebuilt core). Mirrored by robots/g1/robot.yaml.
  • const H2_REAL_DESCRIPTION (L123) — make_real_description(H2_DESCRIPTION, sdk_kind="closed_with_api"). Mirrored by robots/h2/robot.yaml.
  • class UnitreeHgRealHAL(RosControlHAL) (L166) — estop_recovery = RESTART_REQUIRED. Joint split from the selected S0 policy file (unitree_s0_policy): a JOINT_POSITION action owning an S0 joint (named, or implied by joint_names=None) raises ROSCapabilityMismatch before anything is published. Every upper-body message carries every upper-body joint (unowned ones at their held target / measured pose — NVIDIA's forward controller snaps an omitted joint to its activation pose). Every tick re-publishes a twist heartbeat (zero unless a same-tick BODY_TWIST slot set one) so the policy's topic_input_timeout_ms only trips when OpenRAL is gone. No base-height command (no Action field; upstream hardcodes 0.7 m).
  • __init__(description=None, *, robot_model='g1', s0_policy=None, upper_body_controller=..., inference_controller=..., safety_controller=..., freeze_controller=..., joint_state_topic='/joint_states', publish_fn=None, state_fn=None, staleness_limit_s=None, stop_timeout_s=5.0) — s0_policy=None → the model default (G1 gr00t_decoupled_wbc, H2 agile_velocity); refuses an unknown model, a missing/placeholder policy, or a split that is not a disjoint cover of the manifest. (L205)
  • upper_body_joints() -> list[str] — Joints this HAL commands, in message order. (L279)
  • s0_joints() -> list[str] — Joints the policy owns (manifest order). (L289)
  • command_bindings() -> dict[str, ControllerKind] — /upper_body_forward_joint_command_controller/joint_commands_trajectory (JOINT_COMMAND_TRAJECTORY) + the policy's velocity topic (TWIST). (L299)
  • controller_names() -> list[str] — safety_controller, inference_controller, upper_body_forward_joint_command_controller — what estop swaps out. (L312)
  • (property) s0_policy -> str (L327)
  • (property) freeze_controller -> str (L332)
  • attach_controller_stop(seam) -> None — Refuses a seam that is not a ControllerSwapSeam (ROSConfigError). (L338)
  • estop() -> None — Swaps the S0 chain for freeze_controller in one request (_stop_switch), then raises ROSEStopRequested. (L445)
  • _stop_switch(seam, names) [hook] — #566 + review of #571: freeze_controller cannot be activated before the chain lets go (same command interfaces; the manager refuses it), so the hand-over is one STRICT swap (refused whole, chain kept, when freeze cannot be activated — never the deactivations alone). All steps share one stop_timeout_s deadline. Pre-check (advisory: listing bounded by _PRECHECK_TIMEOUT_S = 0.2; an unconfigured freeze is configured first, CRITICAL hal.estop.freeze_configured; a fault in it is noted, CRITICAL hal.estop.precheck_failed, and the swap is sent anyway); partial chain (a refused swap whose listing shows part of the chain already out → swap the members still active); retry (chain out but freeze not active — on_activate failed inside the switch → activate it alone, CRITICAL hal.estop.freeze_retry). ok is the listing's verdict (freeze active, chain inactive), so a repeat e-stop is acknowledged. Live-pinned by test_estop_configures_an_unconfigured_freeze_controller_before_the_swap, test_estop_never_releases_the_chain_when_freeze_cannot_be_configured, test_estop_returns_within_stop_timeout_when_the_manager_stalls, test_a_dead_listing_client_does_not_keep_the_swap_from_the_manager.
  • send_action(action) -> None — JOINT_POSITION → upper-body JointCommandTrajectory + heartbeat twist; BODY_TWIST → row 0 on the velocity topic (planar and finite, else ROSConfigError). (L457)
  • disconnect() -> None (L439)
  • health() -> HALHealthReport (L588)
  • private: _validate_action, _twist_of, _heartbeat_twist, _upper_body_message, _held_or_measured
  • @dataclass _UnitreeHgModel / _MODELS — Per-model defaults (description, default S0 policy): g1, h2. (L144)

python/hal/src/openral_hal/unitree_s0_policy.py

One typed reader of packages/openral_hal_unitree/config/<model>/policies/<policy>.yaml for both UnitreeHgRealHAL (joint split) and real_bringup.launch.py (controller parameters), so the split the HAL enforces is the one the C++ graph runs.

  • class S0PolicyMeta(BaseModel) — name, status (ready/placeholder), data_package | bundle_dir, leapp_config, optional hf_repo / hf_revision / sha256 ({bundle file: SHA-256} pins of a Hub-downloaded bundle_dir), velocity_command_topic, velocity_command_type, s0_joints. extra="forbid". (L62)
  • class S0PolicyFile(BaseModel) — openral_policy + controllers (ROS param blocks). (L96)
  • (property) upper_body_joints -> list[str] — The upper-body controller's joints; ROSConfigError when absent. (L110)
  • module const UNITREE_BRINGUP_PACKAGE = "openral_hal_unitree" (L49)
  • module const UPPER_BODY_CONTROLLER = "upper_body_forward_joint_command_controller" (L51)
  • module const INFERENCE_CONTROLLER = "inference_controller" (L53)
  • module const GUARDED_INFERENCE_CONTROLLER = "openral_hal_unitree/GuardedInferenceController" — the only inference_controller type that enforces WATCHDOG_KEYS on the pinned (v4.6) isaac_ros_deploy (#565). (L55)
  • module const WATCHDOG_KEYS = ("topic_input_timeout_ms", "topic_input_sources") — isaac_ros_deploy v5.0's stale-input watchdog keys. (L57)
  • require_watchdog_enforced(policy, base_params) -> None — ROSConfigError unless the policy sets a positive float topic_input_timeout_ms and every type either document gives inference_controller (manager block, the controller's own block, namespaced / /** keys; at least one) is GUARDED_INFERENCE_CONTROLLER: any other type ignores the timeout on v4.6. Called by real_bringup.launch.py. (L285)
  • s0_policy_path(robot_model, policy) -> Path — $OPENRAL_UNITREE_CONFIG_DIR, then the installed openral_hal_unitree share, then the repo checkout. (L122)
  • load_s0_policy(path, *, require_ready=True) -> S0PolicyFile — ROSConfigError on a missing/malformed/placeholder file. (L159)
  • resolve_leapp_config(policy, override, package_share=None) -> Path — override › share/<data_package>/data/ › bundle_dir; a bundle_dir bundle is checked against every sha256 pin (ROSConfigError on a missing file or mismatch). A missing bundle names its hf download … --revision … command (hf_repo set) or tools/build_gr00t_wbc_leapp.py. (L183)
  • policy_parameters(policy, leapp_config) -> dict — A copy of controllers with inference_controller.config_path filled. (L322)

python/hal/src/openral_hal/interbotix_transport.py

Production rclpy torque-stop seam for the Interbotix XS arms (ALOHA) — the stop only, not the command path (#250).

  • class InterbotixXSTransport — Implements openral_hal.aloha.InterbotixStopSeam over real interbotix_xs_msgs/srv/TorqueEnable clients, one per arm_namespaces entry, created at wire-up on a private helper node (same callback-deadlock rationale as RosControlTransport). Raises ROSConfigError at construction when interbotix_xs_msgs is not installed, so the ALOHA e-stop fails at configure, not on the first stop. Attached by the lifecycle node under hal_mode:=real to any InterbotixStoppable HAL. (L38)
  • torque_enable(robot_name, *, group, enable, timeout_s) -> TriggerReport — /<robot_name>/torque_enable with cmd_type='group'; TorqueEnable has an empty response, so the acknowledgement is the call completing — absent or unanswered → success=False. ROSConfigError for an undeclared arm. (L88)
  • close() -> None — Destroy the helper node. (L131)

python/hal/src/openral_hal/sim_transport.py

SimTransport — in-memory simulated ros2_control transport and ControllerStopSeam; SimTorqueSeam — in-memory InterbotixStopSeam. The in-repo controller simulators the unit lane proves the e-stop path on.

  • class SimTransport — In-memory transport simulating JointTrajectory controllers behind a controller_manager table. Mirrors the two verified facts about a deactivated JointTrajectoryController: a command on an inactive controller's topic is dropped (recorded in dropped_calls, not applied) and nothing moves until re-activated. (L59)
  • __init__(n_joints, *, controllers=None, trigger_responses=None, switch_faults=None, joint_names=None, initial_states=None, activation_faults=None) — initial_states overrides a controller's starting active (e.g. unconfigured); activation_faults maps a controller to how many activations fail (on_activate errors) before one succeeds. joint_names given → a command carrying its own joint_names (a subset HAL such as the Unitree upper body) is applied by name; switch_faults also takes "swap", "list" (controller_states) and "configure". controllers given → STRICT table (an unknown name refuses a switch like an unloaded controller); omitted → names register active on first use. trigger_responses maps a service to the (success, message) its call_trigger returns (simulate a refusing UR dashboard); switch_faults maps "deactivate" / "activate" to the exception that switch raises instead of answering (the rclpy-shaped fault the HAL must contain in its report). (L114)
  • publish(topic, msg) -> None — Record msg, apply joint_targets — unless the topic's controller is inactive. (L151)
  • state() -> dict[str, object] — Current simulated joint state; carries name when built with joint_names (as RosControlTransport always does), which GroupedRosControlHAL.read_state requires. (L188)
  • deactivate_controllers(names, *, timeout_s) -> ControllerSwitchReport — Flip the table to inactive; refuse unknown names under STRICT; raise the switch_faults["deactivate"] exception when configured. (L208)
  • activate_controllers(names, *, timeout_s) -> ControllerSwitchReport — Mirror for the re-arm; switch_faults["activate"] likewise. (L214)
  • swap_controllers(*, deactivate, activate, timeout_s) -> ControllerSwitchReport — One hand-over with the STRICT semantics RosControlTransport requests, recorded as a single ("swap", deactivate + activate) entry in switch_calls: an unloaded name, a deactivate controller not active or an activate one not inactive refuses the whole swap; past that, one in activation_faults fails and the deactivations still happen (no rollback, #566). (L220)
  • controller_states(*, timeout_s) -> dict[str, str] — The controller table; raises switch_faults["list"] when configured. (L269)
  • configure_controller(name, *, timeout_s) -> bool — unconfigured → inactive; False for an unloaded controller; raises switch_faults["configure"] when configured. (L275)
  • call_trigger(service, *, timeout_s) -> TriggerReport — Recorded; answered from trigger_responses (default: success). (L289)
  • publish_empty(topic) -> None — Recorded in empty_publishes. (L295)
  • controller_state(name) -> str — active / inactive / unloaded. (L299)
  • call_count -> int [@property] — Number of commands delivered to an active controller. (L306)
  • last_call -> tuple | None [@property] — The most recent delivered (topic, msg). (L311)
  • calls -> list[tuple] [@property] — Every delivered (topic, msg), in order. (L316)
  • dropped_calls -> list[tuple] [@property] — Every command that reached an inactive controller and was dropped. (L321)
  • switch_calls -> list[tuple] [@property] — Every ("deactivate" | "activate", names) switch, in order. (L326)
  • trigger_calls -> list[str] [@property] — Every std_srvs/Trigger service called, in order. (L331)
  • empty_publishes -> list[str] [@property] — Every std_msgs/Empty topic published on, in order. (L336)
  • class SimTorqueSeam — In-memory InterbotixStopSeam: a simulated xs_sdk torque table. torque_enable(robot_name, *, group, enable, timeout_s) -> TriggerReport flips the arm's torque, refuses an arm not in arms (absent service) or listed in failing, and raises the exception faults maps an arm to (the rclpy-shaped fault the HAL must contain while still stopping the other arms); torque(name) / calls for assertions. (L397)
  • torque_enable(robot_name, *, group, enable, timeout_s) -> TriggerReport — Record the call and flip the arm's torque unless it is absent, listed in failing, or mapped in faults (then raise that exception). (L437)
  • torque(robot_name) -> bool — Whether the arm is currently torqued on. (L453)
  • calls -> list[tuple[str, str, bool]] [@property] — Every (robot_name, group, enable) call, in order. (L458)

python/hal/src/openral_hal/lifecycle.py

Generic ROS 2 managed lifecycle node wrapper for every HAL adapter — UR5e / UR10e / Franka / SO-100 / OpenArm / H1 / future HALs all share the same publish / subscribe / heartbeat / OTel-span wiring.

  • class HALLifecycleNodeBase(LifecycleNode) — Public base class. Owns the standard /joint_states publishers, the /openral/safe_action + /openral/estop subscribers, the 1 Hz DiagnosticsHeartbeat, the per-tick hal.read_state/hal.send_action OTel spans, the estop latch, the publish_rate_hz param (0, the default, = the manifest's control_rate_hz so proprio is published once per runner tick; a manifest with no action_spec.control_freq_hz warns and uses 30 Hz — issue #303), and the full configure → activate → deactivate → cleanup → shutdown transition wiring. on_configure hands this node to a HAL exposing attach_ros_node(node) between building and connect (a ComposedHAL's ROS base part). The /openral/action_applied ack is monotonic per runner session, with the same renumbering the HAL adopts: a new non-zero runner_session_id renumbers it, and for a session-less runner (0) tick 1 after a higher acked tick resets it (_publish_action_applied_if_complete), so a restarted runner is not left waiting on tick 1. Every parameter it (or a subclass) declares is read-only (its declare_parameters override sets ParameterDescriptor.read_only): the values come from the launch params file or the keyword-only parameter_overrides constructor argument, and a later set_parameters (in-process or a DDS peer's ~/set_parameters) is refused, so no peer can change the robot_yaml / scene_composition_json / hal_mode / transport address the next on_configure re-reads. (L746)
  • _create_hal(self) -> HAL — Subclass hook (required): construct and return a HAL instance, reading ROS-parameter-driven constructor args via self.get_parameter(...). (L917)
  • _heartbeat_extra_fields(self) -> dict[str, str] — Subclass hook (optional): extra key/values for the /diagnostics payload. Default {}. (L929)
  • on_configure_post_hal(self) -> TransitionCallbackReturn — Subclass hook (optional): robot-specific setup after the HAL connects. Default SUCCESS. (L986)
  • on_activate_post_subs(self) -> TransitionCallbackReturn — Subclass hook (optional): robot-specific timers/publishers after the base wires its subs. Default SUCCESS. (L1104)
  • on_deactivate_pre_teardown(self) -> None — Subclass hook (optional): stop robot-specific timers before base teardown. Default no-op. (L1112)
  • on_cleanup_pre_disconnect(self) -> None — Subclass hook (optional): tear down robot-specific resources before HAL.disconnect(). Default no-op. (L1119)
  • on_signal_shutdown_pre_disconnect(self) -> None — Subclass hook (optional) shutdown_hal runs before HAL.disconnect() on a signal-driven exit, where no lifecycle transition (so no on_cleanup_pre_disconnect) runs: release what must not outlive the interpreter, without rclpy calls. The manifest node closes its sensor bridge's MuJoCo viewer here; left open, its GL thread aborted the process when GLFW's atexit terminate ran (#742). Default no-op. (L1126)
  • shutdown_hal(self) -> None — Disconnects the HAL on a signal-driven process teardown, since rclpy's SIGINT handler raises out of spin without requesting the lifecycle shutdown transition, so on_shutdown/on_cleanup (and HAL.disconnect) would otherwise never run. Called from both main() factories' finally, before destroy_node; exactly-once and idempotent. Deliberately HAL-only — no publisher/timer teardown, since the rclpy context is already down — except on_signal_shutdown_pre_disconnect, which runs first. SIGKILL stays uncatchable. (L1444)
  • _publish_joint_state(self) -> None — Timer callback: reads self._hal.read_state() under a hal.read_state span and publishes /joint_states; when the HAL exposes read_policy_state, also publishes /openral/policy_state once per new ProprioFrame (never a latched republish) via _publish_policy_state, which creates that publisher only on the first frame carrying a policy state — a backend that produces none never advertises the topic, so the reasoner palette drops use_world_state_policy_state skills there (issue #474). Subclasses may override + call super() to extend (OpenArm does, for viewer-sync). (L1615)
  • _on_safe_action(self, msg) -> None — /openral/safe_action callback. Decodes the openral_msgs/ActionChunk into an openral_core.Action and forwards via _send_action_traced(action, source="safe_action"). (L1871)
  • _send_action_traced(self, action, *, source) -> bool — False when no HAL is bound or send_action raised (logged on the span), else True; Forwards action to self._hal.send_action inside a hal.send_action span; source disambiguates the origin on the dashboard's Commands card. (L2100)
  • _on_estop(self, msg) -> None — /openral/estop callback. Ordered latch → stop → report: sets _estopped (so _on_safe_action drops commands), calls _invoke_hal_estop, then in a finally drops any half-staged slot group (_discard_staged_slots) and reports via _emit_estop_telemetry, so an e-stop is counted even if the vendor stop path raises. Nothing is added ahead of the physical stop.
  • _on_send_failure(self, exc, source) -> None — Every exception out of send_action in _send_action_traced routes here. ROSEStopRequested (a GroupedRosControlHAL or ComposedHAL fan-out that reached some controllers but not all, which already stopped them) is latched through the node's full _on_estop, so the whole HAL's estop runs too (a composed robot's other parts stop; an already-stopped ros2_control part keeps its acknowledged report, RosControlHAL.estop being idempotent), then /openral/estop goes out on _estop_pub, best effort, so the heartbeat reads estop latched and the graph stops with it. Anything else skips the tick with a warning.
  • _discard_staged_slots(self, boundary) -> None — Calls the HAL's discard_staged_slots() when it has one, for every HAL (latch-only ones included — the MuJoCo twin never receives estop()), on the /openral/estop latch and on every /openral/estop_cleared (before the latch check); logs openral_hal.slot_group_discarded when slots were dropped, and once openral_hal.slot_group_discard_skipped for a HAL without the method (it stages no groups). Without it a tick a kernel stop cut short survived openral estop reset into the next goal (Thor twin pass, 2026-10-03).
  • _invoke_hal_estop(self) -> None — Calls self._hal.estop() for HALs implementing LifecycleEStopHAL; on the expected ROSEStopRequested it reads _downstream_stop_fields() and logs ERROR "hardware estop completed" only when the HAL's DownstreamStopReport says acknowledged, else FATAL "hardware estop NOT acknowledged downstream — only the local latch holds"; any other exception is logged at fatal — the latch must survive a vendor stop-path failure.
  • _downstream_stop_fields(self) -> dict[str, str] — Flattens the HAL's last_stop_report (DownstreamStopReporting) for the log line and the /diagnostics heartbeat: downstream_stop=acknowledged|unacknowledged|unproven plus controllers / states / vendor stop / detail. _heartbeat_status merges these into the estop latched payload so an operator sees whether the physical stop was proven.
  • _emit_estop_telemetry(self) -> None — Emits the openral.event.estop_requested span event and increments openral.hal.estop.count. The only producer of either signal — the dashboard ingests OTLP, not /openral/estop topics, so this is the sole chokepoint every robot HAL shares on the actuation side. Never raises; telemetry must not disturb the stop path.
  • make_lifecycle_main(node_name, hal_factory) -> Callable[[], None] — Builds a main() entry point for a zero-parameter HAL adapter, via a _FactoryHALLifecycleNode whose _create_hal() returns hal_factory(). Superseded for standard arms by make_lifecycle_main_from_manifest; retained for bespoke nodes. (L613)
  • _launched_node_name(default, argv) -> str — The node name a __node:= / __name:= remap in argv sets, else default. make_lifecycle_main_from_manifest's main() derives the OTel service.name from it, so every robot sharing the one openral_hal_node executable still reports as openral.hal.<robot_id>. (L592)
  • module constant PLACEMENT_GRADE_TOPIC = "/openral/sim/placement_grade" (L124) — Where the manifest HAL node publishes the running graded goal's placement grade for the rSkill runner.
  • class ManifestHALLifecycleNode(HALLifecycleNodeBase) — Public generic manifest-driven lifecycle node. Reads robot_yaml + hal_mode + sensor knobs as ROS params and builds its HAL via openral_hal.build_hal, so a robot's construction kwargs come from hal.parameters.defaults — no bespoke _create_hal subclass needed. hal_transport_json (a JSON object deploy sim|run fills from DeployScene hal.defaults + --hal) carries every constructor kwarg, so one the node does not declare by name (galaxea host, openarm left_can_interface) is forwarded, not dropped; the named port/robot_ip/fci_ip/id/calibration_dir params win per key; a non-object raises ROSConfigError. Attaches SimSensorBridge in on_activate_post_subs. Under hal_mode:=real it attaches a RosControlTransport to any RosControlHAL and drops this node's global /joint_states publisher so the vendor's joint_state_broadcaster stays the sole writer; since issue #295 it also attaches that transport as the HAL's ControllerStopSeam (attach_controller_stop, built from controller_names() / vendor_stop_services() / vendor_stop_topics()), refuses to configure (ROSConfigError) a drivable HAL that is not ControllerStoppable, warns when controller_manager does not yet list its controllers active, and attaches an InterbotixXSTransport to an InterbotixStoppable HAL (ALOHA) via _attach_interbotix_transport, closing both seams' helper nodes in on_cleanup; it opens /openral/<robot>/reset_to_pose iff the HAL exposes reset_to_pose, and /openral/<robot>/reset_episode (std_srvs/Trigger, reply seed=<n>; proprio snapshot refreshed and republished; the vision attachment bridge is rebuilt empty, so a payload held in the previous episode is not checked against the new pose) iff it exposes reset_episode (sim-attached HALs only), and subscribes /openral/reward/active_task (std_msgs/String, RELIABLE / VOLATILE / KEEP_LAST 1) into the HAL's set_active_task iff it exposes one (_subscribe_active_task); with it, iff the HAL exposes add_placement_grade_listener, it publishes each grade of the running graded goal on PLACEMENT_GRADE_TOPIC = /openral/sim/placement_grade (std_msgs/String JSON {prompt, grade, score, require_released}, RELIABLE / TRANSIENT_LOCAL / KEEP_LAST 1, _publish_placement_grade; one listener per HAL across reconfigures, the publisher destroyed in cleanup) for the rSkill runner. When a scene composition is declared, the named composer's MJCF is threaded in as the HAL's mjcf_path, read from the scene_composition_json ROS param (the composer is imported through import_code_ref, so only openral_* code runs) — which takes precedence over the manifest's scene_defaults.composition fallback, so the scene owns its arena and the manifest describes the robot. When the manifest declares a planar base (base_joints), also attaches a MobileBaseBridge. A back-compat alias _ManifestHALLifecycleNode is retained. (L2409)
  • spin_until_shutdown(node) -> None (L662) — rclpy.spin(node) until a signal-driven shutdown, which ends it quietly: KeyboardInterrupt / ExternalShutdownException, and a RuntimeError (RCLError from a timer callback that published on the context the SIGINT handler had just invalidated — the HAL exited 1 on Ctrl-C once a depth camera published — or a take racing the shutdown). A RuntimeError with the context still up propagates. Both HAL main()s spin through it.
  • make_lifecycle_main_from_manifest(node_name) -> Callable[[], None] — Builds a main() that spins up ManifestHALLifecycleNode, reading robot_yaml + hal_mode ("sim"|"real") ROS params and constructing the HAL via build_hal(description, mode=hal_mode) — one node class serves both modes for every robot. deploy sim/deploy run inject the respective mode; a robot lacking it raises ROSCapabilityMismatch. The one caller is packages/openral_hal_node (node_name="openral_hal_node"); the launch renames the node openral_hal_<robot_id>. (L685)
  • joint_state_republish_stamp_ns(node_now_ns, sample_stamp_ns, *, wall_now_ns=None, sim_time_ns=None) -> int (L127) — Stamp for the HAL node's ~/joint_states republish: the time the sample shows. A sample on the node's own sim clock (sim_time_ns: the post-step frame's sim time, passed when the node publishes /clock from those frames) is stamped with that sim time, so every republish of one frame carries the same stamp (issue #418: the wall-age rule labelled a slow sim's frame up to 2 s early and the robot self-filter posed the arm at the wrong instant). Otherwise the node clock's now minus the sample's wall-clock age (JointState.stamp_ns), so a stamp-pairing consumer (the robot self-filter's max_joint_state_skew_s) sees a stale sample as stale. A negative or >5 s age (another clock domain) falls back to the node's now.
  • grasp_trigger_state(state: JointState, sim_time_ns: int | None) -> JointState (L181) — The joint state the vision leg's grasp trigger folds in: state re-stamped with its frame's ProprioFrame.sim_time_ns when the node has a sim clock, else state itself (real HALs). The trigger's windows are seconds of sample time; a sim-attached HAL stamps its post-step read with wall time, so a sim slower than real time spread its 1/60 s steps past max_gap_s and the jaw never settled (LeIsaac PickOrange, ~0.13x). A re-read frame keeps its sim stamp and is still a repeat. _publish_joint_state passes it to VisionAttachmentBridge.observe_joint_state only; the ~/joint_states republish keeps the HAL's stamp.
  • urdf_named_joint_state(msg, urdf_names, scales=(), offsets=(), curves=()) -> JointState (L215) — A copy of a manifest-named JointState under the URDF's joint names and units (urdf_joint_map): position scale * curve(q) + offset, velocity scale * curve'(q) * qd (curves parallel, empty / None = identity; a curved joint's rate is NaN without a position), effort passed through, "" names dropped; msg is not modified. The HAL's ~/urdf_joint_states publish (params urdf_joint_names, urdf_joint_scales, urdf_joint_offsets, urdf_joint_curves), which robot_state_publisher alone reads.
  • URDF_JOINT_UNITS_UNSET: tuple[float, ...] (L279) — (nan,), the declared default of the urdf_joint_scales / urdf_joint_offsets params: "unset" (an empty list has no ROS parameter type; NaN is never a real scale or offset), so an explicit [0.0] stays a value.
  • urdf_joint_units(n_joints, scales, offsets) -> tuple[list[float], list[float]] (L282) — The per-joint (scales, offsets) the HAL node parses from those params: an unset array expands to 1.0 / 0.0 per joint, each independently; a set one must have n_joints entries (zeros kept), else ROSConfigError.
  • urdf_joint_curves(n_joints, flat) -> list[tuple[tuple[float, float], ...] | None] (L313) — Each joint's calibration curve from the HAL's urdf_joint_curves param (UrdfJointMap.curves_param layout; unset / empty = []); ROSConfigError on a layout that does not cover n_joints joints or a curve check_urdf_curve refuses (#533).
  • sim_attachment_heartbeat(*, hal_mode: str, vision_attachment_enabled: bool) -> bool (L359) — Whether the HAL node builds SimSensorBridge with its "nothing attached, fresh" attachment heartbeat: only for hal_mode == "sim" with the vision attachment leg off. On a real arm that claim has no evidence behind it, so real mode publishes no attachment state unless the vision leg is on, and the kernel's attached-payload check fails closed rather than trusting it.
  • twin_jaw_evidence_timeout_s(*, hal_mode: str, hal_idle_steps: bool, idle_hold_s: object, configured_s: float, rate_hz: float) -> float | None (L387) — The vision leg's jaw-evidence timeout on the idle-stepping sim twin: max(configured_s, idle_hold_s + 4 / rate_hz), only for hal_mode == "sim" with a callable HAL idle_step and a float idle_hold_s; None otherwise (the configured timeout stands, and the evidence run resets on gaps). The node sets VisionAttachmentConfig.evidence_run_spans_gaps exactly when it is not None. The real node also carries a SimSensorBridge, so the bridge's presence must never be the gate (that stretched the real 0.5 s timeout past the kernel's 500 ms attached deadline).
  • decode_action_chunk(msg) -> Action | None — Inverse of ros_publishing_hal._flatten_action_payload: decodes the ActionChunk wire shape back into a typed openral_core.Action with the per-mode payload populated. Returns None for degenerate chunks, malformed ones (the kernel's wire invariants: len(flat) != horizon * n_dof, a non-finite value, an unknown control_mode byte — no longer defaulted to JOINT_POSITION) or modes the F1/F5 publisher doesn't encode (CARTESIAN_POSE, FOOT_PLACEMENT, DEX_HAND_JOINT). The HAL lifecycle node drops (logs hal.safe_action_malformed, never actuates) a None or a chunk the typed Action refuses. Preserves tick_index / tick_group_size / runner_session_id (absent session decodes to 0, session-less), joint_names (ADR-0102; absent decodes to None, a whole-vector action) and cartesian_delta_scale (predictive-safety metadata only — the raw delta passes through unchanged). (L440)

python/hal/src/openral_hal/sim_bringup.py

Resolve a SimScene or BenchmarkScene YAML path to a live SimRollout. Used by build_hal, which every manifest-driven node (incl. panda_mobile) routes through.

  • build_sim_env_from_yaml(sim_env_yaml: str, *, robot_id_fallback: str | None = None) -> tuple[SimRollout, int | None] — Loads a SimScene/BenchmarkScene YAML, resolves its scene id in openral_sim.SCENES, and instantiates the env; relative paths resolve against the source file's parents (ROS param values are cwd-naïve). Returns (env, seed) for SimAttachedHAL(env_reset_seed=seed). Binds the robot via SCENES.resolve_robot (the YAML's robot_id, else a fixed scene's default, else robot_id_fallback for free-axis scenes). Raises ROSConfigError if the YAML is missing, the scene id is unregistered, the robot is not one the scene can build, or validation fails. Scene-id agnostic: continuous-mode ignore_done is the backend's enable_continuous. (L168)
  • sim_scene_backend_options(sim_env_yaml: str) -> dict[str, object] — scene.backend_options of the SimScene / DeployScene YAML build_sim_env_from_yaml attaches, its relative asset paths resolved beside the scene file like the scene's own (openral_core.scene_paths.anchor_scene_paths, so a scene shipped in another repo boots under deploy sim) (same path resolution, ROSConfigError likewise); what build_hal hands to openral_core.sim_scene_description. (L150)
  • hal_transition_timeout_s(deploy_config: str | None) -> str — Per-transition budget for the HAL's tools/lifecycle_autostart.py, derived from the scene: max(300.0, scene.backend_options.boot_timeout_s + 60.0). Falls back to the 300 s floor for no config, an unreadable path, or a malformed value. A sidecar backend boots the simulator inside on_configure, so this bounds the same call build_sim_env_from_yaml makes. (L254)
  • const HAL_TRANSITION_TIMEOUT_FLOOR_S = 300.0 / HAL_TRANSITION_TIMEOUT_MARGIN_S = 60.0 — The floor covers a robocasa-kitchen first boot; the margin covers the import + first reset following a sidecar handshake. Also the ceiling on how long a wedged HAL stays unreported. (L248)
  • const HAL_TRANSITION_TIMEOUT_MARGIN_S = 60.0 (L251) — see above.
  • _synthesise_deploy_task_id(scene_id) -> str (L54) — The inert "<scene_id>/_hal_deploy_noop" task id for a taskless DeployScene; each backend interprets it (LIBERO → task 0), so no scene-id list lives here.

python/hal/src/openral_hal/sim_scene.py

The robot console's Sim scene layer, HAL side (platform#133, #137, #139): turns a scene_mesh(limit_bytes) reply (the Isaac sidecar's, or mujoco_scene_mesh on a live MuJoCo model) into /openral/viz/sim_scene's payload. SimAttachedHAL (the one sim HAL shell, MujocoArmHAL included) exposes it as export_sim_scene(), which the lifecycle node calls when it latches the topic, so nothing is exported outside a deploy.

  • write_sim_scene(scene_mesh) -> dict[str, object] (L45) — Asks scene_mesh for the static scene GLB (at SIM_SCENE_LIMIT_BYTES) and, once the reply checks out, writes it as <sha12>.glb into SIM_SCENE_PACKAGE, sweeping GLBs untouched for a week. Returns {"uri", "bytes", "triangles"} or {"note"}: an export failure is a note, never a failed connect, but a ROSSafetyViolation is re-raised. Logs sim.scene_export.
  • class SceneCache (L89) — One write_sim_scene result per scene source (key: the live MjModel, or one constant for an Isaac stage); a failed export, or a GLB another deploy's sweep removed, is redone on the next call.
  • get(key, scene_mesh) -> dict[str, object] (L113) — The cached payload for key, exporting through scene_mesh when the key changed, the last export failed or its GLB is gone; touches a still-present GLB so the week-old sweep keeps it.
  • odom_from_base(hal) -> NDArray[np.float64] (L131) — The base frame's 4×4 pose in /openral/viz/sim_scene's frame, as MobileBaseBridge sees it: identity for a fixed base; for a mobile base the odom → base pose from base_pose_6dof() when the HAL has one, else the planar base_pose.
  • mujoco_scene_mesh(model, data, description, limit_bytes, odom_from_base_link=None) -> dict[str, Any] (L189) — scene_mesh for a live MuJoCo model (platform#139): tools/scene_glb.py's mujoco_static_scene_glb in odom_from_base_link · base_from_world, the base body being the one resolve_base_frame_body_name names, else the root body of the actuated joints; with no base body the scene stays in the MuJoCo world.

python/hal/src/openral_hal/sim_attached.py

The one sim HAL shell, SimAttachedHAL — HAL Protocol adapter over any in-process SimRollout / SimEnv, with the attachment API, reset_episode and per-goal grading. It serves panda_mobile and every scene-attached deploy-sim HAL; every MujocoArmHAL twin (whose env is a MujocoTwinRollout, #683) is a SimAttachedHAL. Its scene-backend paths need openral_sim + mujoco; a twin built with an explicit env_action_dim never imports openral_sim.

  • module const _TASK_SUCCESS_LOGGER (L84) — dedicated openral.sim.task_success structlog logger (dotted under openral. so the OTel bridge attaches).
  • module const _EVENT_TASK_SUCCESS (L89) — the sim.task_success event name _emit_task_success logs.
  • module const _EVENT_TASK_SUCCESS_FINAL (L90) — the sim.task_success_final event name, emitted from disconnect.
  • module const _EVENT_TASK_SUCCESS_PROBE_FAILED (L91) — the sim.task_success_probe_failed event name, emitted once when the backend's success predicate raises.
  • module const _ROBOSUITE_GROUP_PREFIX (L221) — robosuite body-name prefix (robot0_/robot1_) stripped by normalized_joint_index's prefix-fallback.
  • module const _BASE_TWIST_HOLD_NS = 500_000_000 — how long a base setpoint keeps driving with no new command (diff_drive_controller's cmd_vel_timeout). Measured on the backend's sim clock when it has one (_twist_hold_clock_ns), else wall time: Nav2 publishes on sim time.
  • _group_route(env) -> (step_action_group | None, fixed group size, every command a group) [private] — The send route for a backend that takes typed commands, decided once in SimAttachedHAL.__init__ from what the env declares: action_group_size > 0 (BEHAVIOR: fixed-size groups of ungrouped slots), steps_every_command_as_group (the MuJoCo twin: an ungrouped action as a group of one), neither (multi-slot groups only; an ungrouped action is refused at send with ROSConfigError, as before #683).
  • _group_twist_row(actions) -> list[float] | None [private] — The first BODY_TWIST slot's row of a command (the base_twist latch of a group).
  • module const _PENDING_GROUP_STALE_NS (L269) — how long idle_step waits before loudly discarding a pending mid-flight atomic action group.
  • ActionPacker — Type alias Callable[..., np.ndarray]. Per-composition translator between an OpenRAL Action and the env's flat action vector; default factory is pack_action_for_env. The optional trailing prev arg lets a packer carry an untouched slot (e.g. the gripper while the arm steps) across a split policy step. Pass a custom instance to SimAttachedHAL.__init__ for whole-body/dexterous-hand layouts. (L279)
  • gripper_targets_action(group: list[Action], description: RobotDescription) -> Action | None (L160) — What a committed slot group set for every role: gripper joint, as a one-row compact JOINT_POSITION action (joint_names = every gripper in manifest order) that VisionAttachmentBridge.observe_command reads positionally. Placement is _slot_group.slot_group_targets (the composer's own strictness, never a laxer re-implementation). All or nothing: None when the manifest has no gripper, the group left any gripper uncommanded, or a slot is unreadable (gripper slot with no/unknown ee_name or empty payload, joint row too short for a joint it names) or overlapping — a partial record would leave the uncovered jaw's stale command in the grasp trigger (a phantom attach), while None clears every jaw. SimAttachedHAL._commit_group records it as last_applied_action for a group compose_slot_group_action refuses (a base twist on a mobile manipulator), so the jaw command still reaches the grasp trigger. A record, never a command to apply.
  • normalized_joint_index(model_joint_names: list[str]) -> dict[str, int] — Maps MJCF joint names (exact + robosuite-prefix-stripped) to model index; exact names always win, robot0_joint1 → joint1 is added only when it doesn't shadow or collide. Used by SimAttachedHAL.read_state so one manifest serves both native MjSpec and robosuite scenes. (L224)
  • pack_action_for_env(action: Action, description: RobotDescription, env_action_dim: int, prev: np.ndarray | None = None) -> np.ndarray — Default ActionPacker: translates JOINT_POSITION, BODY_TWIST (slots 0-2), CARTESIAN_DELTA (arm slots), and GRIPPER_POSITION (last slot) into the env's flat action vector. Raises ROSConfigError for unsupported modes or mismatched row widths. prev carries an untouched slot (e.g. gripper) across a policy step that splits into two Actions on a non-composite env — without it each Action zeroed the other's slots. (L297)
  • class SimEnv(Protocol) (L110) — What the shell calls on its env directly (reset, step, close); every other hook is getattr-gated. An openral_sim.SimRollout and a MujocoTwinRollout both satisfy it.
  • reset(seed=None) -> Any (L116) — reset; the initial observation.
  • step(action) -> Any (L119) — one action; the transition.
  • close() -> None (L122) — release the backend.
  • class SimAttachedHAL (L489) — The one sim HAL shell: HAL Protocol adapter wrapping an in-process SimRollout (or any SimEnv; the bare MuJoCo twin's MujocoTwinRollout). Reads live joint state via normalized_joint_index + mj_name2id; sends actions via a caller-supplied ActionPacker, else the env's own pack_action(action, prev) hook when it defines one (a backend that knows its slot layout — the Isaac manifest scene: name-addressed, absolute; also used for its BODY_TWIST path and its slot groups — which may then carry a BODY_TWIST slot, the twist kept across the tick's slots and latched for /odom — with None rather than zeros as the first prev), else pack_action_for_env, into env.step(). connect() drops the last packed vector, so pre-reset targets never ride along. Exposes read_images(), mujoco_handles(), sim_time_ns(), base_pose, base_twist, base_pose_6dof() for the lifecycle node's camera, viewer, clock, and odom wiring. On its first connect() against an env with scene_mesh (the Isaac sidecar), _export_sim_scene writes the returned GLB as <sha12>.glb into SIM_SCENE_PACKAGE (dropping any earlier scene's GLB there) and stores in sim_scene the payload the lifecycle node latches on /openral/viz/sim_scene for the console's Sim scene layer (platform#133): {"uri": "package://openral_sim_scene/…", "bytes", "triangles"} or {"note"} (an export failure is a note, never a failed connect). (L491)
  • step_estop_hold() -> bool (L1842) — One tick while the e-stop is latched (the node's latch or this HAL's own).
  • __init__(env: SimEnv, description: RobotDescription, *, action_packer: ActionPacker | None = None, env_reset_seed: int | None = None, env_action_dim: int | None = None, body_twist_dt_s: float = 0.05) -> None (L542) — body_twist_dt_s is the scene-attached MuJoCo qpos base path's interval (_apply_body_twist_to_qpos); a twin integrates its own control period (MujocoTwinRollout._resolve_twist_interval). Resolves the send route (_group_route).
  • connect() -> None — Resets the env at env_reset_seed (a typed ROSError from env.reset propagates as raised); probes env_action_dim via _probe_env_action_dim, raising ROSConfigError naming the backend if not introspectable and no override given; then _check_time_base — a refusal leaves the HAL disconnected. The estop latch survives a reconnect; only reset_estop clears it. Idempotent while connected. (L721)
  • _check_time_base() -> None (L775) — For a backend that declares sim_dt_per_tick_s (the Isaac sidecar, RoboCasa, LIBERO, a MujocoTwinRollout held to its rate — the one check and log line for every sim HAL), refuses via openral_core.check_time_base (ROSConfigError) an env whose step is not one control period of the robot (1 / description.control_rate_hz, 1 % tolerance _TIME_BASE_TOL) or a manifest with no control rate to hold it to; records the tick and logs sim.time_base (backend, sim_dt_per_tick_s, control_freq_hz, robot, plus the env's time_base_fields) once per connect so a trace carries the time base it was captured on (issue #355). A backend without the field is not checked (RoboCasa/LIBERO step at their own control rate).
  • (property) sim_dt_per_tick_s -> float | None (L819) — Sim seconds one command advances once held to the control rate (set at connect); None before it or for a backend that declares no tick.
  • set_frame_period_s(period_s) -> None (L1535) — Frames on demand for a backend with set_frames_next_step (Isaac): _request_frames asks for "fresh" frames on the step that completes a period_s of sim time since the last rendered one (or after the sim clock went back), "none" otherwise; None renders every step. SimSensorBridge.setup passes 1 / max(camera_rate_hz, depth_rate_hz).
  • refresh_frames() -> bool (L1549) — Render the current state's frames now without stepping (env.refresh_frames, Isaac) and cache them as the newest observation/depth frames; False for a backend without it. SimSensorBridge calls it when the attachment perception barrier starts waiting for a depth frame, then publishes the depth at once: the barrier holds the runner, so neither the sim nor the sim-clock depth timer would move until the idle stepper's 2 s hold.
  • release_env() -> None (L935) — At process teardown (shutdown_hal, never on a cleanup a configure may follow), close a keep_alive backend so its sidecar detaches and the next deploy sim of the scene adopts it; any other env is left to its owner. Idempotent.
  • disconnect() -> None — Emits the terminal sim.task_success_final line, then releases the env handle (idempotent). (L910)
  • read_state() -> JointState — Walks description.joints, resolves each via normalized_joint_index (built over every MJCF joint id, unnamed ones kept as "" so later joints keep their index), reads live qpos/qvel from MJCF and effort via joint_actuator_effort. Without MuJoCo handles (Isaac, BEHAVIOR, RoboTwin, SimplerEnv) it reads obs["joint_positions"|"joint_velocities"|"joint_efforts"] (_read_state_from_obs): in description order with exactly one value per joint, or keyed by obs["joint_names"] (each joint by name, then sim_joint_name; extra names ignored). Position is all or refuse: a missing key, a wrong-width vector or an unreported joint raises ROSRuntimeError, never a zero pose (runtime, not ROSPerceptionStale: no fresher observation would carry it). Velocity is all or nothing (velocity=[]). Effort is all or nothing: a joint absent from the MJCF, no joint_efforts key, or a short vector yields effort=[], never zero rows. A backend with a read_joint_state() hook (MujocoTwinRollout) serves the state itself instead. (L950) An affine_low_high gripper joint reads its [0, 1] opening over ctrl_range (velocity scaled alike), not its finger travel (gym-aloha).
  • send_action(action: Action) -> None (L1114) — Routes one command: ROSRuntimeError ("... not connected") before connect; while estop-latched, drops it and logs hal.send_action.dropped_estop_latched once per latch episode (WARNING, estop → reset_estop). A slot (tick_group_size > 1), or any action on a backend with a fixed action_group_size, is staged (_stage_action_group); an ungrouped action is refused on a groups-only backend, else checked against the watermark (SlotGroupStager.admit) and its twist against the planar rule (_check_twists), then on a backend that takes every command as a group (the MuJoCo twin) stepped as a group of one (_step_env_group); otherwise packed via composite-split or ActionPacker into env.step, a BODY_TWIST Euler-integrating qpos directly on a MuJoCo backend (_apply_body_twist_to_qpos), else held as the base setpoint (_apply_body_twist_via_env_step); then the action itself is committed (commit_tick: an ungrouped action is its own last_applied_action). Only an accepted command (staged or applied) stamps last_action_ns (_mark_active): a refused or latch-dropped one does not, nor does a base setpoint, which steps nothing and needs the idle stepper running.
  • _commit_ungrouped(action) -> None [private] — commit_tick + _mark_active.
  • _mark_active() -> None [private] — Stamp last_action_ns (a command was accepted).
  • _log_latched_drop(action) -> None [private] — The once-per-latch-episode hal.send_action.dropped_estop_latched line.
  • _check_twists(actions) -> None [private] — Every BODY_TWIST of a command through _floating_base.validate_planar_body_twist (differential= the manifest's base_kinematics), before anything steps.
  • _finish_step(step_result, rendered) -> None [private] (L1492) — The bookkeeping after every simulator step, once per step: caches the transition, counts the step, polls the task-success witness, runs the post-step observers. Run by _step_boundary for every route.
  • _step_boundary(step, source) -> Any [private] — The one step boundary every route steps through (_step_and_cache, _step_env_group, the env's idle hook): frames on demand before, _finish_step after (unless an idle hook returned False); a typed ROSError propagates as raised, anything else becomes ROSRuntimeError (".: env.step failed: ...").
  • _latch_twist(row | None) -> None [private] — The one base_twist latch: (vx, vy, 0, 0, 0, wz) of a 6-float row, else zero.
  • export_sim_scene() -> dict[str, object] | None (L744) — /openral/viz/sim_scene's payload for the live scene through a SceneCache: the Isaac sidecar's scene_mesh, else sim_scene.mujoco_scene_mesh on the env's live model in the odom_from_base frame; re-exported after a reset that composed a new MjModel or a failed export; None without an exporter. Never raises but ROSSafetyViolation (write_sim_scene).
  • _stage_action_group(action) -> None — Stages each safety-approved slot through _stage (SlotGroupStager, keyed by (Action.runner_session_id, Action.tick_index); a fixed-size backend's group size when the action is ungrouped) and commits one sim step only when the complete tick is present (atomicity): a lost slot raises ROSRuntimeError ("incomplete slot group") and the exposing slot opens the next tick, a slot that changes its tick's declared size discards the tick (ROSRuntimeError), a replay is refused (TickWatermark.check), a new runner session's first slot drops the old session's partial tick (logged hal.slot_group.stale_partial_dropped), and a new session is adopted only when its group commits. estop() / discard_staged_slots() keep the watermark; disconnect() / reset_episode() clear it. Latches the group's BODY_TWIST slot into base_twist on commit.
  • _stage(action, group_size=None) -> list[Action] | None [private] (L1287) — SlotGroupStager.stage; a slot the stager took (staged, adopted or completing) marks the HAL active, and one left staged restarts the stale-group timer idle_step reads — a refused slot does neither, so it cannot keep a dead tick alive.
  • _step_env_group(actions, group_step) -> Action | None [private] (L1352) — One step_action_group call inside _step_boundary, then the base_twist latch. Returns the command the backend reports it applied (info["applied_action"]), which _commit_group records for a slot group.
  • _require_connected(operation) -> None [private] (L870) — _base.require_connected ("... called while not connected ...").
  • read_policy_state() -> list[float] | None (L2883) — Cached simulator-native checkpoint proprioception (e.g. BEHAVIOR's 61-D R1Pro vector) for /openral/policy_state; only from an explicit obs["policy_state"], never inferred.
  • reset_estop() -> None (L2853) — Clear the e-stop latch (and re-arm the dropped-command log); caller asserts the cause has been resolved. Then stop_stale_motion: the robot comes back holding its present pose.
  • stop_stale_motion() -> None (L2863) — Drop every setpoint still in flight: the held base twist (/odom reads still), the cached env action (the next pack's prev, so an absolute-target env such as RoboTwin seeds unset slots from the measured pose instead of resuming the cut-short target) and, through the backend's hold_present_pose, the arm's targets. Called by the HAL lifecycle node at its /openral/estop latch and at /openral/estop_cleared (_stop_stale_motion; openral#700 item 1), so a stopped robot does not drive or move toward a stale goal after the clear.
  • urdf_extra_joint_positions [@property] — URDF joints outside the manifest that still move (a wheel-driven base's drive wheels), name → position, from the backend's read_urdf_extra_joint_positions() (the MuJoCo twin) or obs["urdf_extra_joint_positions"] (the Isaac scene); empty otherwise. The HAL node publishes them as a second message on ~/urdf_joint_states so robot_state_publisher places the wheel links on /tf. (L2768)
  • step_estop_hold() -> bool (L1842) — One tick while the e-stop is latched (the node's latch or this HAL's own): steps the backend's estop_hold_action (one robot of a shared Isaac world: the idle hold, every target kept, the base stopped; ADR-0137) so its /joint_states stays current for its peers, else False (freeze). Post-step observers run after it. Called by SimSensorBridge._step_estop_hold.
  • idle_step(wall_dt_s=None) -> bool — Sim-only free-running stepper: advances the SimRollout one HOLD tick (the backend's idle_action(), else np.zeros(env_action_dim)) so cameras keep rendering when idle; a backend with its own idle_step(wall_dt_s) hook (MujocoTwinRollout: a wall-time physics slice, ctrl untouched) is advanced by it instead, through the same step boundary (_step_boundary). Returns False when not connected, estop-latched, or the action dim is unresolved (no MuJoCo-handle gate). Defined only on the sim shell (SimAttachedHAL) — real HALs never define it, since a zero vector is HOLD in sim but "drive to 0 rad" on a real arm. (L1877) Refuses to interleave a HOLD inside a mid-flight atomic action group, discarding a stalled pending group after 5 s. A step it runs packs a held base setpoint (see _apply_body_twist_via_env_step) into the twist slots and reports it as base_twist until _BASE_TWIST_HOLD_NS after its last command; otherwise the base is still and base_twist zero.
  • read_images() -> dict[str, Any] — Return latest rendered camera frames keyed by camera name from the cached _last_obs; a backend with a read_images() hook (MujocoTwinRollout, renders on demand) is asked instead, and read_image_times stays empty for it. (L2551)
  • read_depth_clouds() -> dict[str, NDArray] (L2606) — Per-depth-sensor (N,3) base_frame clouds derived from the newest read_depth_frames frame by depth_cloud.cloud_from_depth_frame (within the sensor's range_max_m in the base plane); each frame deprojected once (_depth_cloud_cache), its cloud returned as the same array until a newer frame arrives, since SimSensorBridge publishes each cloud once by identity. SimSensorBridge publishes it in the camera's optical frame (back through the frame's optical_in_base): octomap_server casts rays from the cloud frame's origin, and a base_frame cloud cast them from the robot base (issue #418). {} when the backend renders no depth (MuJoCo backends ray-cast instead).
  • read_depth_cloud_colours() -> dict[str, NDArray[np.uint8]] (L2639) — Per-point RGB of the clouds read_depth_clouds last returned (the pixel each point came from); a sensor whose frame has no matching colour raster is absent. SimSensorBridge colours the published PointCloud2 with it.
  • read_image_times() -> dict[str, int] (L2587) — Sim time (ns) each cached camera frame shows, keyed like read_images (depth cameras by sensor name), from a backend's "image_time_ns" obs slot plus the cross-reset offset, so sim_time_ns() - read_image_times()[k] is that frame's age. The Isaac sidecar reports it because its RTX pipeline delivers frames steps behind the physics (issue #361); {} when the backend reports none. SimSensorBridge stamps each frame with it.
  • read_depth_frames() -> dict[str, dict[str, Any]] (L2647) — The newest registered colour + metric depth frame per depth sensor from a non-MuJoCo backend's "depth_frames" obs slot ({name: {"depth", "rgb", "k", "optical_in_base"}}, the Isaac manifest scene's _depth_frames), kept across the steps that carry none (_keep_depth_frames); {} when the backend renders none. SimSensorBridge._publish_depth_frame publishes each frame once.
  • add_post_step_observer(observer: Callable[[], None]) -> None (L1109) — Registers an idempotent synchronous hook after each real simulator transition; automatic attachment evidence uses this so grasp/release changes publish before the next policy tick is acknowledged.
  • read_scan() -> NDArray | None (L2661) — 2-D LaserScan range fan (base_link) from _last_obs["scan"] on a non-MuJoCo backend that ray-casts a lidar (Isaac); None otherwise. Captured with each observation as ProprioFrame.scan and published on /scan by SimSensorBridge.publish_scan_from_frame.
  • mujoco_handles() -> tuple[Any, Any] | None — Forward the env's (model, data) MJCF handles. (L2394)
  • task_success() -> bool | None (L1609) — Forwards the wrapped rollout's optional task_success() predicate (RoboCasa: the task's own _check_success()); None means "no predicate, or one that raised", never "failed". Observability only — feeds no termination/reset/reward/action path. Logged as sim.task_success (both edges, since RoboCasa success isn't latched) and sim.task_success_final at disconnect. Full signal table in docs/reference/telemetry.md.
  • last_committed_tick -> int [@property] (L2427) — Most recent ticked action or complete slot group committed to the simulator (SlotGroupStager.last_committed_tick).
  • last_committed_session -> int [@property] (L2432) — runner_session_id of that group (0 = none / session-less).
  • last_applied_action -> Action | None [@property] (L2415) — The command the simulator was last stepped with: for a slot group, compose_slot_group_action over the manifest joints, set in step with last_committed_tick (private _commit_group), or, when the group is not one joint-position command (BODY_TWIST / Cartesian slot, uncommanded joints, a joint slot without joint_names), its gripper targets as a compact action (gripper_targets_action; None when it set none placeable); for an ungrouped action, the action itself; cleared on disconnect. Fed to the grasp trigger by the lifecycle node (it had none, so slot-group jaw commands never reached it).
  • sim_time_ns() -> int | None (L2467) — Cross-reconnect-monotonic elapsed sim time in ns; connect (and a twin's release at disconnect / estop) folds elapsed time into an offset so a lifecycle reset doesn't rewind it.
  • clock_authority() -> ClockAuthority (L2492) — Returns ClockAuthority.simulation(<env.clock_id, else the backend class name>, timestep_s=<the env's declared sim_dt_per_tick_s, else its physics_dt_s, else body_twist_dt_s>) when sim_time_ns() is live, else ClockAuthority.host_wall().
  • discard_staged_slots() -> int (L1273) — Drops a half-staged action group (SlotGroupStager.discard, watermark kept); called by the HAL lifecycle node at every /openral/estop latch and /openral/estop_cleared, so a tick a kernel stop cut short never reaches the next goal as an incomplete group. Returns the slots dropped.
  • estop() -> None — Latch e-stop: subsequent send_action calls are dropped (logged once) and idle_step does not step; the base stops and a half-staged group is dropped (watermark kept). The latch survives a reconnect; only reset_estop clears it. Does not raise (a scene-attached env's stop is this latch; the twin's MujocoArmHAL.estop raises). (L2380)
  • (property) env -> SimRollout (L2531) — Direct access to the wrapped sim env (for tests / advanced wiring).
  • (property) estop_latched -> bool (L2536)
  • base_pose -> tuple[float, float, float] [@property] — Current (x, y, yaw): the backend's own read_base_pose() when it has one (the twins' pinned or free base, the OpenAMRobot's planar joints); (0, 0, 0) for a manifest with no planar base (describes_mobile_base); obs["base_pose"] on a non-MuJoCo backend (Isaac), (0,0,0) if it reports none; else the MJCF qpos of base_joints[:3] (_base_qpos_addrs; a joint absent from the MJCF reads 0, one or two declared base joints raise ROSConfigError). Feeds the /odom publisher. (L2679)
  • _base_qpos_addrs(model, mujoco, *, strict) -> list[int | None] [private] — The qpos address of each base_joints[:3] joint (by sim_joint_name); ROSConfigError for fewer than three base joints (no planar base), and (strict, the twist path) for one missing from the MJCF.
  • _apply_body_twist_to_qpos(row) -> None [private] — The scene-attached MuJoCo base path: integrate_planar_twist over body_twist_dt_s into the _base_qpos_addrs(strict=True) qpos, mj_forward, refresh_obs, sim clock advanced by the same dt; a manifest without a planar base is refused (it never falls back to the first three joints).
  • base_twist -> tuple[float, float, float, float, float, float] [@property] — Last commanded body twist (vx, vy, vz, wx, wy, wz); zeroed by a non-BODY_TWIST action or an idle HOLD step — or the backend's own read_base_twist() (the G1 GR00T WBC held command). (L2784)
  • _apply_body_twist_via_env_step(row: list[float]) -> None — Non-MuJoCo BODY_TWIST (the Isaac kinematic base): validates the planar twist and holds it as a velocity setpoint, as a real base controller takes /cmd_vel. It steps nothing; every idle step integrates it until _BASE_TWIST_HOLD_NS (0.5 s, diff_drive_controller's cmd_vel_timeout) after the last command. Stepping once per message tied the distance driven and the sim clock to the message rate (2/3 of the commanded distance at 20 Hz, an /odom twist flickering to zero, Nav2 overshooting).
  • base_pose_6dof() -> tuple[...] | None — Full 6-DoF (xyz, quat_xyzw) from robocasa raw_proprio; None for non-robocasa backends. (L2800)
  • last_action_ns -> int [@property] — Monotonic ns of the last command send_action accepted (staged or applied; not a refused or latch-dropped one, not a base setpoint); 0 until the first one. Read via should_idle_step to yield the idle stepper to an active skill. (L2541)
  • camera_intrinsics() -> dict[str, IntrinsicsPinhole] (L2405) — The wrapped env's rendered RGB camera K (_IsaacSimSidecar.camera_intrinsics, lens included), {} for a backend without it; SimSensorBridge._rgb_camera_info publishes a non-MuJoCo camera's CameraInfo from it.
  • set_active_task(prompt) -> None (L2996) — (Scene-attached surface, on every twin since #683, switched on by getattr reflection in the lifecycle node / sensor bridge, like reset_episode and the attachment API below.) Deploy-sim per-goal placement grading: forwards the dispatched goal's prompt to the env's set_task (Isaac placement_success), then logs sim.placement_grade per grade change (read from step info["placement_grade"]), sim.placement_grade_final (closing + best grade) when the goal ends ("", the next prompt, or disconnect), and sim.placement_grade_unavailable once for a prompt the scene does not grade (WARNING + latch off if set_task raises). While the goal runs, each grade (the starting one included) also reaches the add_placement_grade_listener listeners; a grade after the goal ends reaches none. No-op for an env without set_task. Fed by ManifestHALLifecycleNode from /openral/reward/active_task.
  • add_placement_grade_listener(listener) -> None — Calls listener({prompt, grade, score, require_released}) on each grade of the running graded goal, on the stepping thread; a raising listener is logged (sim.placement_grade_listener_failed), never allowed to break the step. The HAL node registers one per HAL that publishes /openral/sim/placement_grade for the rSkill runner. (L1750)
  • reset_episode() -> int (L2899) — Starts a fresh episode on the live env without rebuilding it (sim only): the same env.reset + per-episode bookkeeping as connect, with seed = base reset seed + episode index (1, 2, …), so per-reset randomisation (Isaac pose_noise) draws a new, reproducible layout each episode. Returns the seed. Served by ManifestHALLifecycleNode as /openral/<robot>/reset_episode.
  • episode_reset_supported: bool (class attribute) — True; the HAL node opens /openral/<robot>/reset_episode only when it is. reset_episode also requires a live connection, and _reset_env folds the elapsed sim time into the clock offset only once env.reset succeeded.
  • update_attached_objects(objects: list[AttachedCollisionObject]) -> None (L2926) — Atomically resolves a complete sim attachment snapshot from evidence_ref="mujoco_body:<name>", including descendant bodies; preserves the previous snapshot on malformed/unknown identities. Without MuJoCo handles (Isaac) it records the set and masks nothing, as on real hardware (#349); on a MuJoCo backend an object whose evidence names no MuJoCo body (the vision leg's segmenter_mask:…) is recorded the same way, so a kernel-accepted revision never stays pending and holds the action ack; the octomap bridge clears the payload's cells only for a tracker-bound attachment (object_tracking: on, OctomapVoxelBridge::clear_by_identity), so a geometry-only payload stays mapped (fail closed).
  • read_attached_objects() -> list[AttachedCollisionObject] (L2988) — Stable payload state SimSensorBridge unions with the robot self-filter so carried objects are absent from world occupancy.
  • read_attached_body_ids() -> frozenset[int] (L2992) — Exact MuJoCo body ids of everything currently attached.

python/hal/src/openral_hal/convex_distance.py

Certified signed distance between two MuJoCo convex geoms — replaces mujoco.mj_geomDistance, which under mujoco 3.8.0 returns confidently wrong values (silently) on some geom pairs the collision-evidence probes adjudicate. Represents each geom as conv(core) ⊕ ball(radius), solving via GJK (separated cores) or exact SAT (overlapping), with curved geoms bracketed by inscribed/circumscribed polytopes; runs only in evidence collection (~2-4 ms/pair), never on the 100 Hz path.

  • ConvexDistance [@dataclass(frozen=True)] — One certified signed distance with its proof: distance_m (the closest end of the bracket — never overstates separation; negative is penetration depth), lower_m/upper_m, certified, uncertified_reason, witness_a/witness_b, direction, duality_gap_m, method. direction (unit b→a, or the MTD axis when overlapping) is the only reliable contact direction at a flush contact, where the two witnesses coincide. as_record() serialises non-finite bounds as None, never Infinity, for strict-JSON round-tripping. (L93)
  • ConvexDistance.as_record() -> dict[str, object] (L140) — see above.
  • module const _ARC_SEGMENTS: Final[int] = 256 (L78) — default polygonisation segment count for a round-type (cylinder/ellipsoid) bracket.
  • module const _BRACKET_TOL_M: Final[float] = 1e-4 (L80) — certify a bracket this tight or tighter.
  • module const _DUALITY_TOL_M: Final[float] = 1e-9 (L82) — certify a separating-axis duality gap this tight or tighter.
  • module const _OVERLAP_TOL_M: Final[float] = 1e-12 (L86) — below this, GJK's terminal simplex has collapsed onto the origin (overlap is SAT's branch, not GJK's).
  • module const _MAX_SAT_AXES: Final[int] = 8_000_000 (L89) — refuse an exact penetration depth beyond this many SAT axes rather than spend unbounded time or silently subsample.
  • ConvexBody [@dataclass(frozen=True)] — A geom as conv(core) ⊕ ball(radius) plus the faces SAT needs; faces is None for a visual mesh (no compiled hull graph), costing nothing until the cores actually overlap. (L167)
  • convex_geom_distance(model, data, geom_a: int, geom_b: int, *, distmax_m: float | None = None, arc_segments: int = 256) -> ConvexDistance — The instrument. distmax_m enables a certified window rejection (method="beyond-window") via a separating-axis bound valid in every direction. certified is False, with a reason, for a geom with no bounded convex hull, a round-type bracket wider than 0.1 mm, or an unclosed/oversized-axis-set overlap; no plausible number is ever substituted for a defensible one. (L586)
  • witness_clearance_m(model, data, geom_id: int, point, *, arc_segments: int = 256) -> float — Certified lower bound on how far point lies outside geom_id; positive proves it's outside. Used to contradict a claimed nearest-point witness (both ends of a real nearest-pair segment lie on their own geoms). Falls back to the bounding sphere for a geom with no hull, -inf for one with neither. (L724)
  • separating_axis_bound(points_a, points_b, direction) -> float — Weak-duality lower bound on the distance along one direction: min_B u·b − max_A u·a. Evaluated at the direction a witness claims, turning a GJK answer into a proof. Returns -inf for a degenerate direction. (L449)
  • mesh_hull(model, mesh_id: int) -> tuple[Any, Any | None] — The hull MuJoCo itself collides, (vertices, faces) in mesh-local frame, decoded from the compiled hull graph rather than recomputed. faces is None for a mesh with no graph — distance stays exact, only penetration depth loses its axis set. (L188)
  • geom_convex_bracket(model, data, geom_id, *, arc_segments=256) -> tuple[ConvexBody, ConvexBody] | None — World-frame (inscribed, circumscribed) ConvexBody pair bracketing one geom (exact for box/mesh/sphere/capsule, polygonised for cylinder/ellipsoid); None for a geom with no bounded convex hull. (L280)

python/hal/src/openral_hal/sim_sensor_bridge.py

Shared sim-sensor + viewer bridge for scene-attached HAL lifecycle nodes: republishes RGB camera frames, /scan, depth PointCloud2 (MuJoCo ray-cast, or a non-MuJoCo backend's own clouds), a live MuJoCo viewer, and the sim-only idle stepper for any manifest-driven node. Also owns the attachment-state, ADR-0097 place-declaration, and E-stop ground-truth snapshot wiring; a place declaration naming a target absent from the scene is refused and logged, and its region/geometry is always this producer's own measurement, never a relayed value. rclpy imported lazily.

  • frame_stamp_ns(node_now_ns: int, frame_time_ns: int | None, sim_now_ns: int | None, *, on_sim_clock: bool = False) -> int (L379) — Header stamp for a sim sensor frame: the sim time it shows. On the sim clock (on_sim_clock, the node's ROS time driven by the HAL's /clock) the stamp is frame_time_ns itself (issue #418: the age form was early whenever the node clock trailed the HAL's newest sim time, and the robot self-filter posed the arm too early); otherwise the node's now minus the frame's age on the sim clock (sim_now_ns - frame_time_ns), by the same rule as joint_state_republish_stamp_ns (no frame time, no sim clock, or a negative / >5 s age keeps the node's now). Used by SimSensorBridge for the RGB images, depth clouds and RGB-D frames of a backend that reports read_image_times (issue #361).
  • glfw_display_usable() -> bool (L269) — Whether GLFW can open a display, probed once in a child process (mujoco.glfw): MuJoCo's viewer init fails in C (mju_error) and exits the process on a DISPLAY that is set but unreachable, or a WAYLAND_DISPLAY without a session, which no except can catch (openral#700 item 7). SimSensorBridge._setup_viewer skips the viewer when it is False. Cached.
  • should_idle_step(now_ns: int, last_action_ns: int, idle_hold_ns: int, *, step_while_active=False) -> bool — Pure predicate for the sim-only wall-time stepper: scene-attached envs return True only after the idle-hold window; bare MujocoArmHAL passes step_while_active=True so its target keeps integrating during active skills. Used by SimSensorBridge._idle_step_tick. (L294)
  • module const _THUMB_INTERVAL_NS = 1_000_000_000 (L44) — throttle dashboard thumbnail emission to ~1 Hz per camera; the live ROS topic itself stays at camera_rate_hz.
  • module const _IMAGE_DIM = 3 (L45) — HWC ndarray rank.
  • module const _RGB_CHANNELS = 3 (L49)
  • module const _MAX_PREATTACH_CELLS = 2_000_000 (L53) — cap on the pre-attach occupancy snapshot; an over-large grid is refused/truncated rather than partially sampled.
  • module const _DEGENERATE_QUAT_NORM = 1e-12 (L57) — below this a quaternion carries no usable direction; keep identity rather than divide by ~0.
  • module const _NEAREST_PROBE_DISTMAX_M = 0.10 (L71) — near-miss probe bounding-sphere prefilter gap for the e-stop ground-truth snapshot.
  • module const _NEAREST_PROBE_MAX_CALLS = 4096 (L72) — exact-distance call budget for one snapshot's near-miss probes.
  • module const _NEAREST_PROBE_MAX_PAIRS = 32 (L73) — closest-pairs cap reported per probe.
  • module const _VOXEL_BACKING_RAYS_PER_AXIS = 3 (L80) — rays per cube axis for voxel_backing_record's ray-fan sampling.
  • module const _QUAT_NORM_TOL = 1e-6 (L84) — tolerance on |q|^2 for a published grid orientation; wide enough for a wire round-trip, too tight for an unset all-zero field.
  • module const _VOXEL_BACKING_EPS_FRACTION = 0.01 (L88) — ray start stand-off outside a voxel cube face, as a fraction of cell size.
  • module const _VOXEL_BACKING_MAX_GEOMS = 8 (L91) — cap on backing geoms reported per cell.
  • module const _XYZ = 3 (L93) — Cartesian dimension count for a grid size / origin / half-extent triple.
  • module const _CONTACTS_CAVEAT (L98) — the robot_world_contacts==0 does NOT mean no interpenetration string emitted verbatim on every estop_ground_truth_snapshot stop line.
  • module const _CANDIDATE_CHUNK_HISTORY = 3 (L114) — candidate chunks retained (ring buffer) for predicted-horizon reconstruction.
  • module const _ESTOP_EVIDENCE_WINDOW_NS = 500_000_000 (L117) — a CollisionEvidence older than this is not attributed to the stop being snapshotted.
  • module const _DOP_VERTEX_EPS = 1e-9 (L1177) — slack (metres/determinant) for the 3x3 solves behind _dop_vertices.
  • module const _VOXEL_BACKING_MAX_LAYERS = 4 (L1468) — how many non-collidable shells one ray looks past inside a single cell before giving up.
  • grid_settles_attachment(*, source_stamp_ns: int, transparent_depth_ns: int, grid_attachment_revision: int, required_revision: int) -> bool — Does a /openral/world_voxels grid end an attachment's perception barrier? Later than the counted transparent depth frame AND OccupancyVoxels.attachment_revision (the revision whose payload/identity clearing the octomap bridge built the grid with; 0 = it certified nothing) at least the armed revision (#418 r7po_on1: the kernel stopped on the held orange 167 ms before the clear landed). Ordering only: no kernel check changes; the barrier never releases early, logs a WARN with the stamps after BARRIER_VOXEL_WARN_S (5 s wall) and keeps holding (the runner's action-applied deadline is the timeout). (L157)
  • BARRIER_VOXEL_WARN_S = 5.0 (L193) — Wall seconds the attachment barrier's cleared-grid wait may run before it logs its WARN (it still never releases early).
  • constant_scan_no_hit_ranges(*, n_beams: int, max_range_m: float) -> list[float] — Pure synthetic scan fan: every beam clamped to max_range_m ("no hit everywhere", the ray-casters' convention), the reading for an in-process digital twin with no scene to ray-cast. Used by SimSensorBridge._compute_scan_ranges's no-handles branch. (L196)
  • scan_ranges_on_wire(ranges: Sequence[float], *, max_range_m: float) -> list[float] — The LaserScan.ranges SimSensorBridge publishes: a beam at or beyond max_range_m (missed) becomes +inf (REP-117), returns pass unchanged. slam_toolbox mapped range_max beams as wall points riding with the robot and under-counted travel by ~14 %; Nav2 discards +inf. The limit is compared at float32 precision (the ray-casters clamp in float32), so a range_max_m like 5.6 that float32 rounds down still reads a missed beam as +inf. (L241)
  • next_scan_due(next_due_ns, now_ns, rate_hz) -> int | None (L212) — When the scan after one observed at now_ns is due, or None when this one is not; next_due_ns is the previous return (None before the first scan). The schedule advances by whole periods (1 / rate_hz in sim time, due 1 % early for integer-ns step rounding), so steps that do not divide the period still average the rate (12 Hz steps, 10 Hz scans: 10 Hz, not 6); it resyncs to now_ns after a pause of more than a period and after sim time went back (a reset). Schedules SimSensorBridge.publish_scan_from_frame.
  • estop_ground_truth_snapshot(model, data, *, robot_body_ids: frozenset[int], attached_body_ids: frozenset[int] = frozenset(), probe_body_ids: frozenset[int] | None = None, base_frame_body: str | None = None, joint_state: Any = None, description: Any = None, evidence_voxel: Any = None, distmax_m: float = 0.10, max_pairs: int = 32, max_calls: int = 4096) -> dict[str, object] — Pure MuJoCo ground truth for one safety stop (attached-payload or robot-world): contacts, poses, and near-miss probe pairs across robot↔world, payload↔world, payload↔robot-link, and link↔link. Contact lists are not a penetration oracle — contype/conaffinity exclusions can suppress a real contact entirely — so the near-miss probes are the adjudicator, measured via convex_geom_distance (never mujoco.mj_geomDistance, which returns confidently wrong values on some pair classes under mujoco 3.8.0). Every probe side is filtered to solid geometry only (a geom with neither contype nor conaffinity is never a real penetration) and reports its own coverage (candidate/probed pairs, certified/uncertified, noncollidable exclusions) so an absent pair reads as "looked and found nothing," not silence. description adds an adjudication_budget (mesh-vs-model slop) so a kernel OBB↔voxel distance and a probe mesh↔mesh distance can be compared fairly, widening (never narrowing) the probe window to the admissible gap; evidence_voxel adds evidence_voxel_backing (the only part of this record that reads the published map rather than MuJoCo alone) and must only be passed for evidence judged fresh. Called by SimSensorBridge._on_estop_ground_truth. (L2264)
  • kernel_checked_body_ids(model, description) -> frozenset[int] — Pure MJCF bodies for exactly the links the safety kernel collision-checks (the manifest's collision_geometry is the kernel's model, so a link with no entry is deliberately invisible). Resolved exactly via each joint's sim_joint_name, never name-mangled; empty when the manifest declares no collision geometry. Scopes the near-miss probes so a mobile base's floor contacts can't bury the arm's. Sibling of depth_cloud.robot_self_body_ids (that answers "what is the robot"; this answers "what does the kernel check"). (L903)
  • kernel_checked_link_bodies(model, description) -> dict[str, int] — Pure name-keyed form of kernel_checked_body_ids, resolving each collision_geometry link name to its MJCF body id the same exact way. Needed wherever a diagnostic must line a manifest OBB up with its MuJoCo geometry (collision_model_mesh_slop is the caller); unresolved links are reported, not guessed. (L928)
  • collision_model_mesh_slop(model, description) -> dict[str, object] — Pure measurement of how far the kernel's manifest-OBB collision model reaches beyond the real meshes per link, so a kernel distance (OBB↔voxel) and a probe distance (mesh↔mesh) can be compared fairly — the admissible gap is corner_slop(link) + voxel_half_diagonal. Returns per-link obb_half_extents_m/face_slop_m/corner_slop_m/hull_overhang_m (has_stage2_hull distinguishes "no hull" from "unmeasured") plus max_corner_slop_m; {} when the manifest declares no collision geometry, so the caller reports "no budget" rather than assuming zero. Robot side only — an attached-payload self stop also needs attached_payload_mesh_slop. (L1005)
  • _dop_vertices(dop_lo, dop_hi) -> NDArray[np.float64] — Vertices of a 26-DOP from its 26 halfspaces, by direct plane-triple enumeration (no hull-intersection library). Needed because distance-to-a-convex-set is a convex function, so its maximum over a polytope occurs at a vertex — the same reason a box's slop term is its corner, not something face-sampled.
  • _payload_model_overhang_m(prim, points) -> float — How far one payload primitive's kernel model (its DOP where one ships, else the box) reaches past the real mesh — the payload-side analogue of a link's hull_overhang_m, used by a world-voxel payload stop's budget. Deliberately the DOP and not a tighter stage-2 hull even when one ships, since the kernel falls back to the DOP whenever its hull budget caps out. inf for a degenerate refinement, so the consumer reads "no budget" rather than scoring against zero.
  • attached_payload_mesh_slop(model, data, *, attached_body_ids: frozenset[int], max_primitives: int = 16) -> dict[str, object] — Pure measurement of how far a carried payload's kernel primitives reach beyond its own meshes — the payload side of the adjudication budget an attached-payload self stop needs (that check is OBB-vs-OBB on both sides, unlike a world-voxel stop's single OBB). Calls extract_body_primitives directly so the budget can't drift from the geometry the kernel was actually handed; only box primitives can be loose (sphere/capsule primitives have no corner to overhang). Returns {"objects": {<body>: {n_primitives, n_box_primitives, corner_slop_m, ...}}, "max_corner_slop_m", "unresolved_objects", "method"}; {} when nothing is carried, so the caller reports "no budget" rather than assuming zero. (L1282)
  • voxel_backing_for_cell(model, data, cell: Mapping[str, Any], *, robot_body_ids: frozenset[int], attached_body_ids: frozenset[int], base_frame_body: str | None) -> dict[str, object] | None — The single place a cached /openral/world_voxels cell dict is unpacked into voxel_backing_record's arguments, so the in-snapshot and late-evidence call sites can't disagree about which fields (notably grid_orientation_xyzw) they pass — omitting it silently places the probe cube by the wrong axes on a rotated base. Returns None when the cell names no index. (L2217)
  • voxel_backing_record(model, data, *, voxel_index: int, grid_origin: Sequence[float], grid_resolution: float, grid_size: Sequence[int], robot_body_ids: frozenset[int], attached_body_ids: frozenset[int] = frozenset(), base_frame_body: str | None = None, grid_orientation_xyzw: Sequence[float] = (0.0, 0.0, 0.0, 1.0), rays_per_axis: int = 3) -> dict[str, object] — Pure answer to what MuJoCo geometry, if any, backs one occupancy voxel — the near-miss probes never look at /openral/world_voxels, so this is the only check of whether the map and the world agree. Decodes the kernel's b=voxel_<n> index against the live grid, lifts it to world coordinates, then classifies via ray-fan sweep as solid_world, attached_payload, self_occupancy_suspect, noncollidable_world, or unbacked, with verdict picking by adjudication order (real world geometry always explains a stop first). rays_cast/rays_hit make unbacked readable as "looked and found nothing"; an index outside the grid returns verdict: "out_of_range". (L1678)
  • attached_model_slip(model, data, *, description: Any, attached_objects: Sequence[Any]) -> list[dict[str, object]] — Pure answer to where the kernel thinks each carried payload is (forward-kinematics from attach_link + pose_in_link, fixed at the attach) versus where the simulator actually has it — a payload that slips, settles, or pivots in the gripper is then charged as collision depth against cells the real object isn't near. One record per object: object_id, attach_link, resolved, kernel_world_xyz, sim_world_xyz, slip_m, rotation_deg, body_radius_m, max_point_slip_m (translation plus the rotation's sweep at the body's radius, since slip_m alone understates a pivoting payload). An object whose link/body/pose can't be resolved reports resolved: False, never a silent zero. Emitted on every ground-truth snapshot as payload_model_slip. (L1974)
  • grid_with_origin(history: Sequence[Mapping[str, object]], origin: Sequence[float], *, tol_m: float = 1e-9) -> Mapping[str, object] | None — The cached /openral/world_voxels geometry whose published origin matches the one the kernel discloses (CollisionEvidence.world_grid_origin_m); exact where grid_current_at's stamp match is ambiguous, since two grids published within one /clock tick can be indistinguishable by stamp while naming different cells. Newest match wins. None when the kernel disclosed nothing or no cached grid matches; the caller then falls back to the stamp proxy and records which mechanism resolved it (grid_decode.decode_source). (L1912)
  • grid_current_at(history: Sequence[Mapping[str, object]], stamp_ns: int) -> Mapping[str, object] | None — The newest cached /openral/world_voxels geometry whose header stamp is at or before stamp_ns, chosen by stamp, never by arrival order: decoding a stop's cell index against whichever grid arrived last is wrong the moment the base drifts across one lattice boundary, misplacing world_xyz by a full grid resolution. None when nothing in history is old enough; the caller then falls back to the latest grid and records fallback_to_latest: true rather than papering over the gap. (L1945)
  • occupied_cell_keys(*, occupancy: Sequence[int] | Any, grid_origin: Sequence[float], grid_resolution: float, grid_size: Sequence[int], grid_orientation_xyzw: Sequence[float], base_rot: Any, base_offset: Any, max_cells: int = 2_000_000) -> tuple[frozenset[tuple[int, int, int]], bool] — Pure reduction of one published OccupancyVoxels grid to the set of world cells (keyed by floor(centre_world / resolution), not rounded or by voxel index — both are wrong once the base has moved) it marks occupied, so a later stop can ask whether its cell predates a given moment (e.g. a grasp). An occupied count above max_cells returns (frozenset(), True) rather than a partial set, since a partial set would wrongly answer "not pre-existing" for cells it never looked at. (L2071)
  • preattach_verdict(*, world_xyz: Sequence[float], resolution: float, preattach_keys: frozenset[tuple[int, int, int]] | None) -> dict[str, object] — Did the cell a stop tripped on already exist before the payload was masked? Returns {available, preexisting, within_one_cell, cell_key, preattach_cells}, or {available: False, reason} when no snapshot was taken — never a bare False, which would misread as "the cell is new." preexisting alone is not a payload-authored finding (world geometry is always pre-existing too); that requires the conjunction with voxel_backing_record's verdict being attached_payload. Consumed by SimSensorBridge._annotate_preattach. (L2159)
  • candidate_chunk_digest(*, stamp_ns: int, control_mode: int, horizon: int, n_dof: int, flat: Sequence[float], cartesian_delta_scale: Sequence[float] = (), ee_name: str = "", frame_id: str = "", rskill_id: str = "", trace_id: str = "", tick_index: int = 0, runner_session_id: int = 0) -> dict[str, object] — Pure JSON-safe digest of one openral_msgs/ActionChunk, reshaped into horizon rows of n_dof under ticks (a mismatched length is kept verbatim with shape_mismatch: true, never truncated). Records runner_session_id beside tick_index (0 = a session-less producer), since a tick number alone is ambiguous across a runner restart. The command-side record of a predicted-horizon stop — the configuration the kernel actually adjudicated is instead CollisionEvidence.joint_positions_rad, the authority. Cached per chunk by SimSensorBridge._on_candidate_action. (L2689)
  • initial_configuration_stop_record(snapshot: Mapping[str, object], *, stop_seq: int, last_action_ns: int, candidate_chunks_seen: int) -> dict[str, object] | None — Pure classifier separating a scene-initialization stop from a mid-task one: None once anything has been applied (last_action_ns != 0), else a record naming the stop as one the scene reset produced rather than one the robot was driven into — no policy, chunk, or margin change can clear it. candidate_chunks_seen is reported but doesn't gate, since a chunk the kernel rejected never reached send_action. Diagnostics only — never suppresses, delays, or alters the stop. Called by SimSensorBridge._log_initial_configuration_stop. (L2759)
  • isaac_estop_ground_truth_record(contacts: Mapping[str, Any], *, joint_state: Any = None, evidence_voxel: Mapping[str, object] | None = None, attached_object_ids: Sequence[str] = ()) -> dict[str, object] — Pure Isaac counterpart of estop_ground_truth_snapshot, built from the sidecar contacts reply (_IsaacSimSidecar.contact_ground_truth): backend: "isaacsim", sim_time_s, robot_world_contacts (one record per robot-collider/other-collider pair, min_separation_m negative = penetration), max_penetration_m, nearest_robot_world_pairs: None + nearest_unavailable_reason (PhysX has no shape-to-shape distance), contacts_caveat, robot_joint_state, evidence_voxel, attached_object_ids. No payload sections, adjudication_budget or voxel backing (MuJoCo-only). Called by SimSensorBridge._on_estop_isaac_ground_truth. (L2633)
  • class SimSensorBridge — Wires and tears down sim-sensor publishers and the MuJoCo viewer on a HAL lifecycle node, gated on the robot manifest + HAL capability. attachment_heartbeat=False (the HAL node sets it via sim_attachment_heartbeat when its vision attachment leg is on, and always under hal_mode:=real, where "nothing attached" has no evidence behind it) opens no /openral/attachment_state publisher, timer or evidence tracker at all — whatever the HAL, including one WITH the attachment API (SimAttachedHAL, the Isaac / scene-attached path, which would otherwise keep publishing its empty revision-0 set beside the vision leg, so the leg's set and grasp/place declarations would alternate on the latched topic) — so one authority publishes on it. Its staging subscriptions (/openral/attachment_state, /openral/attachment_state_applied, /openral/world_voxels) stay for a HAL with the attachment API, so the other authority's revisions are still masked and still held on the attachment barrier (tests/integration/test_hal_attachment_barrier_live.py). Owns /scan for both a live MJCF ray-cast (SimAttachedHAL) and a constant_scan_no_hit_ranges fan for the bare digital twin. (L2844) Attachment heartbeat for every sim HAL (2026-09-22): _setup_attachment_state() creates the /openral/attachment_state publisher and its 0.2 s timer for every sim HAL when attachment_heartbeat is true (the default); only the staging path (subscriptions + the MuJoCo evidence tracker) still requires the HAL's update_attached_objects / read_attached_objects API. The deploy launch enables the kernel's attached-payload check for every sim robot with capsules, and that check fails closed on a world state whose attachment_stamp_ns is still 0 — so a MujocoArmHAL twin (no attach mechanics, zero publishers) had every JOINT chunk dropped as attached_overflow on the OpenArm twin. "Nothing attached, fresh" is the exact truth for such a HAL; covered by tests/integration/test_sim_sensor_bridge_attachment_heartbeat.py. /scan: a backend that returns its lidar fan with each observation (Isaac: no MuJoCo handles, a read_scan) is published by the HAL's proprio publisher thread via publish_scan_from_frame(frame) (once per new observation, stamped like /odom, next_scan_due-scheduled in sim time); MuJoCo ray-casts on the executor thread under the scan_publish_rate_hz timer.
  • (property) idle_hold_s -> float (L3102) — The idle stepper's quiet window in seconds (the longest joint-state gap the twin produces while a skill pauses between VLA chunks). The HAL node raises the vision leg's jaw-evidence timeout to idle_hold_s + 4 joint-state periods on the idle-stepping sim twin only (twin_jaw_evidence_timeout_s; never under hal_mode:=real, whose node also builds this bridge) so the attachment heartbeat survives re-inference pauses.
  • _idle_step_tick() -> None [private] — The sim-only idle stepper's tick: holds while the lifecycle node's /openral/estop latch is set (node._estopped, the latch MobileBaseBridge also reads), so a sim HAL's physics freezes — the twin neither steps nor tracks its last ctrl, the sim clock stops — until /openral/estop_cleared, without tearing the HAL down (reads and cameras serve the frozen state); else should_idle_step decides and hal.idle_step(wall_dt_s) steps (one warning, then disabled, on an error). A real HAL never gets this timer.
  • __init__(node: Any, hal: Any, description: RobotDescription, *, viewer_enabled: bool = True, camera_rate_hz: float = 10.0, viewer_sync_rate_hz: float = 30.0, scan_rate_hz: float = 10.0, scan_n_beams: int = 360, scan_max_range_m: float = 12.0, scan_min_range_m: float = 0.05, depth_rate_hz: float = 10.0, depth_max_range_m: float = 5.0, depth_pixel_stride: int = 4, idle_hold_ms: float = 2000.0, attachment_heartbeat: bool = True, attachment_kernel_checked: bool = True, attachment_kernel_link_names: Sequence[str] | None = None, on_step: Any = None, on_attachment_perception_ready: Any = None) -> None — attachment_kernel_checked / attachment_kernel_link_names (the HAL node's params of the same names, set by the deploy launch from the kernel's own configuration): the MuJoCo attachment tracker is not armed when the kernel does not check attached payloads (nothing would acknowledge a revision); when the tracker would name links the kernel's collision model lacks, the bridge withdraws /openral/attachment_state (no empty "nothing carried" heartbeat) so the kernel fails closed, with an error log. on_step refreshes the proprio snapshot after idle sim steps. on_attachment_perception_ready releases a deferred grouped-action acknowledgement only once a newly attached payload is transparent in both a depth frame and a newer /openral/world_voxels raster.
  • setup() -> None — Activates every stream the manifest + HAL support: RGB camera + CameraInfo publishers (advertised lazily per camera on its first real frame — see _advertise_camera), the sim-only idle stepper, and the passive MuJoCo viewer (always mjCAMERA_FREE, opening pose from initial_viewer_camera; a GL/DISPLAY failure warns and continues). First hands an on-demand renderer its frame period (hal.set_frame_period_s(1 / max(camera_rate_hz, depth_rate_hz)), when the HAL has one). Idempotent per activate. (L3110)
  • publish_scan_from_frame(frame: ProprioFrame) -> None (L3853) — Called from the HAL's proprio publisher thread (never touches the simulator; the float conversion happens here, off the executor thread): publishes a new frame's scan on /scan, stamped like /odom and its TF (the node clock; a sim-time stamp can run a step ahead of /clock and need TF from the future), when next_scan_due says its slot has come (in sim time, time.monotonic_ns for a HAL with no sim clock); a frame already seen is never re-published. A frame without a scan publishes nothing (no beams are made up) and logs sim_sensor_bridge.scan_missing; a fan whose beam count differs from scan_n_beams is published as the sensor gave it, angle_increment from its own count, and logs sim_sensor_bridge.scan_beam_count_mismatch naming both counts. Both warnings are structlog, at most one per kind per _SCAN_WARN_PERIOD_NS (10 s).
  • _advertise_camera(name: str) -> Any — Creates (once) and returns the Image + camera_info publisher for one camera, on its first real rendered frame — never eagerly for the manifest's full camera list, since a manifest may declare a camera the current scene can't render and an eagerly-advertised topic would be indistinguishably silent forever. A declared camera that never yields a frame gets one warning and no topic. (L3277)
  • _publish_optical_mount(spec, sensors) -> None — Latches <mount> -> <mount>_optical_frame (BODY_TO_OPTICAL_QUAT_XYZW) on /tf_static, once per optical frame, for the mount the module's _static_optical_mount(spec, sensors, *, backend_places_depth) names: openral_core.depth_extrinsic.optical_mount of an RGB camera over the manifest's sensors (so a camera that shares_mount_with another sensor gets that sensor's child, issue #641) or of a depth sensor alone (its own mount: the depth leg stamps in depth_optical_frame_id), where the mount frame is body-convention. Not for a depth sensor's mount on a backend that places depth cameras itself (Isaac): _publish_depth_frame broadcasts that frame live, and never one that is latched (a frame has one parent). Its sim camera sits at that mount (SensorSpec.sim_placement), so raster, cloud and colour are placed where they were cast.
  • _mujoco_depth_frame(name, kwargs, model, data, stride) -> tuple[dict, clearing] — One MuJoCo depth camera as an openral_sim.depth_frames frame: the frame's single ray-cast (synthesize_depth_frame, strided raster + K/stride + the self-filter's clearing mask), the same MJCF camera's colour at that raster (_render_registered_colour), and the camera's live optical pose in base_frame (identity when no base body resolves; the static mount then carries the TF).
  • _render_registered_colour(name, model, data, camera_name, w, h, k) -> NDArray | None — The depth camera's colour rendered at its raster from the same MjData (renderer cached per model: RoboCasa rebuilds the model each reset). None (warned once, camera disabled) when K is not the square, centred pinhole the camera's fovy renders.
  • _publish_depth_frame(name, spec, frame, stamp, *, tf_stamp) -> None — Every backend's path (the MuJoCo bridge's own frames and SimAttachedHAL.read_depth_frames): one RGB-D frame → depth 32FC1 + colour rgb8 Images sharing one CameraInfo (the backend's K), all in depth_optical_frame_id(spec) and stamped stamp (the time the frame shows), plus base_frame -> <optical> on /tf stamped tf_stamp (the measured backend state time, converted to the node clock domain, not a lagging ROS /clock callback). TF is published before the raster; a current pose is never stamped as an older capture. Colour/depth size mismatch publishes depth only, warned once; an empty rgb publishes depth only; tf_stamp=None publishes no TF.
  • _frame_times() -> tuple[dict[str, int], int | None] / _frame_stamp(now, frame_time_ns, sim_now_ns) — The HAL's read_image_times() and sim_time_ns(), and frame_stamp_ns as a header stamp in the node's clock: _publish_images (each RGB image + its CameraInfo) and _publish_depth_clouds_from_obs (clouds, RGB-D frames) stamp every frame with the time it shows instead of the publish time (issue #361).
  • _colour_publishers(name) -> tuple[Publisher, Publisher] — The depth camera's colour Image + CameraInfo publishers on camera_topic(name), created once (RGB-camera QoS).
  • teardown() -> None — Cancel timers (incl. the idle-step timer), destroy publishers, close viewer. Called from on_deactivate / on_cleanup. (L3125)
  • close_viewer() -> None (L3212) — Close the MuJoCo passive viewer, if open. Idempotent, no rclpy calls; teardown and the manifest node's signal-exit hook call it.
  • _setup_estop_ground_truth() / _on_estop_ground_truth(msg) — Diagnostics only — nothing here gates, delays, or alters actuation. Gated on live MuJoCo handles or an Isaac contacts source (_contact_ground_truth_source: the wrapped env's contact_ground_truth), not attachment support, so a pre-grasp arm↔world stop still gets ground truth. Subscribes /openral/estop, /openral/candidate_action (a ring of cached candidate_chunk_digests), /openral/failure/safety (the kernel's CollisionEvidence), and the /openral/world_voxels grid geometry, then emits one sim.estop_ground_truth_snapshot line per stop plus a separate sim.estop_ground_truth_evidence line when the kernel's evidence lands late (never delayed for it, since sim state must be captured at the stop instant). Also runs _log_initial_configuration_stop, emitting sim.estop_initial_configuration when nothing has been applied yet. Without MuJoCo handles the stop goes to _on_estop_isaac_ground_truth: the same line from isaac_estop_ground_truth_record (a sidecar ROSError lands in contacts_error, never raised). Full signal table in docs/reference/telemetry.md.
  • attachment_action_ack_ready() -> bool (L5124) — Attachment transaction gate for the lifecycle node: an addition stays unacknowledged until kernel acceptance, one transparent depth frame, and the following voxel raster all land. An empty detach snapshot is immediately ready, since detach unmasks before the kernel drops the old payload.
  • reset_attachments() -> None (L4550) — Called by the HAL node's reset_episode handler after the HAL reset: rebuilds the MuJoCo evidence tracker from no contact and, when this bridge owns /openral/attachment_state, publishes an empty revision (staged as a detach, so no barrier is held). The HAL's own _reset_env clears its attached set and masked body ids, so a payload of the previous episode is neither held nor hidden from depth.
  • _on_attachment_state_applied(msg) — Applies the staged revision once the kernel accepts it, then arms the perception barrier only when the revision masks geometry not already masked (compared exactly by (object_id, evidence_ref)); a revision masking nothing new (e.g. a re-published place witness) releases the barrier immediately instead of deadlocking a successful place.
  • describes_mobile_base(description: RobotDescription) -> bool (mobile_base_bridge.py L40) — Pure predicate: does the manifest declare a planar base (base_joints)? The single answer to "does something already own odom → base_frame", so MobileBaseBridge's attach and SimSensorBridge's TF skip-guard can't drift apart; reading any other field risks a second base_link parent and a split /tf tree.
  • platform_owns_navigation(description: RobotDescription, *, hal_mode: str) -> bool (mobile_base_bridge.py L66) — ADR-0127 Decision 1, no setting: True for a real deploy (hal_mode="real") of a manifest with base_joints. Then the CLI launches no SLAM or Nav2 (and refuses a scene that enables either), the HAL node attaches no MobileBaseBridge, and the launch waits for the platform's /navigate_to_pose before re-seeding the reasoner palette.
  • class MobileBaseBridge (mobile_base_bridge.py L93) — Generic planar-mobile-base ROS wiring (sibling of SimSensorBridge): owns /odom, the odom->base_link TF, and the /cmd_vel→BODY_TWIST bridge (bypasses the safety supervisor — out of scope here). Frame ids come from RobotDescription; ManifestHALLifecycleNode attaches it in on_activate_post_subs iff the manifest declares base_joints. A ROSPerceptionStale from a real base's base_pose (no or late odometry) skips that /odom tick with a throttled warning instead of killing the executor.
  • __init__(node, hal, description, *, odom_rate_hz: float = 20.0, cmd_vel_topic: str = "/cmd_vel", proprio: Any = None) -> None — proprio: when set (sim-attached HALs), odom is published from the node's dedicated thread via publish_from_snapshot, reading the snapshot not the simulator; None (real HALs) keeps the legacy odom timer.
  • setup() -> None (mobile_base_bridge.py L136) — Create the /odom publisher + TF broadcaster + /cmd_vel subscription; the odom timer is created only when proprio is None (sim HALs publish odom off the node's thread).
  • publish_from_snapshot() -> None (mobile_base_bridge.py L190) — Dedicated-thread entry: publish one /odom + TF sample from the proprio snapshot (never the simulator). Thin alias over _publish_odom (which branches on proprio).
  • teardown() -> None (mobile_base_bridge.py L177) — Cancel the timer (if any) + destroy the publisher/subscription. Idempotent.

python/hal/src/openral_hal/proprio_snapshot.py

Decouples the control-critical publishers (odom / joint_state / TF) from the single executor thread that runs env.step + render + raycast. The sim-attached HAL node captures a frame after each step (on the executor thread, where reading the sim is safe) and a dedicated publisher thread re-emits it at ~30 Hz, so odom stays fresh (~28 Hz live, vs ~1.8 Hz starved) without ever touching MjData/GL off the executor thread (a MultiThreadedExecutor was rejected — MuJoCo's GL context is thread-affine).

  • class ProprioFrame (L40) — Frozen dataclass: one coherent proprio sample (state, base_pose, base_pose_6dof, base_twist, sim_time_ns, policy_state, scan: a float32 copy of the backend's lidar fan, or None). Plain immutable data, no live simulator handles, so it's safe to publish from a different thread than the one that stepped the sim. scan carries the 2-D lidar ranges the backend returned with this step's observation (read_scan), else None.
  • class ProprioSnapshot (L74) — Lock-guarded holder for the latest ProprioFrame: the executor thread calls set after each step, the publisher thread calls latest; the frame is swapped under the lock so a reader never sees a torn frame or reaches the HAL directly.
  • set(frame: ProprioFrame) -> None (L102) — Atomically publish frame as the latest sample (executor thread only).
  • latest() -> ProprioFrame | None (L107) — Return the most recent frame, or None before the first capture.

python/hal/src/openral_hal/_sim_attachment_evidence.py

MuJoCo attachment evidence — the counterpart of _vision_attachment_evidence.py, emitting the identical AttachedCollisionObject contract. Only the contact-force and payload-lowering halves are inventoried here; support-contact and place-region predate this section.

  • module const _LOGGER (L41) — module structlog logger.
  • module const _DEGENERATE_NORM = 1e-9 (L45) — below this a summed support normal carries no direction; used by support_contact_witness.
  • module const _SUPPORT_PROBE_GAP_M = 0.001 (L60) — beyond this gap nothing is resting on anything (the safety kernel's own attached_contact_tolerance_m).
  • module const _SUPPORT_MAX_PENETRATION_M = 0.01 (L66) — the safety kernel's support_witness_max_penetration_m; a claim past this fails the whole attachment message, so the producer never constructs one.
  • module const _SUPPORT_MAX_PATCH_RADIUS_M = 0.5 (L67) — the safety kernel's support_witness_max_patch_radius_m mirrored here.
  • module const _SUPPORT_PROBE_MAX_CALLS = 1024 (L77) — exact-distance call budget for one support attestation.
  • module const _CONTACT_FORCE_SCALE_ENV = "OPENRAL_SIM_CONTACT_FORCE_N_PER_UNIT" (L90) — ADR-0100 contact-force scale env var read by contact_force_calibration.
  • module const _CONTACT_FORCE_CALIBRATION_REF_ENV = "OPENRAL_SIM_CONTACT_FORCE_CALIBRATION_REF" (L91) — companion calibration-reference env var; both must be set for calibrated=True.
  • module const _CONTACT_FORCE_DEFAULT_SCALE = 1.0 (L92) — identity scale used when calibration env vars are unset.
  • module const _NORMAL_AGREEMENT_MIN = 0.5 (L99) — minimum cosine agreement between a surface normal and the probe's own contact direction before a support hit is attested.
  • class SimObjectMobility(str, Enum) (L102) — Kinematic mobility of a contacted non-robot MuJoCo body: FREE, HINGE, SLIDE, ARTICULATED, FIXED. Returned by classify_body_mobility.
  • subtree_region_box(model, data, *, root_body_id) -> tuple[NDArray, NDArray] | None (L200) — Sim producer for a declared place target's PlaceRegion: bounds one body's whole collision subtree by a box axis-aligned in the declared body's own frame, computed once at declaration time from the model, never inferred from the payload's position. Returns (centre_in_body_frame, half_extents), or None when the subtree has no (or degenerate) collision geometry.
  • lift_region_off_support(region_local, rotation_base_from_body, *, resolution) -> tuple[NDArray, NDArray] | None (L247) — The sim mirror of openral_core.perception_geometry.target_region_from_mask's HZ-0115-6 rule: shrinks the body-frame box's face on the body axis closest to base +z by resolution / |cos tilt|, so the box's lowest point rises exactly one voxel off the support (the target's own lowest point in sim) and the support cells stay outside the grasp region. None when the target is no taller than one voxel (the real NO_HEIGHT_ABOVE_SUPPORT). Kept local, not shared with openral_core.perception_geometry, because the real producer fits a gravity-aligned box from a cloud.
  • classify_body_mobility(model, body_id) -> SimObjectMobility (L311) — Classifies the contacted body's root as FIXED (no joint), FREE, HINGE/SLIDE (all one joint type), or ARTICULATED (mixed).
  • geom_is_polytope(model, geom) -> bool (L651) — Is conv(geom_surface_points(geom)) the geom's own solid? True for mesh/box, false otherwise: for a curved surface (e.g. a sphere sampled at its poles) that containment runs the wrong way and can under-measure a payload's real extent past a voxel's half-diagonal. Gates both lowering paths; in _clustered_box_primitives one ungroundable geom disqualifies the whole cluster.
  • geom_surface_points(model, geom) -> NDArray[np.float64] (L697) — Points lying on one geom's own surface in its local frame (mesh vertices; box corners; sphere/capsule poles); empty for geometry with no enumerable surface (plane, heightfield, SDF). Deliberately not a bounding cube, which would overstate the geometry and understate the slop both callers measure.
  • _tight_geometry_from_points(points, half_extents) -> TightCollisionGeometry | None — Refines one payload box into the kernel's staged 26-DOP + exact hull online at attach (the payload twin of tools/generate_tight_geometry.derive_tight_geometry), so that mesh ⊆ hull ⊆ DOP ⊆ box holds exactly. No convex-hull solver runs — stage 2 is a support scan over the deduplicated points. Over MAX_TIGHT_HULL_VERTICES it returns the DOP alone, disclosed by an empty vertex tuple, never a truncated hull. None only when there are fewer than four surface points to refine.
  • module const _HULL_DEDUP_CEILING = 2 * MAX_TIGHT_HULL_VERTICES (L760) — bounds the sort _tight_geometry_from_points runs when deduplicating hull vertices.
  • extract_body_primitives(model, data, *, root_body_id, object_id, max_primitives=16) -> list[AttachedCollisionPrimitive] (L1109) — Extracts conservative collision primitives for one unknown sim object: one per collision geom in the body's subtree, or _clustered_box_primitives when there are more geoms than max_primitives. Called by collision_model_mesh_slop/attached_payload_mesh_slop to keep their slop budget from drifting off the kernel's actual geometry. Raises ROSConfigError when the subtree has no collision geometry.
  • support_contact_witness(model, data, *, root_body_id, robot_body_ids, stamp_ns, support_roots=None) -> SupportContactWitness | None (L1496) — Attests one payload's bounded support contact from certified signed distances (openral_hal.convex_distance, not the solver's contact list or mj_geomDistance), so a grasped object resting on the counter it was picked from isn't indistinguishable from driving it through a wall. Only a non-free environment body counts as a support; the place phase restricts support_roots to the declared target's own subtree. None when no eligible support contact exists.
  • contact_force_calibration() -> tuple[float, bool, str | None] (L1626) — Resolves the sim contact-force calibration from OPENRAL_SIM_CONTACT_FORCE_N_PER_UNIT + OPENRAL_SIM_CONTACT_FORCE_CALIBRATION_REF; calibrated=True only when both are set and the scale parses finite and positive — a sim magnitude is a calibration knob, not a newtons claim, and a scale nobody can name must not silently arm the kernel's force gate.
  • probe_contact_force(model, data, *, payload_geoms, target_root_body, target_name, stamp_ns) -> ContactForceWitness | None (L1670) — Walks MuJoCo's solver contact list for payload↔declared-target pairs and attests the total normal load via mj_contactForce (never just the largest single contact, which understates a multi-corner rest). None is not evidence of absent contact — contype/conaffinity exclusions can suppress a pair entirely — it only means the gate does not arm; that blind spot is survivable because this check can only add a refusal, never remove one.
  • class SimAttachmentEvidenceTracker(model, description, *, stable_ticks=3, release_ticks=3, translation_tolerance_m=0.01, rotation_tolerance_rad=0.15) (L1831) — Confirms free-object grasp/release from exact MuJoCo contacts and motion; fed every physics step by SimSensorBridge. Arms one hand (_Hand) per gripper: the role: gripper joints grouped by parent_link (a fixed hand link no joint is the child of resolves to the MJCF body of that name, which must carry the jaws; absent that name, a fixed_attachments child resolves to the jaws' parent body when it hangs jointless under the parent link's sim body at the row's origin_xyz/origin_rpy within 1 mm / 1 mrad — the Panda's panda_hand = menagerie hand, #752 — via _fixed_attach_body; a gripper joint's fixed_jaw_link, which must be its parent_link, adds the attach body alone as the second contact branch — the SO-ARMs' fixed jaw, #752), plus one per sim.grippers entry driving an end_effector with no manifest joint (fingers found by qpos_addrs, attach link the manifest link whose sim body carries them, touch links the finger bodies). Each hand attaches and releases on its own jaws exactly as one gripper does; every hand needs the strictest actuated end effector's jaw count; hands may share no finger body; a payload held by one hand is never the other's candidate; hands publish in fixed order, each record with a 1/N share of the kernel's attached_max_primitives (tracking_thresholds caps) so a full set always fits; an end-effector hand's jaws are only the listed finger joints' subtrees (a jointed sibling is no jaw); an end-effector finger body without an MJCF name is refused; an unattachable payload (no MJCF name, no collision geometry) is refused for that hand alone and logged once, so other hands keep publishing; a place declaration licenses one attestation per carry with at most one attested carry at a time across hands; a candidate the other hand already holds is dropped, history included; an update that fails part-way still publishes the committed transitions next update; a grasp declaration with contact_links freezes its region only on its own hand's attach. Raises ROSConfigError for no gripper, an unresolvable hand body, or too few contact branches.
  • bind_kernel_links(kernel_link_names) -> list[str] (L2081) — Names each hand's attach/touch links as the safety kernel's collision model does: the manifest links when the kernel knows them all, else the hand's sim bodies (attach body; every body under its jaws) when it knows those — a model lowered from the MJCF (mjcf_lowering, the WidowX twin's wx250s/*). Returns the manifest links neither naming resolves; the bridge refuses to arm (and withdraws /openral/attachment_state) when non-empty. A renamed hand keeps its manifest names (_Hand.manifest_links), so a grasp declaration naming them still freezes its region; reset_attachments binds the replacement tracker the same way. The tracker refuses more hands than attached_max_primitives, and a place witness on an unattestable support is no attestation (logged), not an update abort.
  • adopt_kernel_names(twin, *, tolerance=1e-3) -> bool (L1979) — Takes the names of twin (the same robot's tracker on the kernel's own MJCF, already bound) when the scene model names bodies neither the manifest nor the kernel does (LIBERO's robosuite Panda vs a kernel lowered from menagerie): only with the same hands, the same resolvable non-gripper manifest joints (_chain_signature), and every attach body at the same pose relative to the arm's fixed mount (the first manifest joint's parent body) within 1 mm / 1 mrad at qpos0 and at four spread joint configurations, so the chains move each hand alike. Contacts stay measured on this model's bodies. SimSensorBridge._bind_attachment_tracker tries it after bind_kernel_links, at setup and episode reset; manifest joints resolve robosuite-prefixed names (_sim_joint_id).
  • (property) attach_links -> tuple[str, ...] (L2108) — Each hand's attach link, in publication order.
  • update(data, *, stamp_ns) -> list[AttachedCollisionObject] | None (L2131) — Returns a new complete attachment set (one record per holding hand, hand order) only when some hand's attachment changes (attach, detach, or a place-witness arm/disarm); None otherwise, so a heartbeat never re-arms an exemption the kernel had killed.
  • set_place_declaration(declaration: PlaceDeclaration | None) -> None (L2361) — Installs, replaces, or retracts the active place-phase declaration; resolves target_id to a MuJoCo body at install time, so an unresolvable target is refused (ROSConfigError) rather than silently no-op'd per tick.
  • place_declaration(data, *, stamp_ns) -> PlaceDeclaration | None (L2424) — The live declaration, with its region and geometry posed into the robot base frame; overwrites an incoming region/geometry it can measure and drops what it cannot, so a value a dispatcher relayed can never reach the kernel wearing this producer's authority.
  • set_grasp_declaration(declaration: GraspDeclaration | None) -> None (L2548) — The grasp mirror of set_place_declaration: resolves target_id (sim:<body>) to a MuJoCo body at install time, refusing an unresolvable one with ROSConfigError (the previous grasp state is cleared either way); None or a retracted declaration clears it. Touches nothing else in the tracker.
  • set_voxel_resolution(resolution_m: float) -> None (L2640) — Record the occupancy lattice's cell edge for the grasp region's one-voxel lift; SimSensorBridge._fill_grasp_declaration passes the last /openral/world_voxels grid's resolution. Not finite and positive → ROSConfigError.
  • grasp_declaration(data, *, stamp_ns) -> GraspDeclaration | None (L2586) — The live grasp declaration with its region measured from the target's model subtree and posed in the base frame — box only, no geometry (v1). Its lower face is lifted one voxel off the support (lift_region_off_support), so no region is published until set_voxel_resolution has been called (fail closed; an attach before that freezes the region-less state for that declaration). Re-validated against GraspDeclaration's caps (a receptacle-sized box yields region=None); an incoming region is always replaced or dropped. Re-measured at the target's live pose only until the declared object (object_id, empty = any) attaches; from that edge the region is frozen at the attach-instant measurement (its stamp_ns kept) through carry and release, so the kernel's handover rule can fire — only a new set_grasp_declaration clears the freeze. None once retracted or past timeout_s. SimSensorBridge subscribes /openral/grasp_declaration (RELIABLE + TRANSIENT_LOCAL, depth 1) only where this tracker exists and fills it onto every AttachmentState envelope without bumping the revision; a twin without the attachment API relays no declaration.
  • twin_drives_gripper(description) -> bool (L618) — Whether the MuJoCo twin can close a gripper on a payload: a sim.grippers entry, or a role: gripper joint with a sim_joint_name. SimSensorBridge withdraws /openral/attachment_state (kernel fails closed) when such a twin's tracker refuses; a twin with neither (Sawyer, UR, Rizon flange twins) keeps the empty heartbeat, which is the truth there (#752).

python/hal/src/openral_hal/_vision_attachment_evidence.py

Real-hardware attachment evidence from a segmenter mask plus wrist depth — the counterpart of _sim_attachment_evidence.py, emitting the identical AttachedCollisionObject contract so the safety kernel cannot tell the two producers apart. Every fail-closed gate is geometric; the segmenter's own confidence is recorded but never thresholded. Scoped to free objects only — vision gives geometry, not kinematic class.

  • module const _MIN_CLOUD_POINTS = 24 (L99) — minimum points a cloud needs before a PCA orientation means anything; below this clustered_obb_primitives stays axis-aligned.
  • module const _BOX_EPSILON_M = 1e-4 (L103) — padding added to every fitted box half-extent, matching the sim producer's own epsilon so neither producer emits a zero-thickness slab.
  • module const _VISION_CONFIDENCE = 0.7 (L109) — confidence stamped on an accepted vision attachment (below the sim producer's 1.0 since this one infers geometry from one partially-occluded viewpoint). Calibration point, not measured.
  • module const _FALLBACK_CONFIDENCE = 0.2 (L114) — confidence stamped on the conservative jaw_span_primitive fallback box. Calibration point, not measured.
  • class VisionGateConfig — Frozen dataclass of gate thresholds: containment_radius_m=0.12, max_payload_extents_m=(0.10, 0.25, 0.25), max_payload_volume_m3=0.004, min_depth_valid_fraction=0.30, min_depth_m=0.02, max_depth_m=1.0, view_ray_inflation_m=0.02, jaw_span_m=0.05, max_primitives=16. Every value is a chosen calibration point, not a measured constant; the extent/jaw-span caps aren't derivable from the manifest today (EndEffectorSpec has no jaw-aperture field). (L121)
  • class VisionAttachmentReport — Frozen dataclass carrying what the gates measured, for the trace: accepted, rejections ("no_candidates" / "empty_mask" / "depth_validity" / "payload_extent" / "payload_volume" / "jaw_containment" / "no_valid_depth"), depth_valid_fraction, point_count, extents_m, volume_m3, centroid_distance_m, candidate_index/candidate_count, mask_score_advisory (recorded only, never thresholded or used to select). (L190)
  • clustered_obb_primitives(points_in_link, *, object_id, max_primitives=16, inflation_m=0.0, inflation_axis_in_link=None) -> tuple[list[AttachedCollisionPrimitive], NDArray, NDArray] — Reduces a payload cloud to bounded oriented boxes, the same reduction as the sim producer's _clustered_box_primitives but split in the cloud's PCA frame so boxes orient to the object. inflation_axis_in_link pads each axis by its share of the view ray, compensating for the unobserved far side. Clouds under 24 points stay axis-aligned rather than orienting off noise. (L246)
  • palm_plane_m(tcp_in_link, palm_in_link) -> float (L336) — How far along the attach-link-origin → tool-point approach the palm plane (the jaw joint's origin) lies; 0 at or behind the origin. A held object never lies behind it: the producer drops mask points behind it (behind_palm when none are left), poses the jaw-span fallback cube centred on the tool point but no further back than the palm plane, and the bridge clips every payload there (#349). VisionAttachmentEvidenceProducer.palm_in_link is the jaw joint's origin.
  • jaw_span_primitive(*, object_id, jaw_span_m) -> AttachedCollisionPrimitive — The conservative fallback box: a cube of half-extent jaw_span_m centred on the TCP, deliberately crude so a rejected mask still leaves geometry in front of the collision checker. (L361)
  • class VisionAttachmentEvidenceProducer(description, *, gripper_joint=None, config=None) — Event-driven producer (no per-frame update, unlike the ticked sim tracker). With gripper_joint set it serves that one hand: attach_link is its parent_link, touch_links its child_link (one producer per hand on a bimanual robot). With None it serves every gripper-role joint, which must share one parent link. Raises ROSConfigError when there are none, the name is not a gripper joint, or (unnamed) they don't share one parent. (L398)
  • on_grasp(*, masks, depth_m, intrinsics, t_link_from_cam, tcp_in_link, object_id, stamp_ns, mask_scores_advisory=()) -> tuple[AttachedCollisionObject, VisionAttachmentReport] — Fits and gates one payload from the SegmentInView reply's candidate masks; among candidates clearing every gate, the largest fitted volume wins (over-approximation is the conservative error), never the model's own score. Always returns an attachment: any rejection degrades to the jaw_span_primitive fallback at low confidence, never None. An accepted mask is stamped VISION_SEGMENTATION; mass_kg/center_of_mass_m/inertia_kg_m2 stay None (vision gives geometry only). (L608)
  • on_release() -> list[AttachedCollisionObject] — Detach: an empty list, a complete attachment set meaning "nothing is held", mirroring the sim producer's release path. (L491)
  • (property) attach_link -> str (L472)
  • (property) touch_links -> tuple[str, ...] (L482) — finger links allowed to touch the payload: RobotDescription.grasp_contact_links(gripper_joints=…) of its gripper(s) — the jaws, their mimic followers and the links rigid on those.
  • (property) palm_in_link -> tuple[float, float, float] (L477) — the jaw joint's origin in the attach link (palm_plane_m).
  • (property) config -> VisionGateConfig (L487)

Not covered (see the module docstring): articulated objects, support contact, transparent/thin objects, self-occlusion, mass/CoM/inertia, deformables, multi-object grasps, and the attach trigger itself.

python/hal/src/openral_hal/_tracking_watch.py

A position-commanded joint that does not follow its command. Nothing downstream of the kernel checked that the arm moved: on the Orin cell (2026-10-16) the OpenArm drives stopped producing torque ~4 s after bringup while CAN feedback continued, and every chunk passed, every target reached the controllers, the goal ran to its deadline and the arms hung limp. Armed by the deploy launch for a real HAL (tracking_fault_window_s: 1.0; a params file may retune but never set it ≤ 0 or non-finite there — ROSConfigError); the HAL node then latches its own e-stop and raises /openral/estop on a fault (hal.tracking_fault). The node refuses a negative or non-finite window at activate and logs an error when the watch is off on a live HAL, and when the HAL exposes no last_applied_action (slot-grouped policies then run unwatched).

  • joint_row_targets(row, names, joint_order) -> dict[str, float] | None (L34) — An ungrouped JOINT_POSITION row by joint name: a full-dof row is padded and read at each owned joint's manifest index (ADR-0102), a row as long as names is compact, anything else None. The one rule the grasp trigger (VisionAttachmentBridge._row_targets) and the watch both read applied commands with.
  • class TrackingFault (L59) — Frozen dataclass: joint, target, measured, error, signed progress toward the target over the window, window_s.
  • class TrackingWatch(description, *, tolerance_rad, window_s, min_progress=0.2, tolerance_m=0.01) (L79) — Watches revolute / prismatic / continuous joints that are not role: gripper (a jaw stalled on an object is the grasp working). A joint faults when its error to the applied target stays above its tolerance (tolerance_rad; tolerance_m for prismatic) for window_s while its signed progress toward that target over the window is below min_progress of the error — a limp joint sagging away makes negative progress. A target that moves to the other side of the window's start opens a new window (reach-and-retreat is not a failure). Continuous joints are compared on the circle. A held target with no usable measurement (non-finite position, even intermittently) for a window faults with error=inf. ValueError on a non-positive or non-finite tolerance/window or progress outside (0, 1]. Replay of the real Orin runs: the tracking run stays quiet, the limp run faults at +1.0 s.
  • observe_command(action) -> None (L144) — Fold in the command the HAL applied (JOINT_POSITION, the chunk's last row; an ungrouped action or a slot group's composed last_applied_action). Any other applied command — another control mode, or a row that places nothing — supersedes the old targets and clears them (the start-pose ramp's end pose never stays the target under a Cartesian policy).
  • clear() -> None (L162) — Forget targets and windows (e-stop latched or cleared).
  • clear_command() -> None (L168) — The HAL applied a command it cannot state: forget the targets rather than judge against a guess (the _fold_applied_command contract the grasp trigger shares).
  • observe_state(names, positions, now_s) -> TrackingFault | None (L172) — Judge one measured state; the first fault, or None.
  • observe_read_failure(now_s) -> TrackingFault | None (L218) — read_state failed: a fault once reads have failed for a whole window with a target held (the HAL node calls it from its joint-state timer); a successful observe_state restarts the clock.

python/hal/src/openral_hal/_grasp_trigger.py

When to ask perception "what is in the jaws?" — a debounced state machine over the gripper joint's commanded target and measured position (no effort: the real OpenArm driver hard-codes it to 0.0). Pure: no ROS, no numpy, no clock. _vision_attachment_evidence.py is told a grasp happened; this is what tells it. Thresholds are the joint's manifest closure_calibration; an uncalibrated gripper refuses to arm.

  • class GraspEvent(str, Enum) (L95) — ATTACH (empty → loaded: segment, gate, attach), REGRASP (still loaded but the jaw re-settled materially elsewhere, so the fitted geometry is stale: segment again), DETACH (loaded → empty: publish an empty attachment set; no segmentation).
  • module const GAP_PERIODS = 4.0 (L92) — sample periods for_rate tolerates between accepted samples before a window restarts.
  • class PositionStallConfig (L116) — Frozen dataclass, robot-independent windows only, in seconds of sample time (JointState.stamp_ns) so they mean the same at any joint-state rate: consecutive_s=0.06, settle_s=0.13 (the spans 3 and 5 samples covered at 30 Hz), plus minimum sample counts consecutive_samples=3, settle_samples=5 (every window must hold on both time and count, so late ticks cannot confirm early), max_gap_s=0.1 (a longer gap between accepted samples restarts every window), min_sample_interval_s=5e-4. Calibration points.
  • for_rate(rate_hz, *, max_gap_s=None) -> PositionStallConfig [@classmethod] (L178) — The windows for a stream fed at rate_hz: only max_gap_s is rate-bound, max(0.1, GAP_PERIODS / rate_hz) (a fixed 0.1 s is one period at 10 Hz, so neither the trigger nor the heartbeat evidence ever confirmed); max_gap_s overrides it. The time windows stay (their sample-count floors already stretch them at slow rates). ROSConfigError on a non-positive / non-finite rate or a degenerate override.
  • validate() -> None (L154) — ROSConfigError on a non-finite or negative window, settle_s == 0, max_gap_s <= min_sample_interval_s, consecutive_samples < 1 or settle_samples < 2.
  • is_gap(stamp_ns, last_ns) -> bool (L211) — a sample stamped more than max_gap_s after the last accepted one; restarts the trigger's windows and the bridge's _JawEvidence run.
  • is_repeat(stamp_ns, last_ns) -> bool (L222) — a sample stamped no later than last_ns + min_sample_interval_s repeats (or predates) the last accepted one; shared by the trigger and the bridge's _JawEvidence.
  • gripper_joints(description) -> list[JointSpec] (L234) — Every role: "gripper" joint, in manifest order (one per hand on a bimanual robot). Raises ROSConfigError only on zero.
  • gripper_joint(description, joint_name=None) -> JointSpec (L260) — One gripper joint: the named one (ROSConfigError if it is not gripper-role), or with None the manifest's single one — zero or several raise.
  • class PositionStallTrigger(description, *, joint_name=None, config=None) (L301) — ATTACH when the command is within the close band (closure_calibration.command_band: close_band, else stall_gap) of closed_position, the jaw is settled (span ≤ settle_tolerance over settle_s) and sits further from closed than the command by more than closed_rest_offset + stall_gap; DETACH when, still commanded closed, that gap collapses to ≤ rest + stall_gap/2 (slip / closed on nothing), or when commanded open and the jaw opens more than stall_gap/2 past its hold; REGRASP when still stalled but stall_gap/2 from the hold. "Settled" is the span over at least settle_samples samples covering the last settle_s; every transition needs at least consecutive_samples agreeing samples spanning consecutive_s; a gap over max_gap_s restarts both. A repeated stamp (is_repeat) is dropped and counted in repeated_samples. Raises ROSConfigError on an unresolvable joint, no closure_calibration, no position sensor, a closed_position that is not an end of position_limits, or a degenerate window.
  • command(target) -> None (L445) — Fold in the jaw's commanded target (joint units); non-finite ignored. A command entering the close band (from outside it, or the first) restarts the settle history and the debounce streak (counted in close_starts), so ATTACH needs the jaw to settle after the close was commanded, never on stationary-open samples from before it (DROID deploy sim t6).
  • clear_command() -> None (L472) — Forget the command (it is unknown): no ATTACH / REGRASP / DETACH until the next command; a held payload stays held. Measuring against a stale close is how an open, stationary jaw reads as a grasp.
  • update(state) -> GraspEvent | None (L481) — Fold one snapshot in. A tick with no finite position for the joint increments missing_position_ticks and clears the settle window; a tick before any command increments uncommanded_ticks and can never attach; a repeated stamp increments repeated_samples, a gap past max_gap_s increments gap_resets and restarts every window.
  • (property) joint_name -> str (L401) — the resolved gripper joint's manifest name.
  • (property) attached -> bool (L406) — current latched grasp state.
  • (property) last_command -> float | None (L411) — the last commanded target, None before the first.
  • (property) pending_event -> GraspEvent | None — The transition the current debounce streak argues for, not yet confirmed: DETACH from the jaw's first let-go sample until update confirms it; the bridge pins a mobile base's let-go dofs on it. (L421)
  • (property) hold_position -> float | None (L416) — the jaw position latched as held at the last ATTACH/REGRASP, None while empty (a DETACH clears it); VisionAttachmentBridge reads it before update so a DETACH's GraspEvent.hold_position is the hold it released.
  • (property) thresholds -> tuple[float, float, float, float, float] (L438) — (closed_position, closed_rest_offset, stall_gap, settle_tolerance, close_band) in force (close_band = stall_gap when the manifest sets none).
  • (property) closing -> bool (L430) — the last command is within the close band (close_band, else stall_gap) of closed, the only band ATTACH reads.
  • attributes missing_position_ticks, uncommanded_ticks, repeated_samples, gap_resets (a gap past max_gap_s restarted every window), close_starts (a command entering the close band restarted them) — health counters; last_short_of_command, last_settle_spread — the last classified sample's margin to the command and the jaw's position span over the settle window (None before one). Read by VisionAttachmentBridge._log_close; no decision reads them.

python/hal/src/openral_hal/vision_attachment_bridge.py

The ROS wiring that turns _grasp_trigger events into openral_msgs/srv/SegmentInView calls, feeds the replies to VisionAttachmentEvidenceProducer, and publishes the resulting AttachmentState the safety kernel already consumes. The real-hardware, opt-in sibling of SimSensorBridge's attachment leg (the two must not both drive /openral/attachment_state) — torch-free by construction, since everything model-shaped lives behind the service in openral_perception_ros.segmenter_node.

The deferred-ack barrier. The HAL holds a grouped tick's action_applied until attached-payload perception settles; segmentation runs inside that same wait. The wait is bounded (deadline_s), never skipped (every failure path ends in the conservative jaw-span box at GRIPPER_CLOSURE, posed off the live tf2 TCP when it resolves — also on a precondition failure such as no depth frame — else off the manifest tool point, logged), and visible (every fallback logs its typed reason).

  • module const DEFAULT_SEGMENT_SERVICE (L224) ("/openral/perception/segment_in_view") — shared with segmenter_node.DEFAULT_SEGMENT_SERVICE; a unit test asserts the two halves agree.
  • module const MAX_RELEASE_CLEAR_M (L232) (0.1) — Ceiling on VisionAttachmentConfig.release_clear_m (refused above, ROSConfigError at bridge construction, i.e. at HAL activate): the deploy passes release.clear_m (0.04 m) from the tracking thresholds file, floored at the kernel's world margin + one octree cell; 0.1 m leaves headroom for a 5 cm margin over a coarse 5 cm cell. It also bounds the region payload's support-witness rise tolerance, so a params-file 0.3 cannot keep the support exemption through a 30 cm carry.
  • class VisionAttachmentConfig (L1088) — Frozen dataclass: self_filtered_cloud_topic="" (the robot self-filter's output for this camera, set by the deploy launch when the filter runs — the grasp target fit drops the robot's own points with mask_without_removed_points), camera="" (empty picks the manifest's first camera with intrinsics; only the id and its existence come from the manifest), depth_topic="" (empty → camera_topic(camera, CameraTopicKind.DEPTH_IMAGE); its header.frame_id is the optical frame tf2 is asked for), camera_info_topic=None (empty/None → camera_topic(camera, CameraTopicKind.DEPTH_CAMERA_INFO); HAL param vision_attachment_camera_info_topic; the only K ever projected through — no message, an uncalibrated one, or a size that differs from the depth raster is a typed GRIPPER_CLOSURE fallback, never the manifest's nominal K), service_name=DEFAULT_SEGMENT_SERVICE, deadline_s=0.25, tcp_frame="" (empty → the gripper joint's child_link, an approximation — no schema field carries a calibrated TCP today), jaw_tip_frames=(), object_id="grasped_payload" (suffixed :<gripper joint> per leg), evidence_timeout_s=0.5 (calibration point; how old the newest sample with a finite jaw position for every gripper may be before the attachment heartbeat stops; HAL param vision_attachment_evidence_timeout_s), evidence_run_spans_gaps=False (sim twin only, set by the HAL node from twin_jaw_evidence_timeout_s: a sample gap shorter than evidence_timeout_s does not restart the _JawEvidence run), tf_frames={} (manifest link → tf2 frame, used only for tf2 lookups; each entry must be the same rigid body, e.g. OpenArm openarm_left_link7 → openarm_left_ee_base_link; keys must be manifest links), and the pre-grasp target leg's grasp_target_enabled=False, grasp_target_rate_hz=3.0 (2-5 Hz, else ROSConfigError), grasp_target_freeze_s=None (unset = 2 × grid_max_age_s; HAL param vision_attachment_grasp_target_freeze_s, 0 = unset), grasp_target_min_cells=8, grasp_target_min_cover=0.5, grasp_target_support_search_below_m=0.15 (≤ 0.5 m), grasp_target_support_probe_margin_m=0.05 (≥ two grid cells, else a lost view), grasp_target_occluder_margin_m=0.05 (≤ 0.10 m), grasp_target_approach_m=None (the approach-armed target, off; HAL param vision_attachment_grasp_target_approach_m, 0 = off), grasp_target_margin_m=VisionAttachmentRuntime.DEFAULT_GRASP_TARGET_MARGIN_M (0.0 — no bloat unless the scene names one; the grasp-target bloat, [0, 0.05] m else ROSConfigError from GraspTargetLeg; HAL param vision_attachment_grasp_target_margin_m, 0 = unbloated; HZ-0115-32), grasp_target_premeasure=False (pre-measure object instances from head-camera segmentation before any hand arms, map-confirmed — openral_core.object_primitives, GraspTargetLeg(premeasure=True); HAL param vision_attachment_grasp_target_premeasure; prototype, issue #349) (HAL params vision_attachment_grasp_target_*; the bridge hands the last three to GraspTargetLeg; calibration points), and the release window's release_clear_m=0.04 and release_timeout_s=3.0 defaults read load_tracking_thresholds().release (clear_m, clear_timeout_s) — release_clear_m (the deploy passes the same release.clear_m the tracker and kernel use, in sim and on real; the launch refuses a value under the kernel's world-voxel margin + one voxel resolution; the default serves direct construction (tests) only — ManifestHALLifecycleNode refuses the leg with it unset; HAL param vision_attachment_release_clear_m; also the region payload's support-witness rise tolerance; at most MAX_RELEASE_CLEAR_M = 0.1 m, else ROSConfigError) and release_timeout_s (HAL param vision_attachment_release_timeout_s; calibration points; both must be positive, else ROSConfigError), grid_max_age_s=1.0 (oldest world-voxel grid the grasp-target and place-fixture legs use; the deploy passes the kernel's world_voxel_deadline_s, 1.0 s is the real cell's; the default serves direct construction (tests) only — ManifestHALLifecycleNode refuses the leg with it unset; HAL param vision_attachment_grid_max_age_s; must be positive), and mask_depth_max_skew_s=0.1 (HAL param vision_attachment_mask_depth_max_skew_s; largest |mask capture stamp - depth stamp| a SegmentInView mask is back-projected across — a same-grab ZED pair is 0, 0.1 s admits one frame of cache lag at ≥ 10 Hz; beyond it the attachment path falls back to GRIPPER_CLOSURE and the grasp-target leg takes a mask_depth_skew lost view; must be positive; calibration point). tcp_frame/jaw_tip_frames are single-gripper only and raise on a multi-gripper manifest; there the TCP is each gripper joint's origin_xyz, read without TF. deadline_s is sized off a warmed GPU segmenter call plus round trip; a CPU-only host must raise it deliberately or every grasp falls back. Place leg: place_target_enabled=False, place_target_rate_hz=2.0, place_target_freeze_s=None (= and at most 2 * grid_max_age_s), place_target_search_depth_m=0.20, place_target_extrinsic_error_m=MAX_PLANAR_ERR_M (HAL params vision_attachment_place_target_*; calibration points). publish_attachment_state=True (HAL param vision_attachment_publish_attachment_state; False when the #418 object tracker owns /openral/attachment_state in object_tracking: tracking | on — the bridge is then only the grasp trigger feeding /openral/grasp_events: no /openral/attachment_state publisher, no grasp/place-target leg, no depth/voxel/CameraInfo subscription, no SegmentInView client, no heartbeat; an ATTACH still holds the ack barrier until the tracker's next /openral/attachment_state revision (the bridge subscribes to it, _hold_for_tracker / _on_tracker_attachment_state), released past deadline_s with a warning as a segmentation would be; covered by tests/unit/test_vision_attachment_bridge.py::test_with_the_tracker_owning_attachment_state_an_attach_is_only_an_event and ::test_a_tracker_owned_attach_holds_the_ack_until_the_trackers_next_revision).
  • class SegmentOutcome (L1315) — Frozen (use_masks: bool, reason: str).
  • resolve_segment_outcome(*, timed_out, ok, failure_reason, mask_count) -> SegmentOutcome (L1329) — Pure decision for one round trip: a deadline miss wins as ROSDeadlineMissed:; ok=False uses the server's typed failure_reason (or a ROSPerceptionStale: default); ok=True with zero masks is also ROSPerceptionStale:. No input combination yields an unexplained fallback.
  • build_segment_request(*, stamp_ns, camera, t_link_from_cam, tcp_in_link, negatives_in_link=()) -> SegmentInView.Request (L1448) — The request the bridge sends: frame_id="" (the segmenter's "already in my optical frame") with the TCP and jaw-tip prompts moved into the optical frame by inv(t_link_from_cam), so the segmenter never re-resolves a link its TF tree may lack. Precondition: the segmenter's RGB is registered to the depth stream (true for the ZED rgb/color/rect / depth/depth_registered pair).
  • decode_mono8_mask(data, *, height, width) -> NDArray[np.bool_] (L1378) — Reader half of segmenter_node.mono8_bytes_from_mask; any non-zero pixel is set. Raises ROSConfigError on a length mismatch.
  • mask_depth_skew_reason(mask_stamps_ns, depth_stamp_ns, *, max_skew_s) -> str (L1408) — ROSPerceptionStale: … when any mask's capture stamp is more than max_skew_s from the depth frame it would be back-projected through, else "". Applied by the bridge's _on_reply (→ GRIPPER_CLOSURE fallback, reason logged) and the grasp-target leg (→ mask_depth_skew lost view).
  • mask_stamps_ns(masks) -> list[int] (L1443) — Each sensor_msgs/Image mask's header.stamp in ns (the segmenter copies the RGB frame's capture stamp).
  • class VisionAttachmentBridge(node, description, *, on_perception_ready=None, config=None, gate_config=None, trigger_config=None, hal_mode="real") (L1494) — trigger_config is one PositionStallConfig (debounce) for every hand and the heartbeat evidence; None derives it from the manifest's control_rate_hz (PositionStallConfig.for_rate, the 30 Hz-tuned defaults when undeclared) — the HAL node passes one derived from its own joint-state rate; the thresholds are each gripper joint's closure_calibration (an uncalibrated gripper is a ROSConfigError). One leg (private _GripperLeg: PositionStallTrigger, producer, TCP, current attachment, in-flight request, deadline timer, generation, region_spent, support_anchor — (frame, ATTACH origin, rise tol, slide tol), regrasp_hold: AttachedCollisionObject | None — the region payload a REGRASP began on, kept when its segmentation is rejected, HZ-0115-34) per role: gripper joint; every publish carries the union of the legs' attachments. __init__ creates no ROS entities. Owns the depth and depth-CameraInfo subscriptions (sensor-data QoS), tf2 listener, SegmentInView client and the /openral/attachment_state publisher (RELIABLE/TRANSIENT_LOCAL, matching the sim bridge). Raises ROSConfigError at construction when the manifest can't support the producer or the trigger. setup() seeds the revision from the node clock (host wall time on real) so a re-activate never moves it backwards (+1 per event; nothing persisted), and starts a 0.2 s heartbeat that republishes the union at the current revision with a fresh stamp — only while jaw-position evidence is live (private _JawEvidence: every gripper reported a finite position within evidence_timeout_s, in an unbroken run of new — not repeated-stamp — samples spanning PositionStallConfig.consecutive_s and at least consecutive_samples of them, re-earned after a monotonic timeout or a sample-time gap over max_gap_s — over evidence_timeout_s instead with evidence_run_spans_gaps, the twin), no grasp is being resolved, and every trigger agrees with its leg's attachment; otherwise it is withheld (logged once per transition) so the kernel's snapshot ages into a drop rather than a stale "nothing attached". Back-projection runs in the cached depth frame's header.frame_id (empty → typed ROSPerceptionStale fallback; logged once at info when it differs from the manifest's frame_id), through the live CameraInfo intrinsics, with masks resampled nearest-neighbour onto the depth raster only when the aspect agrees within 1e-3 (else a typed ROSConfigError fallback). With grasp_target_enabled it owns a _grasp_target_leg.GraspTargetLeg and every publication (event and heartbeat) carries its grasp_declaration_valid / grasp_declaration; an ATTACH on a leg whose jaw link (_GripperLeg.jaw_link, the gripper joint's child_link) the declaration names stops re-measurement, and — when the envelope (TTL/expiry applied) still holds a region and the jaw is at it (jaw_at) — attaches that region — closed over the map cells it touches, the box the kernel latched (GraspTargetLeg.kernel_region, Isaac i50; tight vs closed half-extents logged once) — as the payload (region_attachment, private _region_payload) without a SegmentInView call (design §2.2 "Handover") — once per leg per measured region (region_spent = (target_id, region.stamp_ns)), handed to GraspTargetLeg.on_attach with the region it was built from; a segmented ATTACH (_finish) goes through GraspTargetLeg.on_attach(region=None), which hands the region over only for a payload on it; a REGRASP, or a later ATTACH offered the same region, segments; otherwise it segments, logging why the region was not used. With place_target_enabled it owns a _place_target_leg.PlaceTargetLeg: every publication carries its place_declaration_valid / place_declaration (dispatch's goal-scope one — the leg never declares on its own — with the slab measured under the carried payload as region) and the attachment set passes through PlaceTargetLeg.decorate (the map-support proximity witness); observe_joint_state feeds PlaceTargetLeg.on_joint_state. A DETACH opens that leg's ReleaseWindow (the payload stays published, frozen on the base link) instead of dropping it; the heartbeat polls every window first and publishes at a fresh revision when one closes. Every publish at a fresh revision whose set lost or replaced an object, or is empty, first calls GraspTargetLeg.on_attachment_changed (emptied passed: a mid-grasp hand's identity — never its region — is kept across a change that leaves the set non-empty), so that very snapshot's envelope already names the other hand's fresh identity with no pre-change region (the kernel retires an armed declaration at every detach edge, HZ-0115-3). Every DETACH (also one that finds nothing latched) and every barrier release re-checks the hand's pick (GraspTargetLeg.on_hand_settled). Threading: one re-entrant bridge lock (_lock, replacing the former publish and release locks) serializes every entry point that reads or mutates leg, tracker or attachment state — observe_joint_state / observe_command / clear_command / attachment_action_ack_ready / missing_position_ticks, the heartbeat and release poll, every publish, the segmentation reply/deadline commits, teardown, and the producer legs' ticks, replies, deadlines and declaration callbacks (the legs alias it). Order: bridge lock → GraspTargetTracker's lock, never the reverse. Slow pure work runs outside it and commits only under an unchanged generation: a reply's mask decode + back-projection (_finish, GraspTargetLeg._measure) and the grasp leg's column scan (GraspTargetLeg._seed); tf2 lookups (latest, no timeout) run under it. A malformed SegmentInView reply (mask bytes vs shape, a bad field) resolves like the deadline — the GRIPPER_CLOSURE box, the barrier released — never an exception out of the executor. The bridge owns the ONE /openral/world_voxels subscription (_on_voxels, the kernel's RELIABLE/VOLATILE/KEEP_LAST 1, created when either producer leg is enabled): each grid is decoded once into _grid (lattice, source_stamp ns, receive time), shared by both legs, its whole-grid occupied-cell scan deferred to first use and cached on the VoxelLattice. Real hardware runs every caller on the executor's one thread, so behaviour there is unchanged. Covered by tests/unit/test_grasp_target_leg.py::test_every_bridge_and_leg_entry_point_is_serialized and ::test_the_lock_order_is_bridge_then_tracker_never_the_reverse. Construction refuses a base_frame the kernel's collision FK can move (_release_base_link): it must be the kinematic tree's root or below it only through fixed edges, or on a mobile manipulator also through the planar base_joints — station mode, enforced sim-only (hal_mode other than "sim" is a ROSConfigError; the lifecycle node passes its own; Safety-WG review and hazard-log row owed for hardware). On a mobile base the planar dofs are read from the joint states (_base_dofs): a DETACH's window takes the dofs at the jaw's let-go sample (_GripperLeg.let_go_base, the first sample of the DETACH debounce, PositionStallTrigger.pending_event) as its reference and is not opened when they are unknown or already moved; every joint-state sample then runs _check_base_motion, which on the first sample past BASE_STILL_M / BASE_STILL_RAD (or with the dofs unknown) closes the window (reason=base_moved) and publishes at a fresh revision, retires a region payload's support witness (_GripperLeg.support_base, the dofs at ATTACH) and retracts the grasp leg's held, not handed-over region (GraspTargetLeg.on_base_moved) — all three live in frames that ride the base. Covered live by tests/integration/test_vision_attachment_heartbeat_live.py, tests/integration/test_vision_attachment_optical_frame_live.py, tests/integration/test_grasp_target_leg_live.py and tests/integration/test_vision_attachment_release_window_live.py.
  • setup() -> None (L1662) — Create the ROS entities, including the /openral/failure/hal FailureBusPublisher for KIND_GRASP_OUTCOME (issue #353).
  • teardown() -> None (L1796) — Destroy the ROS entities. Idempotent and always reopens the barrier, so a mid-flight deactivate can never leave the node deferring an acknowledgement forever.
  • tf_frame(link) -> str (L1901) — The tf2 frame a manifest link is looked up as (tf_frames, else the link itself). Applied to the attach link and to the leg's TCP frame alike (the SO-101's logical moving_jaw → jaw).
  • jaw_point(jaw_link, frame) -> tuple[float, float, float] | None (L2979) — Where the hand whose jaw link is jaw_link is, in tf2 frame: the leg's attach link through tf2 (tf_frames-mapped) composed with its TCP — the attachment prompt's own point, never a tf lookup of the jaw link (the OpenArm's openarm_<side>_finger_pair is a manifest-only link). None for a link no leg owns or a missing transform. Used by the grasp-target leg's occlusion gate.
  • jaw_at(jaw_link, region, *, reach_m) -> tuple[bool, str] (L3006) — Whether the hand whose jaw link is jaw_link is at the held region, with the measure as log text: its TCP or its closing midpoint within region grown by reach_m (separating-axis gap of the point on the region's axes). The closing midpoint is the mean centre of jaw_link's manifest collision primitives (bounded boxes, private _link_boxes — shared with ReleaseWindow.open) posed by the attach link's tf2 pose · gripper joint origin · _joint_motion(q) at the last read jaw angle — between the fingers; never a box overlap, which on the OpenArm's opening-spanning finger_pair box (half 0.029 × 0.071 × 0.081 m) accepted a neighbour ~7 cm beside the jaw (PR #346 review). Unknown angle / no geometry / no tf2 → the TCP alone / not at it, said in the measure. The ATTACH test of _region_payload and GraspTargetLeg.on_attach (segmented payload); the TCP may be the finger hinge (OpenArm), a finger length above what the jaws close on (Isaac i41: midpoint 13.5 mm off the can, hinge 9 cm).
  • _on_kept_cloud(msg) -> None (L3102) — Caches the self-filter's PointCloud2 (skip_nans, x/y/z) by capture stamp and frame, the last 8; the subscription exists only with self_filtered_cloud_topic set and is destroyed (cache cleared) by teardown.
  • kept_points(stamp_ns, frame) -> NDArray[np.float64] | None (L3110) — The robot self-filter's kept points for the capture nearest stamp_ns (within mask_depth_max_skew_s; clouds are best-effort and some are lost, and a neighbouring capture can only remove more mask pixels; last 8 clouds on self_filtered_cloud_topic), in frame; None without that capture or its tf2 — the grasp target leg then refuses the capture as the lost view unfiltered.
  • (property) gripper_joint_names -> tuple[str, ...] (L1913) — one leg per name, manifest order.
  • attachment_action_ack_ready() -> bool (L1844) — True only when no leg is pending. The same shape SimSensorBridge exposes, so ManifestHALLifecycleNode's deferred-ack path treats both identically.
  • observe_joint_state(state) -> None (L1920) — Called from _publish_joint_state with the same typed snapshot the HAL just read (no second source of truth). Fed to every leg (and to PlaceTargetLeg.on_joint_state when that leg is on); also caches every joint position by name (the jaw angles for the release test, a mobile base's planar dofs for _check_base_motion, run on every sample). DETACH moves that leg's attachment into a ReleaseWindow (no tf2 hand pose → dropped at once, logged) and republishes; ATTACH/REGRASP closes an open window (reason=attach), closes the barrier for that leg and dispatches one bounded request. Every event first supersedes the leg's in-flight request (private _supersede: generation +1, deadline timer cancelled and destroyed, future dropped then cancelled); replies and deadlines carry their generation and a stale one is dropped, so a DETACH in flight resolves to no attachment and releases the barrier. Every event is also published first on /openral/grasp_events (openral_msgs/GraspEvent, RELIABLE/VOLATILE/KEEP_LAST 10, issue #418, private _publish_grasp_event; the publisher is created in setup(), always on): kind, gripper_joint, hand_link (the producer's attach link, the gripper joint's parent), jaw_measured / jaw_commanded / hold_position (NaN when unknown) and stamp = the confirming joint-state sample's stamp (the sim clock in sim, never the node clock). Covered by tests/unit/test_vision_attachment_bridge.py::test_grasp_events_carry_what_the_trigger_computed.
  • _log_close(leg, event) -> None (L2125) — Per leg, from observe_joint_state: one line when a close starts (command within stall_gap of closed, jaws empty) and one at its outcome — the ATTACH, or the command leaving that band without one — with that close's gap_resets / repeated_samples and the trigger's last short_of_command / settle spread. The outcome is handed to _report_outcome; no threshold or decision reads the counters.
  • _report_outcome(leg, *, attached) -> None (L2159) — Issue #353: FailureTrigger KIND_GRASP_OUTCOME (GraspOutcomeEvidence) on /openral/failure/hal per close outcome, through a FailureBusPublisher(node, FailureSource.HAL) with no rate limit at any severity (at most one event per close, and a suppressed miss or recovery would leave the reasoner's reflection wrong for good) created in setup() (always, also with publish_attachment_state off) and destroyed in teardown(). A close that ended without an ATTACH is a miss: the leg's run (_GripperLeg.misses / miss_target) is per target — a miss on a different declared target (or an undeclared one after a declared one) restarts it at 1. SEVERITY_FAIL when the live grasp declaration (GraspTargetTracker.envelope) names this leg's jaw link — carrying its target_id, region is not None, rskill_id and trace_id — else SEVERITY_WARN (an undeclared close is buffered and wakes no reasoner tick; with grasp_target_enabled off every miss is undeclared). An ATTACH ends this leg's run and every other leg's run on the same declared target ("try the other hand" succeeded), each one attach at SEVERITY_INFO with the run it ended; an ATTACH that ends no run publishes nothing. Evidence only — nothing retries, re-opens or plans (Layer 0 has no task knowledge). Each outcome is also logged with its severity and whether it was published (private _publish_outcome). Covered live by tests/integration/test_grasp_outcome_live.py.
  • observe_command(action) -> None (L2252) — Called by _on_safe_action with the command the HAL applied (called by HALLifecycleNodeBase._fold_applied_command from _on_safe_action: an ungrouped action as sent; for an ADR-0102 slot group the HAL's last_applied_action — the composed full-dof action — once its last_committed_tick/_session match the slot's, a slot that only staged changes nothing; a committed group whose command is unknown — last_applied_action is None, or the HAL has none, logged once — calls clear_command instead, never keeping the old command); the last row (the trajectory goal) is the command. The bridge stages no slots: a slot (tick_group_size > 1) handed to it is ignored and logged once. An ungrouped JOINT_POSITION row: full dof → padded, read at each owned joint's manifest index; as long as its joint_names → compact, positional; any other length → logged once, ignored. Other modes leave every leg's last command untouched.
  • clear_command() -> None (L2292) — PositionStallTrigger.clear_command on every leg: the HAL applied a command nobody can read.
  • (property) missing_position_ticks -> int (L2327) — The legs' missing/non-finite jaw-position counters, summed.
  • _retire_lifted_supports() -> None [private] (L2856) — From observe_joint_state, throttled to the place leg's 20 Hz witness period: drops a region payload's witness for good (same object and stamp, so the kernel's (object, support, stamp) key never re-arms) once the payload frame, in the support plane's frame (z up), rose more than max(resolution, extrinsic_error_m, release_clear_m) (the kernel's world margin plus a cell: the payload's lower face rests on the support top; release_clear_m capped at MAX_RELEASE_CLEAR_M) or moved horizontally more than max(resolution, extrinsic_error_m) (the margin buys nothing sideways) from its ATTACH pose (_GripperLeg.support_anchor), or tf2 cannot place it; sinking keeps it (same plane, the kernel bounds the penetration) — the kernel's own liveness reads the map, and the octomap bridge withholds the witness band, which rides with the payload over the carried object's own lowest cells. Republishes at the current revision while the heartbeat is open.
  • clip_payload_behind_tool_point(obj, tcp_in_link) -> AttachedCollisionObject (L539) — Every box primitive of obj clipped so nothing lies behind the tool point along the approach (an axis within 30°, front face kept); other shapes and tcp_in_link=None unchanged. The bridge applies it to every segmented / fallback payload (#349: a mask that bled into the hand put a box against the carrying wrist).
  • region_attachment(declaration, *, attach_link, touch_links, t_link_from_region, stamp_ns, support_z=None, extrinsic_error_m=MAX_PLANAR_ERR_M, tcp_in_link=None, inner_region=None) -> AttachedCollisionObject (L621) — The declaration's latched region as one box primitive posed in the attach link; given inner_region (the measured, unpadded region), it rides as the box's stage-2 tight_geometry (clipped like the box, clamped inside it) so the kernel checks the payload against the robot's own links as the measured box; given tcp_in_link, a box axis within 30° of the approach is shortened so nothing lies behind the tool point (#349: the margin's top bloat reached the carrying wrist); object_id = the declaration's object_id (the kernel handover's match key) or its target_id; AttachmentEvidenceKind.GRASP_TARGET_REGION, confidence 0.7. ROSConfigError without a region. Given support_z (the support top the grasp-target leg measured under exactly this region, GraspTargetLeg.measured_support), the payload carries the ADR-0092 D6 SupportContactWitness on that plane (_place_target_leg.plane_witness, support_id="map_support_under:<target_id>", stamped at the ATTACH, patch = the published box's horizontal footprint) — Isaac i42's payload, still on its table, was stopped 90 ms after the handover; None attests nothing. The bridge passes the region's cell closure (GraspTargetLeg.kernel_region), so the target's own boundary cells are embedded residue at the kernel's attach-time snapshot (Isaac i50).
  • box_gap_lower_bound_m — moved to openral_core.kinematics (issue #418); imported and re-exported here. The release window's separation test.
  • freeze_released_attachment — moved to openral_core.geometry (re-imported here; the object tracker freezes its released payloads with it too).
  • primitive_poses(obj, t_frame_from_link) -> list[NDArray] (L762) — frame <- primitive (4, 4) for each primitive of an AttachedCollisionObject, given frame <- attach link; shared by ReleaseWindow.clearance_m (the frozen record, link = base), GraspTargetLeg.on_attach's segmented-payload test, and _place_target_leg (payload_witness, and PlaceTargetLeg's posed published payloads each tick; the old private _posed_primitives copy was removed).
  • _edge_chain — alias of openral_core.kinematics.edge_chain (moved, issue #418); the release window's FK.
  • module const BASE_STILL_M (L779) (0.01) — How far (m) a mobile base's planar dofs may move from a reference before what was frozen or measured in base_frame is wrong (base_displaced); calibration point.
  • base_displaced(reference, now, prismatic) -> bool — openral_core.geometry.base_displaced at BASE_STILL_M / BASE_STILL_RAD: whether a mobile base's base_joints positions left reference; None on either side counts as moved. (L783)
  • base_prismatic — re-exported from openral_core.geometry.base_prismatic (see docs/methods/00-core-schemas.md).
  • module const BASE_STILL_RAD (L780) (0.01) — The same bound in yaw (rad): 1 cm at a 1 m reach; calibration point.
  • class ReleaseWindow (L805) — Frozen dataclass (record, opened_s, hand_link, hand_boxes, jaws, urdf_curves, base_dofs=None, base_prismatic=()) (urdf_curves: each curved jaw joint's urdf_curve, applied before posing a jaw, #533; base_dofs: a mobile base's base_joints positions at the jaw's let-go, None on a fixed base; open(..., now_s, stamp_ns, base_dofs=None) stamps the frozen record at the DETACH sample, never before the held one) — one leg's released payload (design note §2.3 "Release").
  • open(description, held, *, base_link, t_base_from_link, now_s, base_dofs=None) -> ReleaseWindow (L853) — Freeze held and collect the hand's and every exempted touch link's manifest collision primitives (bounded as boxes), each with its edge chain from the hand (_edge_chain: jaw joints, MimicJoint followers, fixed_attachments rows — the Robotiq's bars and the inner fingers below them).
  • clearance_m(t_base_from_hand, positions) -> float | None (L923) — Smallest box_gap_lower_bound_m over (exempted link primitive, payload primitive); each touch link posed down its chain, origin · joint motion(q) per moving edge (a mimic follower at value_at of its leader's angle), origin per fixed one. None when a jaw angle is unknown or a link is off the hand's subtree — never "clear".
  • close_reason(*, now_s, clearance_m, clear_m, timeout_s) -> str (L976) — "timeout", "separation" (strictly > clear_m), or "".
  • base_moved(base_dofs) -> bool (L906) — False on a fixed base; on a mobile one base_displaced from the let-go dofs (unknown is never still), judged by the bridge on every joint-state sample: the record is frozen in base_frame, which rides the base while the released object stays in the world, so the bridge drops it and the object is again voxels the kernel avoids.
  • _release_base_link(description, *, hal_mode) -> str (L1009) — base_frame, proven a link the kernel's collision FK never moves: the root of joints + fixed attachments, or reached from it only through fixed edges (fixed joints, fixed_attachments: REP-105 base_link under base_footprint_joint, as the kernel's link_static_ accepts) and the manifest's base_joints (the kernel's collision_base_dofs, zeroed before its FK; the OpenAMRobot 2.0's base_footprint). A base_frame that is no joint's parent, one below any other joint, a cyclic walk, or a walk through base_joints with hal_mode other than "sim" is a ROSConfigError.
  • _tree_links(description) -> tuple[set[str], set[str]] (L1000) — (parents, children) of every joint and fixed attachment; also the tf_frames key check.
  • bounding_half_extents — moved to openral_core.kinematics (issue #418); re-exported here for the grasp leg's HZ-0115-11 guard.
  • _xyz_rpy_matrix — alias of openral_core.kinematics.transform_from_xyz_rpy (moved, issue #418).
  • _joint_motion — alias of openral_core.kinematics.joint_motion (moved, issue #418).

python/hal/src/openral_hal/_grasp_target_leg.py

The pre-grasp target producer (design note docs/reference/real-pick-place-design.md §2.2), owned by VisionAttachmentBridge (single /openral/attachment_state authority), default off. Subscribes /openral/grasp_declaration (RELIABLE + TRANSIENT_LOCAL, depth 1) and reads the bridge's one shared /openral/world_voxels grid (VisionAttachmentBridge._on_voxels); at grasp_target_rate_hz measures the support plane from the map (support_top_from_voxels over search_column(box, below_m=support_search_below_m), ring probe support_probe_margin_m around the target's footprint, counted on the column grown by that margin + one cell — never the box's bottom face, a lifted bbox min-z that can sit below the table top; none is a no_support contradiction), seeds from the occupied cells of that column above it (whose lowest cell must sit within one voxel + one of tolerance of the support, else a not_on_support contradiction — a bench under the shelf board the target stands on; the mask fit refuses the same way when the masked cloud ends > 2 voxels above the support — a target stacked on another object), sends the seed as the single positive SegmentInView point (optical frame, no negatives, the leg's own deadline), fits target_region_from_mask on the depth frame the request was made against, cross-checks region_covers_occupied and gates track_region at one voxel. Contradicting evidence (no_support, not_on_support, ambiguous, caps, no_height_above_support, map_disagrees on any re-fit the map does not cover, target_moved on a re-fit reaching outside the held region grown by one voxel, unoccluded_refit on one shrunk inside it with no declared contact link near, frame/calibration mismatch) retracts at once; a lost view (no seed cells, seed off-image, no mask, a mask more than mask_depth_max_skew_s from its depth frame (mask_depth_skew), deadline, too_few_points, stale or missing grid/depth/TF/CameraInfo, hand_at_target — a fit refused outright with a region held and the hand over it (_hand_over_target: the jaw's hand point over the held footprint up to approach_m above its top, the measure occluded_refit uses too) — and partial_fit — a fit passing every other gate whose kernel (cell-closed) region leaves an occupied cell of the target's map component outside (occupied_touching_outside: more than a voxel above the measured support, touching the region's cells) and that the map cannot complete (map_completed_region inside the armed search column refused: the component touches the column's edge, exceeds the caps or leaves another body in the box; raised only where the fit would be accepted, never re-classing another refusal; a fit the map does complete is held, tracked, handed over and published as the completed box, Isaac i45) — and occluded_refit — a map-covered re-fit failing the tracking gate but inside the held region grown by one voxel while a declared contact link's hand point (VisionAttachmentBridge.jaw_point: its leg's TCP via the attach link, since jaw links such as OpenArm's finger_pair are not tf frames) is within one voxel + occluder_margin_m of it, the robot's own hand occluding part of the target; it never replaces the held region) freezes the last accepted region for grasp_target_freeze_s from its stamp_ns (the older of the depth stamp and the grid's source_stamp, so a stalled octomap whose bridge republishes a fresh header.stamp ages the region out), then retracts. Each transition logged once. A grid received longer than grid_max_age_s ago (the deploy's kernel voxel deadline, grid_stale), with no source_stamp (grid_source_unknown) or whose source_stamp is older than the freeze (grid_source_stale) is not used — lost views; the freeze defaults to twice grid_max_age_s and may not exceed it (the kernel's grasp_region_max_age_s = 2 × its voxel deadline). Approach-armed target (approach_m, default off): a live declaration with no search_box (the runner's goal-scope one, or a named one without a box) is measured where ONE hand approaches — each tick the hands (openral_core.gripper_hands) whose links the declaration names are located (jaw_point), approach_box around each; a hand with ≥ grasp_target_min_cells occupied cells in its box above the box's lowest occupied layer (approach_cell_count: the table under the hand is not a target) and holding nothing (no payload, release window or segmentation on its legs) is approaching; exactly one arms target_id="approach:<first link>:<n>" (n the tracker's pick counter, seeded from the wall clock at construction — GraspTargetTracker(first_pick=None) — and advanced per completed pick, so a re-activated HAL never reuses an identity), contact_links = that hand, the box as search_box, the goal's attribution/stamp/timeout; two at once arm none; the box follows the TCP; the hand leaving retracts at once (approach_ended) — except the armed hand while its legs hold or segment (its ATTACH resolves the arming). A grasp-leg request in flight when the tracker's generation moves (handover, re-arm, retraction, declaration change) is discarded on reply or deadline. A retracted arming (before any handover) re-arms for that hand only once its box centre moved more than one voxel or one freeze window elapsed (no arm-refuse-re-arm flood), under the same identity — except a hand that left the approach distance and was then seen away (located, its box off the last target's column) continuously for a freeze window, which arms under a fresh identity (liveness after a kernel grid_frame_changed / attachment_rejected retirement, which the producer cannot see). Every publish whose attachment set lost or replaced an object, or is empty, first drops every pre-handover arming's region and re-arms it under a fresh identity, accepting only a region measured after the change (on_attachment_changed; the kernel retires an armed declaration at every detach edge) — except that a hand mid-grasp (an ATTACH being resolved: a segmentation in flight or jaws loaded with nothing latched, GraspTargetLeg._resolving; a carried payload or release window is not mid-grasp) keeps its identity across a change that leaves the set non-empty, though still not its region, so its ATTACH is handed over with no region (fail closed); an emptying change refreshes it regardless. Handover is per hand: only an ATTACH on the armed hand (or a named search_box declaration's link) hands over, and only an ATTACH on what was measured (GraspTargetLeg.on_attach) hands the region over — else attach_off_target (handed over with no region; also when confirm raises). Multi-pick per goal: nothing arms while a hand is handed over; the bridge's DETACH (GraspTargetLeg.on_detach, with the release window's frozen record) drops that hand's region at once and keeps the handover (GraspTargetTracker.on_release); once the hand's legs hold nothing — re-checked on the DETACH, the window's close and every barrier release (on_hand_settled), never polled — the pick completes (on_pick_complete): the counter advances and the hand re-arms behind the backoff, but not until the column its next measurement would search (search_column of its approach box, support_search_below_m) clears the payload it just released by more than one voxel (_near_spent: box_gap_lower_bound_m against each primitive's bounding_half_extents box; no record = no re-arm for the rest of the goal; HZ-0115-11). A guarded hand is not a candidate: it does not count toward "two hands at once" (HZ-0115-12 is the kernel's one-hand rule). The release poll and a re-ATTACH are serialized by the bridge's one lock and a loaded trigger counts as holding, so the poll racing a re-ATTACH never completes the live regrasp's pick in either ordering. The kernel retires every pick's identity at its release and never re-arms one (HZ-0115-3). A named declaration stays handed over after its pick. A named search_box wins. Threading: every leg entry point (tick, reply, deadline, declaration, teardown) and bridge hook runs under the bridge's one re-entrant lock (the bridge's ATTACH runs on the HAL's proprio thread); the tracker's own RLock nests inside it. Only pure work on a snapshot runs outside — the tick's column scan (_seed) and the reply's decode/back-projection/gates (_measure, given the grid, hand points and held region read under the lock) — and is committed under the lock only under the snapshotted tracker generation; teardown sets a torn-down flag under the lock that _tick / _on_deadline check, so no request or deadline timer outlives it.

  • class GraspTargetTracker(*, freeze_s, log, first_pick=None) (L380) — Pure state machine on a caller-supplied ROS-clock now_ns; thread-safe (every method under its own re-entrant lock, which in the HAL always nests inside the vision bridge's lock). first_pick seeds the pick counter in approach:<link>:<n>; None seeds it from time.time_ns() so a re-activated HAL never re-mints a retired identity.
  • on_declaration(declaration) -> None (L536) — active=False clears; a new (target_id, stamp_ns) resets the region; the latched copy again is a no-op.
  • rebase(resolve) -> None (L570) — Re-expresses dispatch's search_box / workspace_box through resolve(field, box) from the boxes as declared (never compounding); identity, generation and region kept. The leg passes rebase_box into the grid frame every tick, with tf2 at the grid's source_stamp (VisionAttachmentBridge._lookup(stamp_ns=)), so the box sits where the base was when the map was built; no tf2 at that time leaves it unresolved (fail closed), logged once per field and state.
  • wants_approach(*, now_ns) -> bool (L601) — Approach detection should run: a live declaration with no search_box, not handed over.
  • on_approach(near, *, now_ns, move_m, holding=(), generation=None, located=None) -> None (L612) — Given generation (the tick's), ignored when the tracker moved on since (a pick completed on the HAL's thread). near = (hand links, approach box) per approaching hand this tick; only hands the declaration names count. Holds one hand: arms on exactly one, follows its box, retracts at once (approach_ended) when it leaves — unless it is in holding (legs holding, releasing or segmenting: arming and box kept for the ATTACH); two at once arm none (a backed-off hand still counts). A hand whose arming was retracted re-arms only after its box centre moves > move_m or freeze_s elapses, under the same identity — unless its arming ended by leaving (approach_ended) and every sample for a continuous freeze_s since showed it in located (the approach boxes of the hands located and holding nothing this tick) with its box off the column over its last target: then a fresh identity (liveness after a kernel fault retirement the producer cannot see). An unlocated, holding or back-over-the-target sample restarts that window; absence from near alone is not away.
  • on_attachment_changed(*, now_ns, emptied=True, holding=()) -> None (L898) — The bridge is publishing a set that lost or replaced an object, or is empty (the kernel's detach edge retires an armed declaration before its handover too). An arming not handed over drops its region and, approach-armed, advances to a fresh identity — the counter also advances when an identity was armed since the last advance and has since retracted (the kernel may still hold it); no region with stamp_ns <= now_ns is accepted afterwards (any arming). An arming whose hand is in holding (mid-grasp: an ATTACH being resolved) keeps its identity unless emptied (the kernel retires on the empty edge regardless, so that grasp then hands nothing over) — but always drops its pre-change region, so its handover carries none. A handed-over pick follows its own path; a named declaration keeps dispatch's identity (the kernel refuses it once retired).
  • on_base_moved(*, now_ns) -> None — A mobile base moved: a held region not yet handed over is retracted (retracted:base_moved; measured in the grid frame, which rides the base), and with none held the generation still advances so a reply in flight is dropped; a handed-over one is the hand's payload and stays. The bridge calls it on each BASE_STILL_* trip from a reference taken at the previous trip, checked before the sample's grasp transitions. (L764)
  • presence_unknown() -> None (L783) — A tick that could not sample the hands (no fresh grid, a request in flight, a stale verdict): every away window restarts — unknown is not away.
  • on_attach(contact_link, *, confirm) -> None (L802) — confirm receives the held region or None; Per hand: a link of the armed declaration (approach-armed hand, or a named search_box one) attached → no further measurement or approach arming until that hand's pick completes (on_pick_complete); the held region is kept for the kernel's handover only if confirm(region) (run under the lock, before any state changes) says the payload is its target, else dropped (attach_off_target, also when confirm raises). An ATTACH on a hand with nothing armed (the goal-scope declaration names every hand) hands nothing over and is logged.
  • on_release(hand, record) -> None (L871) — The bridge's DETACH on the handed-over hand: drop its region at once, keep the handover (nothing re-latches it), remember record (the frozen release record, or None) as the hand's spent payload. A named search_box declaration drops its region too (nothing spent recorded: it never re-arms); a hand not handed over is untouched.
  • on_pick_complete(hand, *, now_ns) -> bool (L962) — The handed-over hand holds nothing: drop the arming (backoff as a refusal), advance the pick counter, release the handover (spent defaulted to None when no on_release came). Named search_box declarations stay handed over (returns False).
  • spent(hand) -> tuple[bool, AttachedCollisionObject | None] (L992) — (guarded, released record) of the hand's last completed pick this goal; cleared by a new or cleared declaration.
  • clear_spent(hand, record) -> None (L997) — End the guard, only while record is still the guarded one; the ending is logged once (the hand may arm again).
  • measured() -> tuple[GraspDeclaration | None, int] (L480) — (target, generation) read atomically, to tag one measurement request.
  • (property) generation -> int (L504) — bumped on every change of what is measured (declaration, arming, retraction, handover); the leg tags each request with it and drops a reply or deadline under an older one.
  • (property) handed_over -> tuple[str, ...] | None (L491) — links of the hand whose ATTACH ended re-measurement.
  • (property) region_generation -> int (L496) — the generation the held region was accepted under; a map re-stamp of the same measurement keeps it, a new declaration or pick bumps it.
  • wants_measurement(*, now_ns) -> bool (L1004) — Live, has a search_box, not handed over.
  • accept(region, *, generation=None, map_cells=0) -> None (L1015) — Hold a region (map_cells > 0: completed from the map — that many cells came from the map alone, logged with the completed half-extents on entering that state); one that breaks GraspDeclaration's caps is refused (declaration_bounds). Ignored once handed over, under a generation other than the current one, or when the region was measured at or before the last attachment-set change (on_attachment_changed; measured_before_change, logged once).
  • refuse(kind, detail, *, retract, now_ns, generation=None) -> None (L1065) — Retract now, or freeze under the TTL. Ignored once handed over, or under a generation other than the current one.
  • envelope(*, now_ns) -> GraspDeclaration | None (L1101) — Dispatch's fields verbatim + the held region; expiry clears, an over-age unfrozen region is retracted.
  • (property) declaration -> GraspDeclaration | None (L470) — dispatch's live copy, region-less.
  • (property) target -> GraspDeclaration | None (L475) — what is measured and published: the approach-armed one-hand declaration while held, else dispatch's.
  • (property) region -> PlaceRegion | None (L486) — the last accepted region still held.
  • APPROACH_TARGET_PREFIX = "approach:" (L324) — target_id prefix of an approach-armed declaration; the hand's first link and :<n> (the pick counter) follow — one identity per pick.
  • approach_cell_count(grid, box) -> int (L1190) — Occupied cells in an approach box above its lowest occupied layer (the support under the hand); one layer only, so a box bottom cutting a small object still counts it.
  • approach_box(points, *, approach_m, frame_id, cap_m=GraspDeclaration.MAX_HALF_EXTENT_M) -> PlaceRegion (L1154) — Gravity-aligned box spanning a hand's TCP points grown by approach_m, each half-extent capped at cap_m (the pre-measurement box lifts it); the approach test and the approach-armed target's search box. ROSConfigError on no points.
  • rebase_box — moved to openral_core.geometry (re-imported here; the object tracker re-expresses fixed-frame place zones with it too). A gravity-aligned declared box re-expressed in frame through tf2 frame <- box, still yaw-only (the transform's tilt, at most 0.5°, dropped; more, or a tilted box, is a ROSConfigError). GraspTargetLeg._tick applies it every tick to a search_box / workspace_box a scene declares in a fixed frame (odom, map) via GraspTargetTracker.rebase(resolve) — which re-expresses the boxes as declared, never compounding, keeping identity, generation and region — so they stay put while a mobile base moves; with no tf2 the box stays in its own frame and the existing frame_mismatch refusal / workspace retraction applies.
  • search_column(search_box, *, below_m) -> PlaceRegion (L1122) — The search box extended below_m downward, the column the support is measured in; a tilted box is a ROSConfigError.
  • _hand_over_target(hands, held, *, reach_m, hand_rise_m) -> bool [private] (L1251) — A declared contact link's hand point (the jaw TCP, a finger length above the tips) over the held region's footprint, up to hand_rise_m above its top, grown by reach_m; the measure hand_at_target and occluded_refit share.
  • _refused_fit(kind, detail, previous, hands, *, reach_m, hand_rise_m, visible=None, tol_m=0.0) -> _Refusal [private] (L1300) — A refusal from target_region_from_mask typed for the tracker: too_few_points is a lost view; a not_on_support with a region held, its visible box (TargetRegionFit.box) inside the held region grown by tol_m (one voxel) and the hand over it (_hand_over_target) is the hand_at_target lost view (the hand occluding the target's lower part, Isaac i25; the held region stays under its freeze TTL, never replaced); every other refusal (no height, the caps) and a visible part reaching outside the held region (target knocked over or gone) is the contradiction it names, hand or not.
  • _within_caps(region, grid) -> bool [private] (L1338) — Whether region's cell closure fits GraspDeclaration's half-extent and volume caps unclamped.
  • _capped_margin(region, grid, margin_m, *, down=True) -> tuple[float, str] [private] (L1346) — The largest margin <= margin_m whose bloat (margin_grown_region(down=down)) still fits the caps once cell-closed — the margin shrinks, never the measured box (bisection, rounded down; noted when reduced, 0 when the unbloated closure is already at the caps). The note names the state, never the bisected value, so logging on change logs once per state.
  • _kernel_closure(region, grid, *, margin_m=0.0, down=True) -> tuple[PlaceRegion, str] [private] (L1376) — The region as the kernel gets it over grid and a note when it is not as configured: bloated by the capped margin (margin_grown_region, every face with down, sides and top without), then cell_closed_region clamped at GraspDeclaration.MAX_HALF_EXTENT_M (noted), the tight fit when the closure exceeds MAX_VOLUME_M3 (noted). margin_m=0 is the unbloated closure of region exactly. Used by kernel_region (published region and payload, with the capped margin) and, unbloated, by _gate_refit (what the whole-target gate checks).
  • _gate_refit(grid, region, previous, *, support_z, min_cover, column, hands=(), occluder_margin_m=0.05, hand_rise_m=0.0, complete=True) -> tuple[PlaceRegion, int] [private] (L1426) — (accepted, added). Map cover on the fit (map_disagrees); the whole-target gate: when occupied_touching_outside on _kernel_closure(region) is non-empty the fit is completed from the map (map_completed_region inside column, Isaac i45) and the completed box is the candidate — what is tracked, held, handed over and published (cell-closed); then the tracking gate on that candidate (target_moved / occluded_refit / unoccluded_refit), so a later fit of more or less of the target completes or fits to about the same box. Against a held region (previous) the leg only logs its outcome: a held region is frozen and only the map retracts it (GraspTargetLeg._map_hold, design Revision 4). A refused completion leaves the tight fit as the candidate and, where it would otherwise be accepted, raises the lost view partial_fit (never re-classing another refusal; nothing new accepted, a held region kept under its freeze TTL). added = the cells the map added (0 for a fit holding the whole component).
  • WORKSPACE_MIN_COVER (re-exported from openral_core.perception_geometry) — The fraction of a declared workspace_box's footprint that occupied cells centred in it must cover for the leg to confirm it (region_covers_occupied); a calibration point (issue #349).
  • class GraspTargetLeg(node, bridge, config, *, support_search_below_m=0.15, support_probe_margin_m=0.05, occluder_margin_m=0.05, approach_m=None, premeasure=False) (L1560) — ROS wiring; premeasure (from VisionAttachmentConfig.grasp_target_premeasure, default off) pre-measures object instances before any hand arms: every SegmentInView request is then an instance prompt (_premeasure: at most _PREMEASURE_MAX_HZ = 2 Hz, one in flight, around each free hand within _PREMEASURE_REACH_APPROACHES = 2 approach distances or in the named/armed box; instance_prompt or a refresh of an instance older than half a freeze, every instance in the armed box due each prompt), its reply fitted by the camera path's _fit and kept only when map_confirms it (_on_instance_reply → PrimitiveTracker); instances older than freeze_s or no longer covered by the map are dropped every tick. The armed region comes from the instances with no segmenter call (_tick_instances: with nothing held, the instance nearest the armed hand, refused on a tie, or the lone one in a named box, through _gate_instance — its whole region inside that box plus one voxel, map_confirms, _gate_refit(complete=False) — then accepted). Frozen once held (design Revision 4, both paths): _map_hold(grid, held, source_ns, hands) every tick — map_confirms on the held box and its measured support; map_disagrees retracts, map_split retracts unless every second body lies in a declared hand's own space (_hand_boxes, passed as map_confirms(own=…); then a lost view, the freeze TTL runs), confirmed re-stamps the same box with the grid's source_stamp; re-fits still run but their outcome is only logged once per change (_refit_ignored: grasp target re-fit ignored, region frozen (map-confirmed) — …); on the camera path _hold_frozen runs _map_hold each tick and _refuse_refit logs instead of applying every re-fit refusal (seed, request, deadline, reply) while a region is held; approach_m (from VisionAttachmentConfig.grasp_target_approach_m, None = off) turns on the approach-armed target and must be in (0, GraspDeclaration.MAX_HALF_EXTENT_M]; reuses the bridge's depth/CameraInfo caches, tf2 buffer and SegmentInView client. ROSConfigError on a rate outside 2-5 Hz, a non-positive cell count / cover / probe margin, a freeze outside (0, 2·grid_max_age_s] (the kernel's grasp_region_max_age_s), a search depth outside (0, 0.5] m or an occluder margin outside [0, 0.10] m (upper bounds keep the gates meaningful), or config.grasp_target_margin_m outside [0, VisionAttachmentRuntime.MAX_GRASP_TARGET_MARGIN_M]; the setup line logs the margin. The bridge passes the support and occluder tunables from VisionAttachmentConfig.grasp_target_support_search_below_m / _support_probe_margin_m / _occluder_margin_m; the keyword defaults serve direct construction.
  • setup() -> None (L1727) — The declaration subscription + the measurement timer (the grid is the bridge's).
  • (attribute) unfiltered_fits -> int — Consecutive fits that found no self-filtered cloud for their capture although self_filtered_cloud_topic is set (the self-filter dropped it, the 8-deep cache rolled over, or no tf2): the capture is then not fitted (lost view unfiltered), since the robot's own points would enter it. Entering that state logs one warning (topic, depth stamp, cache size and stamp span); the next filtered fit logs the count and resets it (CLAUDE.md §1.4).
  • _kept_points(stamp_ns, frame) -> NDArray[np.float64] | None (L3208) — VisionAttachmentBridge.kept_points for _measure, keeping unfiltered_fits and its two log lines.
  • teardown() -> None (L1767) — Idempotent, under the bridge lock; marks the leg torn down and cancels any in-flight request's deadline.
  • fill(msg, *, now_ns) -> None (L1783) — Sets grasp_declaration_valid / grasp_declaration on one AttachmentState; the region goes out cell-closed (kernel_region): before the handover bloated on every face, from the handover on (tracker.handed_over; the bridge's on_attach precedes the ATTACH snapshot the kernel latches from) the payload box (payload=True), so the latched region is the payload — no downward bloat after the handover, the payload origin inside it at every margin. The tracker keeps the tight fit. Since #349 the declaration also carries workspace_region = published_workspace(...) when the leg holds a confirmation of its workspace_box.
  • published_workspace(declaration, *, now_ns) -> PlaceRegion | None (L2049) — The confirmed manipulation workspace (issue #349) to publish with declaration: only the confirmation of its own workspace_box (same frame, pose, extents; never grown) and only within freeze_s of its stamp (the confirming grid's source_stamp). _confirm_workspace(now_ns) (every tick, under the bridge lock) confirms the live declaration's box on a fresh grid (_fresh_grid) when occupied cells centred in it cover ≥ WORKSPACE_MIN_COVER of its footprint, retracts at once on map_disagrees / frame_mismatch / no box declared, and keeps the last confirmation on a stale or missing grid until it ages out; each state change is logged once.
  • kernel_region(target_id, region, *, payload=False) -> PlaceRegion (L1816) — The held region as the kernel gets it (payload=False, before the handover: bloated by grasp_target_margin_m on every face, downward too) or as the region payload's box (payload=True, VisionAttachmentBridge._region_payload and fill from the handover on, Isaac i50: lowered onto the measured support top by lowered_to_support (Isaac i56/i57), then bloated on the sides and top only — the region the kernel latches) (HZ-0115-32), then cell_closed_region over the newest grid, clamped at GraspDeclaration.MAX_HALF_EXTENT_M; a closure over MAX_VOLUME_M3, no grid or a grid in another frame publishes the tight box. The capped margin is cached per (region, grid frame/resolution/orientation, margin) per box kind, so an unchanged region costs no bisection per publish. Every such case is logged once per change of (box kind, note), never per refit near the caps.
  • on_detach(jaw_link, record) -> None (L2547) — The bridge's DETACH (after it dropped the leg's attachment), with the release window's frozen record or None: tracker.on_release, then the pick completes if the hand's legs hold nothing (no attachment, window, pending segmentation or loaded trigger). Event-driven, never polled.
  • on_attachment_changed(*, emptied) -> None (L2563) — Called by VisionAttachmentBridge._publish_attachment before it fills a snapshot whose set lost or replaced an object, or is empty: tracker.on_attachment_changed at the node clock with the links of every hand with an ATTACH being resolved (_resolving: a segmentation in flight or loaded jaws, nothing latched) — producer-side liveness for the kernel's detach-edge retirement, HZ-0115-3; a mid-grasp hand keeps its identity unless the set emptied, never its region.
  • on_base_moved() -> None — GraspTargetTracker.on_base_moved at the node clock; called by the bridge's _check_base_motion. (L2587)
  • on_hand_settled(jaw_link) -> None (L2591) — The leg's release window closed (not for a re-ATTACH), its barrier was released, or it DETACHed with nothing latched: completes the pick if the hand holds nothing (a trigger reading the jaws loaded counts as holding). Event-driven, never polled.
  • measured_support(region) -> float | None (L2994) — The support top (support_top_from_voxels) the request whose reply the tracker accepted as exactly region was measured on (_on_reply records it; target_region_from_mask stood the box one voxel above it), in region.frame_id; None for any other region. What _region_payload passes to region_attachment(support_z=…).
  • on_attach(jaw_link, payload, *, region) -> None (L2605) — The bridge's one entry for a resolved ATTACH: region set (the payload was built from it, _region_payload) hands over only while the tracker still holds exactly that region (dropped or replaced since → attach_off_target, never "absent"); region=None (segmented, _finish) hands over only when the jaw is at the held region (VisionAttachmentBridge.jaw_at, reach occluder_margin_m) and every payload primitive centre lies in it grown by one voxel — else attach_off_target.

python/hal/src/openral_hal/_place_target_leg.py

The real place producer (design note docs/reference/real-pick-place-design.md §2.3; drafted, unapproved ADR-0097 / ADR-0092 D6 amendments in docs/reference/real-pick-place-adr-drafts.md), owned by VisionAttachmentBridge, default off. Nothing is surveyed and nobody has to name a place target, but nothing arms outside a goal: at place_target_rate_hz, only under a live dispatch /openral/place_declaration (else no_declaration), against the newest /openral/world_voxels (the bridge's shared grid; received, or its source_stamp data, older than grid_max_age_s, or source_stamp unset/future → grid_stale, a lost view), it measures the surface directly under the held, loaded payload — a column of the payload's lattice-axis footprint grown by one voxel + place_target_extrinsic_error_m, from its bottom down place_target_search_depth_m; the first occupied layer must cover the whole footprint (partial_support otherwise) with the payload's height + one voxel + the extrinsic bound free above it (no_headroom); cells within one voxel of any published payload are ignored. The patch is latched as a one-voxel slab region (grid frame, no geometry, stamp_ns = the grid's source_stamp — the world data's capture time, the kernel's own voxel data-age clock, never header.stamp, which a bridge republishing a stalled octree keeps fresh) and re-verified (not re-chosen) while the payload stays over it: new occupancy above it retracts at once, missing support cells / a missing or stale grid freeze it for at most place_target_freeze_s (default and ceiling 2 * grid_max_age_s, the kernel's place-region age bound) from its last verification. The dispatch /openral/place_declaration (RELIABLE + TRANSIENT_LOCAL, depth 1; region never relayed) is required — the runner's goal-scope one (place_approach_enabled, target_id="surface") or a named one; the leg never declares on its own. Its fields ride the envelope (the measured region attached, object_id narrowed to the measured payload when empty) and its search_box refuses a patch outside it (outside_hint). A retraction (goal end, cancel, E-stop) or expiry retracts the patch and the witness (no_declaration) and nothing re-arms until a new declaration; a new declaration drops a latched patch (redeclared) so it is re-measured under the new hint. The witness (MAP_SUPPORT_PROXIMITY, proximity to a map-measured plane, not sensed contact, not a proven support) is attested once per (declaration, payload); it dies with the region (contradiction, the freeze TTL = the kernel's region age bound, retraction or a payload change), so no part of the place allowance outlives a region the kernel would drop as region_stale.

  • class PlaceRefusal(StrEnum) (L140) — Typed reasons: no_payload, payload_changed, no_grid, grid_stale, tilted, no_surface, partial_support, no_headroom, outside_hint, frame_mismatch, free_volume_occupied, support_occluded, freeze_ttl, grid_moved (the lattice re-snapped since the latch — a contradiction), no_declaration (no goal: retraction, expiry or none yet), redeclared (a new declaration drops the old latch); the grid ones and support_occluded are lost views that freeze a latched patch.
  • class PlacePatch (L169) — Frozen dataclass: lattice layer, i0/j0/ni/nj, free_layers, plane_z, the slab region, and the latch grid's lattice ((origin, orientation_xyzw, resolution), which the indices are into).
  • measure_under_payload(grid, payload, *, extrinsic_error_m, search_depth_m, exclude=(), evidence_ref="") -> PlacePatch | tuple[PlaceRefusal, str] (L298) — The surface under the carried payload (see the module note); region.evidence_ref carries map_measured_support:plane_z=…;patch=<ni>x<nj>@layer<k>.
  • verify_patch(grid, patch, payload=()) -> tuple[PlaceRefusal, str] | None (L383) — Re-check on a newer grid: grid_moved (origin/orientation/resolution off the latch lattice by > _LATTICE_TOL = 1e-6 — the indices name other cells; contradiction), free_volume_occupied (contradiction) or support_occluded (lost view); None = holds.
  • payload_witness(obj, t_base_link, patch, *, support_id, resolution, extrinsic_error_m, stamp_ns) -> tuple[SupportContactWitness | None, str] (L442) — Lowest primitive point within max(resolution, extrinsic_error_m) of the measured plane and centre over the patch → the witness (plane_witness).
  • plane_witness(obj, t_base_link, *, plane_z, support_id, extrinsic_error_m, detail, stamp_ns) -> SupportContactWitness (L486) — The one map-support proximity witness construction, shared by payload_witness (place) and vision_attachment_bridge.region_attachment (vision pick): contact point under the payload's centre on z = plane_z, normal +z, both in the object frame; patch_radius_m = the horizontal footprint (per primitive: horizontal offset + its local box's farthest corner projected onto the plane — a yaw-only box's hypot(hx, hy), never the 3-D half-extent norm, whose vertical term widened the exemption) ≤ 0.5; max_penetration_m = min(extrinsic_error_m, 0.01); confidence=0.5; MAP_SUPPORT_PROXIMITY.
  • class PlaceTargetTracker(*, freeze_s, extrinsic_error_m, log) (L561) — Pure state machine on a caller-supplied ROS-clock now_ns.
  • on_declaration(declaration) -> None (L636) — Dispatch's goal-scope copy; active=False drops it with the patch and the witness (no_declaration); a new one drops a latched patch (redeclared) and the witness; the latched copy again is a no-op.
  • latch(patch, *, payload_key, resolution) -> None (L672) — Hold a measured patch.
  • reverified(grid_stamp_ns) -> None (L685) — Restamp the region with the verifying grid's source_stamp (an unchanged stamp never makes it younger).
  • refuse(reason, detail, *, now_ns) -> None (L694) — Lost view freezes a latched patch; anything else retracts.
  • live(*, now_ns) -> PlaceDeclaration | None (L715) — Dispatch's live declaration; expiry ends the allowance like a retraction.
  • envelope(*, now_ns) -> PlaceDeclaration | None (L727) — Dispatch's live declaration (+ the held region, scoped to its payload when dispatch names no object), else None; expires an over-age region.
  • attest(candidates, *, now_ns) -> bool (L745) — Arm or drop the witness from (attachment, T_grid_from_attach_link | None, loaded) per leg; True when the published set must change.
  • on_released(held, record) -> None (L804) — Re-keys the patch latched and the witness armed on held to its frozen release record (stamped at the DETACH sample), so both ride the record through the window; the bridge calls it as the window opens.
  • decorate(objects) -> list[AttachedCollisionObject] (L820) — The set with the held witness on the object it names.
  • (property) declaration -> PlaceDeclaration | None (L605) — dispatch's copy in force, region-less.
  • (property) patch -> PlacePatch | None (L610) — the latched patch.
  • (property) payload_key -> tuple[str, int] | None (L615) — the payload the patch was measured under.
  • place_tick(tracker, grid, grid_stamp_ns, *, carried, published, extrinsic_error_m, search_depth_m, now_ns) -> None (L855) — One pure measurement tick (grid_stamp_ns = the grid's source_stamp): nothing without a live declaration (no_declaration); re-verify the latched patch while its payload is over it (or released onto it), else refuse a dispatch hint in another frame than the grid (frame_mismatch, before measuring), then measure under the carried payload, applying the hint (outside_hint).
  • class PlaceTargetLeg(node, bridge, config) (L948) — ROS wiring; reuses the bridge's tf2 buffer, legs and publisher. ROSConfigError on a non-positive rate / freeze / depth / extrinsic bound, or a freeze past 2 * grid_max_age_s.
  • setup() -> None (L1016) — The declaration subscription + the measurement timer (the grid is the bridge's shared one).
  • teardown() -> None (L1049) — Idempotent.
  • fill(msg, *, now_ns) -> None (L1061) — Sets place_declaration_valid / place_declaration on one AttachmentState.
  • decorate(objects) -> list[AttachedCollisionObject] (L1068) — PlaceTargetTracker.decorate.
  • on_joint_state() -> None (L1073) — Witness re-evaluation (throttled to 20 Hz); republishes on a change.

Node wiring (ManifestHALLifecycleNode): vision_attachment_* params (enabled defaults to False; vision_attachment_tf_frames takes "link=frame" strings; no trigger thresholds are params — they are the manifest's closure_calibration; _on_safe_action feeds the HAL's applied command to observe_command (_fold_applied_command, which clears it via clear_command when a committed group's command is unknown); the trigger windows are PositionStallConfig.for_rate of the node's resolved joint-state rate (publish_rate_hz, else the manifest's control_rate_hz), with vision_attachment_trigger_max_gap_s (default 0.0 = derived) as an explicit gap override; vision_attachment_grasp_target_support_search_below_m / _support_probe_margin_m / _occluder_margin_m (defaults 0.15 / 0.05 / 0.05 m) reach GraspTargetLeg through the matching VisionAttachmentConfig fields; vision_attachment_grid_max_age_s / _release_clear_m default 0.0 = unset and are REQUIRED with the leg on — the kernel's voxel deadline and margin + resolution, passed by deploy_e2e.launch.py; unset is a ROSConfigError naming the param at activate, no cell's values as fallback); built in _setup_vision_attachment on activate, torn down on deactivate/cleanup. _attachment_barrier_holders() / _attachment_perception_ready() require every present holder (sim bridge + vision bridge) to clear before a tick is acknowledged. _publish_action_applied_if_complete re-checks readiness right after storing a deferred tick (_on_attachment_perception_ready), so a holder settling on another thread between the check and the store cannot strand it (a lost wakeup); _publish_action_applied_tick's check-and-publish runs under _ack_publish_lock (calls no holder), so that re-check and a holder's notify ack a tick once.