Skip to content

feat: new openarm adapter#2382

Open
TomCC7 wants to merge 32 commits into
mainfrom
cc/openarm-rust-adapter
Open

feat: new openarm adapter#2382
TomCC7 wants to merge 32 commits into
mainfrom
cc/openarm-rust-adapter

Conversation

@TomCC7

@TomCC7 TomCC7 commented Jun 6, 2026

Copy link
Copy Markdown
Member

Solution

Adds an opt-in openarm_rs manipulator adapter for OpenArm hardware using the Rust-backed can-motor-control Python binding. (https://github.com/TomCC7/can-motor-control)

The existing openarm adapter remains the default production path. openarm_rs is selected explicitly through hardware config or the new OpenArm RS blueprints, and is intended for binding-backed bring-up, state monitoring, MIT command validation, gravity compensation, and trajectory-control validation.

This also updates manipulator adapter discovery to use lightweight __registry__.py manifests, so listing available adapters does not import unselected hardware SDKs or optional bindings.

User-facing behavior

  • adapter_type="openarm" continues to use the existing in-tree SocketCAN OpenArm adapter.
  • adapter_type="openarm_rs" selects the Rust-backed OpenArm adapter.
  • Missing can_motor_control now fails only when openarm_rs is selected/connected, with a clear install hint.
  • Adapter listing remains healthy in partial installs.
  • The OpenArm RS path defaults to CAN-FD and supports staged validation before active trajectory control.

How to Test

uv run pytest \
  dimos/hardware/manipulators/test_registry.py \
  dimos/hardware/manipulators/openarm_rs/test_adapter.py \
  dimos/hardware/manipulators/damiao/test_base_adapter.py -q

uv run mypy \
  dimos/hardware/manipulators/damiao/base_adapter.py \
  dimos/hardware/manipulators/openarm_rs/test_adapter.py
For hardware bring-up:
dimos run coordinator-openarm-rs

@codecov

codecov Bot commented Jun 6, 2026

Copy link
Copy Markdown

@TomCC7 TomCC7 marked this pull request as ready for review June 8, 2026 04:30
@greptile-apps

greptile-apps Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces a new openarm_rs manipulator adapter backed by the Rust can-motor-control Python binding, alongside a shared DamiaoArmAdapterBase that provides MIT/gravity-compensation control. Adapter discovery is moved to lightweight __registry__.py manifests so unselected hardware SDKs are never imported.

  • New adapter: OpenArmRSAdapter subclasses DamiaoArmAdapterBase, picks per-side joint limits based on side=\"left\"/\"right\", defaults to CAN-FD, and exposes gravity-compensation and MIT command paths.
  • Registry refactor: AdapterRegistry.discover() now imports only manifest files; the full adapter module is loaded lazily on first create(), keeping partial installs healthy.
  • New blueprints: coordinator_openarm_rs and openarm_rs_planner_coordinator wire the right-arm RS adapter into the existing coordinator/planner pipeline.

Confidence Score: 4/5

The adapter is safe for wiring and basic bring-up; one error-recovery path in write_clear_errors leaves the hardware motors enabled without a position hold if the startup write fails.

write_clear_errors sets _enabled = True and calls _robot.enable(), then attempts a hold-position write. If that write returns False, the method returns without calling _robot.disable() or resetting _enabled, so the hardware remains powered with no reference position. The analogous code path in write_enable was corrected (it now resets _enabled and disables the robot on hold failure), but write_clear_errors did not receive the same treatment.

dimos/hardware/manipulators/damiao/base_adapter.py — specifically the write_clear_errors method around line 539

Important Files Changed

Filename Overview
dimos/hardware/manipulators/damiao/base_adapter.py New shared Damiao adapter base with MIT/gravity-comp control — write_clear_errors leaves _enabled=True and motors powered without a position hold when the startup hold write fails
dimos/hardware/manipulators/openarm_rs/adapter.py New OpenArmRS adapter subclassing DamiaoArmAdapterBase; correctly selects per-side joint limits and rejects custom motor specs
dimos/hardware/manipulators/registry.py Registry refactored to lazy-path manifests; no error handling around __registry__.py imports in discover(), but discovery logic is otherwise correct
dimos/hardware/manipulators/damiao/specs.py New typed spec dataclasses with proper validation of CAN ID uniqueness and per-joint length checks
dimos/robot/manipulators/openarm/blueprints.py Adds coordinator_openarm_rs and openarm_rs_planner_coordinator blueprints targeting the right arm; gravity model path and side settings are wired correctly
dimos/robot/catalog/openarm.py Adds OPENARM_V10_RIGHT_MODEL export and adapter_kwargs merge logic in openarm_arm to allow callers to add keys without clobbering the catalog's side
dimos/hardware/manipulators/damiao/test_base_adapter.py Tests write_stop and write_enable failure paths but has no test for write_clear_errors hold-failure state

Class Diagram

%%{init: {'theme': 'neutral'}}%%
classDiagram
    class DamiaoArmAdapterBase {
        +connect() bool
        +disconnect() void
        +write_enable(enable) bool
        +write_stop() bool
        +write_clear_errors() bool
        +write_joint_positions(positions) bool
        +write_mit_commands(...) bool
        +compute_gravity_torques(q) list
        -_robot: Any
        -_enabled: bool
        -_gravity_comp: bool
    }
    class OpenArmRSAdapter {
        +_adapter_type = "openarm_rs"
        +_POSITION_LOWER_LEFT
        +_POSITION_LOWER_RIGHT
        +__init__(side, address, canfd, ...)
    }
    class AdapterRegistry {
        +register(name, cls)
        +register_path(name, factory_path)
        +discover()
        +create(name, **kwargs)
        +available() list
        -_resolve_adapter(key)
    }
    class DamiaoArmSpec {
        +name: str
        +vendor: str
        +motors: tuple
        +position_lower: tuple
        +position_upper: tuple
        +kp: tuple
        +kd: tuple
        +validate()
        +from_values(...)
    }
    DamiaoArmAdapterBase <|-- OpenArmRSAdapter
    DamiaoArmAdapterBase --> DamiaoArmSpec : uses
    AdapterRegistry --> OpenArmRSAdapter : creates via lazy path
Loading

Reviews (7): Last reviewed commit: "fix: openarm adapter lifecycle" | Re-trigger Greptile

Comment thread dimos/hardware/manipulators/openarm_rs/adapter.py Outdated
Comment on lines +480 to +490
def write_clear_errors(self) -> bool:
if self._robot is None:
return False
try:
self._robot.disable()
self._robot.enable()
except Exception as exc:
logger.error(f"{type(self).__name__} {self._hardware_id} clear errors failed: {exc}")
return False
self._enabled = True
return True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 write_clear_errors() re-enables the motors but does not issue a hold command for the current position, unlike write_enable(True) which calls write_joint_positions(positions) after enabling. On a gravity-loaded arm this means clearing errors leaves the arm unpowered at its last position for one control cycle before the caller sends the next command, which could cause uncontrolled droop or jerk.

Suggested change
def write_clear_errors(self) -> bool:
if self._robot is None:
return False
try:
self._robot.disable()
self._robot.enable()
except Exception as exc:
logger.error(f"{type(self).__name__} {self._hardware_id} clear errors failed: {exc}")
return False
self._enabled = True
return True
def write_clear_errors(self) -> bool:
if self._robot is None:
return False
try:
self._robot.disable()
self._robot.enable()
except Exception as exc:
logger.error(f"{type(self).__name__} {self._hardware_id} clear errors failed: {exc}")
return False
self._enabled = True
positions = self.read_joint_positions()
if not self.write_joint_positions(positions):
logger.error(f"{type(self).__name__} {self._hardware_id} clear errors hold failed")
return False
return True

Comment on lines +302 to +315
def disconnect(self) -> None:
if self._robot is not None:
try:
self._robot.disable()
except Exception as exc:
logger.warning(
f"{type(self).__name__} {self._hardware_id} disable on disconnect failed: {exc}"
)
self._enabled = False
self._connected = False
self._robot = None
self._arm = None
self._state_cache = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 disconnect() only disables motors, no connection teardown

connect() calls robot.connect() but disconnect() only calls robot.disable(). If the can_motor_control binding keeps sockets, threads, or file descriptors open until an explicit disconnect is called, resources will leak on every reconnect or clean shutdown. The original OpenArmAdapter.disconnect() closes the bus (bus.closed is True in its test). Consider calling self._robot.disconnect() (or equivalent) if the binding exposes one, before nulling out self._robot.

Comment on lines +100 to +120
import dimos.hardware.manipulators as pkg

for root in pkg.__path__:
for child in sorted(Path(root).iterdir()):
if not child.is_dir() or child.name.startswith(("_", ".")):
continue
if not (child / "__registry__.py").exists():
continue

module_name = f"dimos.hardware.manipulators.{child.name}.__registry__"
module = importlib.import_module(module_name)
adapter_factories_obj = getattr(module, "ADAPTER_FACTORIES", None)
if not isinstance(adapter_factories_obj, Mapping):
raise TypeError(f"{module_name} must define ADAPTER_FACTORIES")
adapter_factories = cast("Mapping[object, object]", adapter_factories_obj)
for name, factory_path in adapter_factories.items():
if not isinstance(name, str) or not isinstance(factory_path, str):
raise TypeError(
f"{module_name}.ADAPTER_FACTORIES must map strings to strings"
)
self.register_path(name, factory_path)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 discover() no longer silences import errors from __registry__.py files

The old discover() wrapped each adapter import in except ImportError and logged a debug message, so a broken adapter never blocked discovery of others. The new implementation calls importlib.import_module(module_name) for each __registry__.py with no error handling. A SyntaxError, missing transitive dependency, or any other exception in a __registry__.py (even a third-party plugin) will now abort discovery entirely and make all adapters unavailable. Adding a narrow except Exception around each importlib.import_module call with a warning log would restore the resilience property.

@TomCC7 TomCC7 force-pushed the cc/openarm-rust-adapter branch from b675674 to b5a0e2c Compare June 8, 2026 05:32
Comment thread openspec/changes/archive/2026-06-06-add-dm-motor-arm-adapter/tasks.md Outdated
adapter.connect()


def test_lifecycle_read_write_disable() -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are many low value tests in this file. Tests should check functionality.

A good test is structured like this:

  1. setup the test
  2. execute the functionality
  3. check that the desired result was achieved

But a test like this one just constructs one object and asserts every minor aspect. It's not clear what behavior is even desired given that so much is asserted.

Tests that over-assert make the system hard to change and introduce uncertainty.

Comment thread docs/development/openspec.md Outdated
@@ -0,0 +1,102 @@
# OpenSpec Workflow

DimOS uses OpenSpec as the checked-in planning layer for behavior changes. OpenSpec artifacts live under `openspec/` and should describe what the system is supposed to do, why it is changing, and how contributors or agents should validate the work.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we want to use OpenSpec, that should be a separate PR, it shouldn't be coupled to this openarm stuff.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the confusion added here. I based all my branches on an openspec initialization commit. I cleaned that out and created this pr: #2428. will remove openspec stuff in this branch

The FloatArray alias and its numpy.typing.NDArray import were never
referenced. Remove both.
The OpenArmRSMotorSpecConfig alias for DamiaoMotorSpec was only
referenced by its own __all__ entry; nothing imports it. Remove both.
Move 'import time' out of FakeState.__init__ to the module top, per the
imports-at-top convention. FakeState.timestamp is still read by the
adapter's staleness check, so it stays.
gravity_comp=True and canfd=True are already the OpenArmRSAdapter
defaults. The blueprint should only specify what differs, so keep just
gravity_model_path.
Per the imports convention, a lazy import of a heavy optional dep needs
a comment saying why. Add it to both gravity-model import sites.
tick_deadline_us=1_000 and state_cache_ttl_s=0.002 were unnamed magic
numbers duplicated as defaults in both the base and the openarm_rs
subclass. Hoist them to _DEFAULT_TICK_DEADLINE_US and
_DEFAULT_STATE_CACHE_TTL_S so the two can't drift.
The 'can0' interface name was hard-coded three times: the base
constructor default, the base None-coalesce, and the openarm_rs
subclass default. Collapse them onto one _DEFAULT_ADDRESS constant so
the literal lives in exactly one place. The None-coalesce stays to
handle a config that leaves address unset (the factory then passes
address=None).
- refresh_state: build the position/velocity/torque lists with
  ndarray.tolist() instead of per-element float() loops.
- write_mit_commands: assemble the MIT matrix with np.column_stack
  instead of a Python comprehension over zipped rows; this removes the
  now-redundant _mit_command_rows helper (validation moves to a direct
  _validate_command_lengths call).
- read_state: look the control-mode index up in a precomputed
  _CONTROL_MODE_INDEX map instead of rebuilding list(ControlMode) every
  call.
The connect/disconnect/write_enable/write_clear_errors/write_stop paths
stuffed context into f-string log lines and dropped the traceback on
real failures. Switch to structlog key/value fields and use
logger.exception (or warning with exc_info) so the traceback survives
instead of being downgraded to an f-string error message.
When the pre-command state read fails, the adapter substitutes
zero feed-forward torque. Log a warning (with traceback) so the dropped
gravity term is visible instead of being silently swallowed.
The try wrapped both refresh_state and compute_gravity_torques under a
broad except Exception, masking a real gravity-model error as 'invalid
state'. Scope the try to refresh_state (the call that raises RuntimeError
on a bad read) and let a genuine compute error propagate. Also switch
the log line to structured fields with a traceback.
The **_: object catch-all silently dropped misspelled adapter kwargs.
The registry factory only passes declared parameters (dof, address,
hardware_id plus the blueprint adapter_kwargs), so drop the catch-all
to turn config typos into a clear TypeError.
The OpenArm integration guide inlined the kp/kd preset numbers, which
drift from the adapter code. Replace them with a pointer to
OpenArmRSAdapter._DEFAULT_KP/_DEFAULT_KD (and the openarm adapter's
own constants).
@paul-nechifor

Copy link
Copy Markdown
Contributor

@TomCC7 My auto fixer created this PR: https://github.com/dimensionalOS/dimos/pull/2426/changes

Do you agree with the changes? If so, please merge them into this PR.

…utofixes

Auto-fixes for cc/openarm-rust-adapter
@github-actions github-actions Bot added the ready-to-merge Required CI checks have passed on this PR label Jun 8, 2026
@github-actions github-actions Bot removed the ready-to-merge Required CI checks have passed on this PR label Jun 8, 2026
Comment on lines +452 to +478
def write_stop(self) -> bool:
if self._arm is None or self._robot is None:
return False
if self._gravity_comp and self._enabled:
try:
q_now = self.read_joint_positions()
except RuntimeError:
return False
return self.write_mit_commands(
q=q_now,
dq=self._zero_vector(),
kp=list(self._kp),
kd=list(self._kd),
tau=self.compute_gravity_torques(q_now),
)
try:
self._robot.disable()
except Exception:
logger.warning(
"damiao adapter stop disable failed",
adapter=type(self).__name__,
hardware_id=self._hardware_id,
exc_info=True,
)
return False
self._enabled = False
return True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 write_stop() leaves motors powered on gravity-comp state-read failure

When gravity_comp=True and _enabled=True, a RuntimeError from read_joint_positions() (e.g., a CAN bus fault) causes the method to return False without ever calling _robot.disable(). The motors remain hardware-powered with no position hold issued — the opposite of a stop. The fallthrough _robot.disable() path at the bottom of the method is never reached because the gravity-comp branch returns early. A safe fallback would be to attempt _robot.disable() before returning False in the except RuntimeError block.

Comment on lines +480 to +503
def write_enable(self, enable: bool) -> bool:
if self._robot is None:
return False
try:
self._robot.enable() if enable else self._robot.disable()
except Exception:
logger.exception(
"damiao adapter enable failed",
adapter=type(self).__name__,
hardware_id=self._hardware_id,
enable=enable,
)
return False
self._enabled = enable
if enable:
positions = self.read_joint_positions()
if not self.write_joint_positions(positions):
logger.error(
"damiao adapter startup hold failed",
adapter=type(self).__name__,
hardware_id=self._hardware_id,
)
return False
return True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 _enabled=True persists after a failed startup hold position write

_enabled = enable is set unconditionally at line 493 once _robot.enable() succeeds. If the subsequent write_joint_positions(positions) call returns False (for example, a transient CAN error during the MIT write), the method returns False to the caller but _enabled remains True. The hardware motors are enabled (from _robot.enable()) but no hold position was written, so the arm is powered with no reference. Any subsequent method call that guards on self._enabled (such as write_joint_positions, write_joint_torques, write_mit_commands) will proceed against an arm in an undefined state. Consider setting _enabled = False and calling _robot.disable() before returning False from the startup hold failure path.

@github-actions github-actions Bot added the ready-to-merge Required CI checks have passed on this PR label Jun 9, 2026
@greptile-apps

greptile-apps Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@TomCC7 TomCC7 force-pushed the cc/openarm-rust-adapter branch from 6f77783 to 2125808 Compare June 9, 2026 00:37
@github-actions github-actions Bot removed the ready-to-merge Required CI checks have passed on this PR label Jun 9, 2026
Comment thread dimos/hardware/manipulators/damiao/base_adapter.py
@github-actions github-actions Bot added the ready-to-merge Required CI checks have passed on this PR label Jun 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-to-merge Required CI checks have passed on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants