feat: new openarm adapter#2382
Conversation
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR introduces a new
Confidence Score: 4/5The adapter is safe for wiring and basic bring-up; one error-recovery path in
dimos/hardware/manipulators/damiao/base_adapter.py — specifically the Important Files Changed
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
Reviews (7): Last reviewed commit: "fix: openarm adapter lifecycle" | Re-trigger Greptile |
| 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 |
There was a problem hiding this comment.
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.
| 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 |
| 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 | ||
|
|
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
b675674 to
b5a0e2c
Compare
| adapter.connect() | ||
|
|
||
|
|
||
| def test_lifecycle_read_write_disable() -> None: |
There was a problem hiding this comment.
There are many low value tests in this file. Tests should check functionality.
A good test is structured like this:
- setup the test
- execute the functionality
- 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.
| @@ -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. | |||
There was a problem hiding this comment.
If we want to use OpenSpec, that should be a separate PR, it shouldn't be coupled to this openarm stuff.
There was a problem hiding this comment.
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).
|
@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
| 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 |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
_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.
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
6f77783 to
2125808
Compare
Solution
Adds an opt-in
openarm_rsmanipulator adapter for OpenArm hardware using the Rust-backedcan-motor-controlPython binding. (https://github.com/TomCC7/can-motor-control)The existing
openarmadapter remains the default production path.openarm_rsis 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__.pymanifests, 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.can_motor_controlnow fails only whenopenarm_rsis selected/connected, with a clear install hint.How to Test