Driver template and examples
A driver is the one Python class our control loop needs to run a robot of your own: it reads and writes one arm, in the units of your arm’s URDF. This page holds the template to start yours from and the drivers we ship, as worked examples. Each block below is a whole file: copy it with the block’s copy button and save it under the name in its title. A robot of your own says how the loop runs your driver and how a coding agent can write one for you.
The driver template
Section titled “The driver template”Save it beside your robot’s config (as my_arm.py, for one), fill in its four methods, read(), write(), close() and torque_off(), and point the config’s custom.driver at it (my_arm.py:MyArm once you rename the class). As it ships, TemplateArm is an arm in memory that reads back what it was last told, so the whole loop runs with no robot attached; its docstring gives a whole config and the dry run to try first.
"""The starting point for a robot of your own: copy this file, fill in the four methods, and point the config at it. Everything else is shared with our robots: the control loop, the station, the safety caps, the dream client's IK and the wire to your fine-tune. Your driver only reads and writes one arm in the units of your arm's URDF (the one dream's IK solves with, the config's `custom.ik`): joints in radians with the URDF's zero and direction, the gripper from 0 closed to 1 open. If your motors count differently (degrees, ticks, another zero or direction), convert here. ```yaml body: custom custom: driver: my_arm.py:MyArm # this file, copied; or package.module:MyArm ik: makers # dream's name for your arm's URDF embodiment: <username>/<name> # the embodiment your fine-tune was trained on follower_l: {can_channel: /dev/ttyACM0, home: [0, 0, 0, 0, 0, 0]} follower_r: {can_channel: /dev/ttyACM1, home: [0, 0, 0, 0, 0, 0]} ``` `configs/custom.example.yaml` is a whole file. `dreamcli robot run --config <file> --task "..." --dry-run` reads your arms and logs their joints without writing a target, the first thing to try. Your gripper's range can be measured rather than coded: fill in TemplateArm.gripper_deg(), and `dreamcli setup` records each gripper closed and open by hand into its arm's `gripper_closed_deg` and `gripper_open_deg`, which `cfg` then hands your driver to map the gripper with. As shipped, #TemplateArm is an arm in memory: it reads back what it was last told. That is enough to run the whole stack with no robot attached. Two more things are yours to set. disengage() lets the arm go limp for the setup wizard's steps by hand; without it the arm is held stiff there. `drops_when_limp` says the arm has no brakes, which changes how a reset and a fault let it go (the attribute's comment below says how). close() and every path that disconnects must never command motion: the only move a driver makes on its own is torque_off() parking a brakeless arm, at a pose you chose. Mind this on a LeRobot robot (an SO-101 on its Feetech STS3215 bus, for one), where read() is `get_observation()`, whose `"<motor>.pos"` values you turn into radians, and write() is `send_action()` with targets turned back. A vendor's LeRobot plugin may home, rezero, power or move the arm in `connect()` and `disconnect()`: Seeed's `lerobot_robot_seeed_b601`, for one, may rezero every motor in `connect()` (`set_zero_position()`, when it finds no calibration file), enable them all and drive the gripper closed, and its `disconnect()` runs `safe_zero()`, moving the whole arm to its zero pose. Read the plugin's source before calling either; better, drive the motor SDK directly, or the plugin's lower-level bus without `connect()` and `disconnect()`. An arm reads and takes as many joints as its `home` in the config lists, 1 to `robots.followers.MAX_JOINTS` (`robots.followers.FollowerArm.dof`), and a read of another count fails naming the arm; the wire sends only the joints dream's spec of the arm drives. (The SO-101 ships as `body: so101`.) @see TemplateArm, robots.followers.Driver """ import numpy as np import numpy.typing as npt from robots import config, followers class TemplateArm(followers.Driver): """One arm, in memory: read() answers the last target, so the loop sees the arm reach every command at once. Replace each method's body with your robot's I/O; keep the signatures. """ ## True for an arm without brakes, which falls when its motors switch off. A reset then lets the arm go with ## torque_off() rather than close() (`FollowerArm.close_for_reopen()`), so torque_off() must park it first or it ## drops on every reset; an arm fault in a run holds the arms rather than disengaging them; and an arm that stops ## answering while it holds is reported as still holding under power, to be supported before its power goes off ## (`FollowerArm.holds_dead()`), where False reports it only as not answering. drops_when_limp = False def __init__(self, cfg: config.ArmConfig, side: str) -> None: """Opens one arm; the station calls this once per arm, and again after a reset. Open your bus or your LeRobot robot here, and leave the arm powered and holding where it is: the loop starts from what read() reports. @param cfg The arm's config section: `can_channel` is the device to open, `home` the arm's home joints. @param side `"left"` or `"right"`; while `dreamcli setup` is still finding which arm is which ("Find your arms"), the adapter's id instead, so per-side calibration cannot be looked up yet: open the arm to be read and moved by hand, and key anything per arm by `cfg.can_channel` or leave it until a side is known. """ # Setup's arm finding passes the adapter id, not a side. self._side = side if side in ("left", "right") else None self._positions_rad = np.array(cfg.home, dtype=np.float64) self._gripper = 1.0 self._is_limp = False def read(self) -> followers.Reading: """The arm's latest state; called every tick, so it should cost little. @return Joint positions and velocities `[dof]` (one per angle of the home) in radians and rad/s, and the gripper from 0 closed to 1 open. """ return followers.Reading(self._positions_rad.copy(), np.zeros_like(self._positions_rad), self._gripper) def write(self, positions_rad: npt.NDArray[np.float64], gripper: float) -> None: """Takes a new target, checked (finite, one per joint; a gripper in `[0, 1]`) and rate-capped by the loop. @param positions_rad A target per joint, `[dof]`, radians. @param gripper The gripper target, 0 closed to 1 open. """ if self._is_limp: # The first target after disengage() re-engages the arm holding where the hand left it, and is dropped. self._is_limp = False return self._positions_rad = positions_rad.copy() self._gripper = gripper def disengage(self) -> bool: """Lets the arm go limp where it is and keeps reading it; delete this if your arm has no passive mode. The setup wizard calls it so a hand can move the arm (finding the arms, home); without it (the default returns False) the arm is held stiff there instead. On your arm: switch the motors off, or to zero torque, and leave read() answering. The next write() must not jump to its target from wherever the hand left the arm: switch the motors on holding the pose they read now, and drop that first target. @return True once the arm is limp. """ self._is_limp = True return True def close(self) -> None: """Releases the device without moving the arm; the motors keep holding their last target if they can. Never through a call that moves the arm, as some vendors' `disconnect()` does. """ def torque_off(self) -> None: """Switches the motors off and releases the device; park the arm first if it would fall.""" def gripper_deg(self) -> float | None: """The gripper motor's angle as of the last read(), degrees, before read() maps it to 0 closed to 1 open. The setup wizard records it with each gripper closed, then opened, fully by hand, and saves the two angles as the arm's `gripper_closed_deg` and `gripper_open_deg`; `cfg` hands them to your driver, NaN until measured. Keep the angle read() saw (the wizard asks from its own thread) and map with the two: the gripper is `(deg - closed) / (open - closed)` in read() and `closed + gripper * (open - closed)` in write(); refuse to write while they are NaN. Return None if your driver keeps its gripper's range itself: the wizard then skips that step and says why. @return Degrees. The arm in memory has no gripper motor: None. """ return None
Our drivers as examples
Section titled “Our drivers as examples”These are the drivers the dream library ships for the robots we support. They import from the library’s robots package, which Setup API installs in ~/dream-env; the code is the library’s, with a few comments trimmed.
| File | Robot | How it talks to the arm |
|---|---|---|
yam.py |
i2rt YAM | wraps the i2rt SDK’s robot |
makers.py |
MakerMods Makers Arm | a table of RobStride motors for the shared bus-arm driver |
metal.py |
MakerMods Metal Arm | a table of Damiao motors for the shared bus-arm driver |
so101.py |
SO-101 | a table of Feetech servos on LeRobot’s bus |
The YAM
Section titled “The YAM”"""The i2rt YAM's driver: #I2rtDriver, a #robots.followers.Driver over an i2rt robot; the only module that knows i2rt. open_arm() opens one arm from its #robots.config.ArmConfig and carries the fleet's follower-process settings (end-effector mass, gravity compensation factor, SDK gripper force limiter, temperature export) onto the i2rt driver. The i2rt robot's joints are the YAM URDF's and its gripper is already 0 closed to 1 open, so the driver converts nothing: it reads the observation dict and sends the 7-vector command. Grip force is regulated a level up, by #robots.gripper_force. System 0 (#robots.sys0) writes the arm a level below that: write_motor_command() swaps in a whole MIT-mode block the way i2rt's own command methods do, and set_motor_loop_hook() runs a check on i2rt's motor loop before every update, which is where a stalled tracker is caught. open_arm(fast_motor_loop=True) opens the arm behind #robots.sys0.fast_loop, the faster i2rt transport the tracker was trained behind. @see open_arm(), I2rtDriver """ import logging from collections.abc import Callable from typing import Any import numpy as np import numpy.typing as npt from robots import config, errors, followers from robots.sys0 import fast_loop _log = logging.getLogger(__name__) ## Observation keys i2rt's `Robot.get_observations()` must carry for one read. _JOINT_POS_KEY = "joint_pos" _JOINT_VEL_KEY = "joint_vel" _GRIPPER_POS_KEY = "gripper_pos" ## Observation key i2rt's `MotorChainRobot` adds: the gripper motor's effort, in its torque units. Optional, ## because a driver without it (the test fakes) still reads. _GRIPPER_EFF_KEY = "gripper_eff" ## A YAM arm's joints; i2rt's command vector is these followed by one gripper value. JOINTS = 6 ## What `MotorChainRobot.update()` reads as "no gripper force limiter": it skips the limiter when the stored ## limit is `<= 0`, and `get_yam_robot` hardcodes 50 N otherwise. _SDK_GRIPPER_FORCE_LIMIT_OFF = -1.0 class I2rtDriver(followers.Driver): """A #robots.followers.Driver over an object with the i2rt `Robot` shape. The robot has `get_observations()` returning a dict with `joint_pos` `[6]`, `joint_vel` `[6]` and `gripper_pos` `[1]` (plus `gripper_eff` `[1]` when the driver has it), `command_joint_pos()` taking a `[7]` vector, and optionally `enter_gravity_comp_idle()` / `zero_torque_mode()`, a `motor_chain` with `running`, `channel` and `motor_list`, and `close()`. Attributes: - name: `"left"` or `"right"`, for messages. - robot: The i2rt robot. @see read(), write(), close(), torque_off(), is_alive(), disengage(), write_motor_command(), set_motor_loop_hook() """ def __init__(self, name: str, robot: Any) -> None: """Wraps an opened i2rt robot; nothing is commanded here. @param name `"left"` or `"right"`, for messages. @param robot The robot; see the class docstring. """ self.name = name self.robot = robot def read(self) -> followers.Reading: """One `get_observations()`. @return The reading; `gripper_effort` is i2rt's raw `gripper_eff` when it reports one, else None. @throws ArmError The observation lacks six joints or a gripper value. """ observation = self.robot.get_observations() return followers.Reading( positions_rad=_joint_vector(self.name, observation, _JOINT_POS_KEY), velocities_rad_s=_joint_vector(self.name, observation, _JOINT_VEL_KEY), gripper=_scalar_value(self.name, observation, _GRIPPER_POS_KEY), gripper_effort=( None if _GRIPPER_EFF_KEY not in observation else _scalar_value(self.name, observation, _GRIPPER_EFF_KEY) ), ) def write(self, positions_rad: npt.NDArray[np.float64], gripper: float) -> None: """Sends `[*positions_rad, gripper]` as one `command_joint_pos()`. @param positions_rad Six joint targets, radians. @param gripper The gripper target, 0 closed to 1 open. """ self.robot.command_joint_pos(np.append(positions_rad, gripper)) def is_alive(self) -> bool: """False when i2rt's motor chain has stopped, which i2rt otherwise hides. i2rt's CAN thread clears `robot.motor_chain.running` and exits when a motor stops answering, but `get_observations()` keeps returning the last state and `command_joint_pos()` keeps accepting targets, so a loop would run blind on a dead arm (seen on a station: 36 s of ticks after the bus died). A robot without the flag (the test fakes) is taken as alive. @return False once i2rt's motor chain stopped. """ chain = getattr(self.robot, "motor_chain", None) return chain is None or getattr(chain, "running", True) is not False def why_stopped(self) -> str: """Why is_alive() is False: i2rt's motor chain stopped, which it does when a motor stops answering. @return The reason. """ return "its motor chain is no longer running (a motor stopped answering on the CAN bus)" def close(self) -> None: """Stops i2rt's threads and closes the CAN channel; it sends nothing, so the motors keep their last target. A robot without `close()` (the test fakes, a sim robot) is left alone. """ close = getattr(self.robot, "close", None) if close is not None: close() def torque_off(self) -> None: """Closes the robot, then switches every motor on its chain off, so the arm goes limp. What close() leaves out: i2rt's `MotorChainRobot.close()` stops its thread and shuts the CAN socket without sending a frame, and a DM motor keeps the last MIT target it was given when the bus goes quiet (the firmware CAN timeout is 0 on the fleet's motors), so a closed arm stays stiff until its power is cut. This sweep fixes that: the chain's channel and motor ids are read before close() shuts the bus, then _switch_off_motors() sends the DM disable command to each id over an interface of its own. A robot without a motor chain (a sim robot, the test fakes) is only closed. The arm drops under gravity from wherever it was. @throws Exception Whatever i2rt raises when the channel cannot be opened for the sweep; the robot is closed by then. A motor that does not answer is logged and skipped, and once every other motor is off an ArmError names it. """ chain = getattr(self.robot, "motor_chain", None) channel = getattr(chain, "channel", None) motor_ids = [int(entry[0]) for entry in getattr(chain, "motor_list", [])] self.close() if channel is None or not motor_ids: return _switch_off_motors(self.name, channel, motor_ids) def write_motor_command( self, target: npt.NDArray[np.float64], kp: npt.NDArray[np.float64], kd: npt.NDArray[np.float64], torque: npt.NDArray[np.float64], ) -> None: """Swaps in one whole MIT-mode block: the six joints' targets, gains and torques, the gripper's position. The block is what i2rt's motor loop sends every cycle, with gravity compensation added to the torque; it is replaced under the robot's command lock as `command_joint_pos()` replaces it. The gripper keeps the robot's own gains. @param target Position targets, `[7]`: six joints in radians, then the gripper in `[0, 1]`. @param kp Stiffness per joint, `[6]`. @param kd Damping per joint, `[6]`. @param torque Torque per joint on top of gravity compensation, `[6]`, newton metres. @throws ArmError The robot has no MIT command block (not an i2rt `MotorChainRobot`). """ robot = self.robot if not _has_command_block(robot): raise errors.ArmError(f"arm '{self.name}': the driver has no MIT command block to write") count = len(robot.motor_chain) # i2rt's JointCommands, taken from the block in place rather than imported on every 4 ms write. block = type(robot._commands).init_all_zero(count) block.pos = robot.remapper.to_robot_joint_pos_space(robot._clip_robot_joint_pos_command(np.array(target))) block.kp = np.concatenate([kp, np.asarray(robot._kp, dtype=np.float64)[JOINTS:]]) block.kd = np.concatenate([kd, np.asarray(robot._kd, dtype=np.float64)[JOINTS:]]) block.torques = np.concatenate([torque, np.zeros(count - JOINTS)]) with robot._command_lock: robot._commands = block def set_motor_loop_hook(self, hook: Callable[[], None] | None) -> None: """Runs `hook` on i2rt's motor loop before every update, or removes it. i2rt's loop calls the robot's `update()` every cycle; the hook wraps it on the instance, so removing it leaves the robot's own method. A robot without the loop (the test fakes, a sim robot) takes no hook. @param hook A fast check to run before each update, or None to remove the one installed. """ robot = self.robot if hook is None: robot.__dict__.pop("update", None) return update = getattr(type(robot), "update", None) if update is None: return def hooked_update() -> None: hook() update(robot) robot.update = hooked_update def disengage(self) -> bool: """The fleet's follower release: gravity compensation, else zero torque. Under gravity compensation the arm floats where it is without fighting the operator; under zero torque it sags. @return False when the robot offers neither: the wrapper holds it. """ for method in ("enter_gravity_comp_idle", "zero_torque_mode"): release = getattr(self.robot, method, None) if release is not None: release() return True return False def open_arm(cfg: config.ArmConfig, name: str, *, fast_motor_loop: bool = False) -> followers.FollowerArm: """Opens the CAN channel named by the config, applies its driver settings and wraps the robot. i2rt is imported here and nowhere else, so the rest of the package (and every test) runs without the hardware extra installed. `ee_mass_kg` goes into `get_yam_robot` (its gravity model needs it before the first torque); the other settings are attributes set on the built robot, see _configure_driver(). @param cfg Arm config: CAN channel, gripper type, the driver settings and the home pose. @param name `"left"` or `"right"`, for messages. @param fast_motor_loop Run i2rt's motor loops faster (#robots.sys0.fast_loop), which System 0 was trained behind; patched in before the robot starts its threads. @return A #robots.followers.FollowerArm over an #I2rtDriver. @throws ConfigError Its home does not list #JOINTS angles, or i2rt is not importable. """ if len(cfg.home) != JOINTS: raise errors.ConfigError( f"arm '{name}': its home in the config lists {len(cfg.home)} angles, but a YAM arm has {JOINTS} joints" ) try: # i2rt is not on PyPI, so it is an optional extra and mypy cannot see it either. from i2rt.robots.get_robot import get_yam_robot # type: ignore[import-not-found] from i2rt.robots.utils import GripperType # type: ignore[import-not-found] except ImportError as exc: raise errors.ConfigError( f"follower '{name}' needs i2rt, which is not installed; the dream library brings it: " "pip install --upgrade dreamlabs" ) from exc if fast_motor_loop: fast_loop.install_before_robot() robot = get_yam_robot( channel=cfg.can_channel, gripper_type=GripperType(config.i2rt_gripper(cfg.gripper)), ee_mass=cfg.ee_mass_kg ) _configure_driver(name, robot, cfg) if fast_motor_loop: fast_loop.install_pipelined_bus(robot) _log.info("arm '%s': fast motor loop on %s", name, cfg.can_channel) return followers.FollowerArm(name, I2rtDriver(name, robot), home_rad=cfg.home) def _configure_driver(name: str, robot: Any, cfg: config.ArmConfig) -> None: """Sets the driver attributes the fleet's follower process sets, from the arm config. Each is guarded with `hasattr` as the fleet does, because `get_yam_robot` can return a driver class without it (a sim robot, another i2rt version) and a missing attribute must not stop the arm from opening; the one that matters for safety is logged when missing. - `temp_record_flag` (`temp_export`): i2rt reads every motor's temperatures anyway; the flag only gates their export in `get_observations()`. - `gravity_comp_factor`: i2rt stores a per-joint array (one entry per motor, gripper included) and multiplies it into the gravity torques on every update; the fleet overwrites it with one scalar, which numpy broadcasts over every joint. The config value is that scalar; None leaves i2rt's per-joint defaults. - `_limit_gripper_force` (`sdk_gripper_force_limit`): `get_yam_robot` hardcodes a 50 N `GripperForceLimiter` (clog detect, then hold), and `update()` skips it when the stored limit is `<= 0`. The fleet turns it off and regulates grip force in its own control loop instead, because the two fight (the SDK's clog threshold sits right at a low cap and its hold level above it), which shows up as a jittery grasp. The loop-side cap is #robots.gripper_force.GripperForceCap here, on by default; `sdk_gripper_force_limit: true` puts the SDK's limiter back, for a station running with `grip_force_cap: 0`. @param name `"left"` or `"right"`, for messages. @param robot The driver `get_yam_robot` returned. @param cfg The arm config carrying the settings. """ if cfg.temp_export and hasattr(robot, "temp_record_flag"): robot.temp_record_flag = True if cfg.gravity_comp_factor is not None and hasattr(robot, "gravity_comp_factor"): robot.gravity_comp_factor = cfg.gravity_comp_factor if cfg.sdk_gripper_force_limit: return if hasattr(robot, "_limit_gripper_force"): robot._limit_gripper_force = _SDK_GRIPPER_FORCE_LIMIT_OFF else: _log.warning("arm '%s': driver has no _limit_gripper_force; the SDK gripper force limiter stays on", name) def _switch_off_motors(name: str, channel: str, motor_ids: list[int]) -> None: """Sends the DM disable command to each motor on a channel, over an interface opened and closed here. Its own interface, after the driver has closed its bus, because the window inside i2rt's close (thread joined, socket still open) is not reachable from outside it; the few milliseconds between the two cost nothing, since the motors were holding indefinitely anyway. Best effort per motor: one that does not answer (i2rt gives up after its five retries) is logged and skipped so it cannot leave the others energized, and the error raised at the end names the ids that may still be live. @param name `"left"` or `"right"`, for the log lines. @param channel The arm's CAN link. @param motor_ids The chain's motor ids, in chain order. """ # i2rt is imported here as in open_arm(): the extra is optional and mypy cannot see it. from i2rt.motor_drivers.dm_driver import DMSingleMotorCanInterface # type: ignore[import-not-found] interface = DMSingleMotorCanInterface(channel=channel) failed: list[int] = [] try: for motor_id in motor_ids: try: interface.motor_off(motor_id) except Exception: # The one broad except: the sweep must reach every motor whatever one of them does. _log.exception("arm '%s': motor %d on %s did not switch off", name, motor_id, channel) failed.append(motor_id) finally: interface.close() if failed: raise errors.ArmError( f"arm '{name}': motors {failed} on {channel} may still be energized; cut the arm's power" ) _log.info("arm '%s': motors %s on %s switched off", name, motor_ids, channel) def _has_command_block(robot: Any) -> bool: """Whether the robot is an i2rt `MotorChainRobot`, with the command block write_motor_command() swaps.""" return all( hasattr(robot, attr) for attr in ("_commands", "_command_lock", "remapper", "motor_chain", "_kp", "_kd") ) def _joint_vector(name: str, observation: Any, key: str) -> npt.NDArray[np.float64]: """Pulls one `[6]` float64 vector out of a driver observation. @param name Arm name, for the message. @param observation The dict returned by `get_observations()`. @param key Which entry to read. @return The vector as float64. @throws ArmError If the entry is missing or not six values long. """ if not isinstance(observation, dict) or key not in observation: raise errors.ArmError(f"arm '{name}' observation lacks '{key}'") vector = np.asarray(observation[key], dtype=np.float64).reshape(-1) if vector.shape != (JOINTS,): raise errors.ArmError(f"arm '{name}' observation '{key}' has {vector.size} values, expected {JOINTS}") return vector def _scalar_value(name: str, observation: Any, key: str) -> float: """Pulls a single-valued entry (the gripper position or effort) out of a driver observation. @param name Arm name, for the message. @param observation The dict returned by `get_observations()`. @param key Which entry to read. @return The value as a float. @throws ArmError If the entry is missing or does not hold exactly one value. """ if not isinstance(observation, dict) or key not in observation: raise errors.ArmError(f"arm '{name}' observation lacks '{key}'") value = np.asarray(observation[key], dtype=np.float64).reshape(-1) if value.size != 1: raise errors.ArmError(f"arm '{name}' observation '{key}' has {value.size} values, expected 1") return float(value[0])
The Makers Arm
Section titled “The Makers Arm”"""A MakerMods Makers Arm, as a table for #robots.motor_arm; the only module that knows the Makers Arm. The Makers Arm is the vendor's brakeless arm on seven RobStride motors (six joints and the gripper), one CAN adapter per arm. Its driver is the shared bus-arm thread (#robots.motor_arm.MotorArm) over a #robots.robstride.RobstrideChain, with every safety check of our original Makers Arm driver. Not ported: teleoperation and the Star leaders, calibration (setting the motors' zero), the adapter reopen after an I/O failure (here an adapter that fails latches the arm down, and the station's Reset reopens it), and the raw-USB candleLight transport (#robots.robstride says why). Units: joints are the turn-corrected motor angles in radians with no sign flip, the frame the Makers datasets were recorded in and dream's IK model reads (`dream_ik`'s `maker_arm_ik.urdf`). The gripper's stroke runs from 0 closed to #GRIPPER_MAX_MM open, linear in the motor angle between the config's `gripper_closed_deg` and `gripper_open_deg`. @see ARM, JOINTS """ from collections.abc import Callable from typing import Any from robots import config, motor_arm, robstride ## The six joints, base to wrist, the same on both arms: name, CAN id, motor model (RS02 `"O1"` on the shoulder lift ## and the elbow, RS00 `"O0"` elsewhere), the vendor's bench MIT `kp` and `kd`, and soft limits in degrees from the ## folded calibration pose (the vendor's mechanical-stop capture). JOINTS = ( motor_arm.Joint("shoulder_pan", 1, "O0", 60.0, 4.0, (-158.2, 156.1)), motor_arm.Joint("shoulder_lift", 2, "O1", 150.0, 4.5, (-175.3, -3.2)), motor_arm.Joint("elbow_flex", 3, "O1", 90.0, 3.0, (2.8, 236.1)), motor_arm.Joint("wrist_flex", 4, "O0", 30.0, 2.0, (-65.2, 104.0)), motor_arm.Joint("wrist_yaw", 5, "O0", 30.0, 2.0, (-97.6, 78.0)), motor_arm.Joint("wrist_roll", 6, "O0", 30.0, 2.0, (-153.2, 152.0)), ) ## The gripper's stroke, mm: the Makers gripper is recorded in it, and the loop's 0..1 is its fraction. GRIPPER_MAX_MM = 80.0 def _gripper(cfg: config.ArmConfig) -> motor_arm.Joint: """The gripper's motor: CAN id 7, its `kp` low so grip force stays compliant, its soft limits the stroke's ends.""" return motor_arm.Joint("gripper", 7, "O0", 20.0, 0.5, (cfg.gripper_open_deg, cfg.gripper_closed_deg)) def _chain( side: str, cfg: config.ArmConfig, *, opener: Callable[[str], Any], clock: Callable[[], float], sleep: Callable[[float], Any], ) -> robstride.RobstrideChain: """The arm's RobStride motors, the gripper through its hold (`gripper_hold_torque_nm`).""" joints = (*JOINTS, _gripper(cfg)) return robstride.RobstrideChain( side, cfg.can_channel, joints, cfg.gripper_hold_torque_nm, opener=opener, clock=clock, sleep=sleep ) ## The Makers Arm: a 60 Hz policy tick, parked before torque-off at its folded calibration pose ## (every joint at zero) at 30 deg/s (the vendor's MAKER_RETURN_SPEED_DEG_S), the gripper open. ARM = motor_arm.ArmSpec( name="makers", ik="makers", tick_hz=60.0, rest_speed_deg_s=30.0, rest_rad=(0.0,) * 6, grip_scale_mm=GRIPPER_MAX_MM, grip_margin_mm=2.0, temp_warn_c=55.0, temp_stop_c=65.0, chain=_chain, )
The Metal Arm
Section titled “The Metal Arm”"""A MakerMods Metal arm, as a table for #robots.motor_arm; the only module that knows the Metal arm. The Metal arm is MakerMods' brakeless arm on seven Damiao motors (six joints and the gripper), one CAN adapter per arm. Its driver is the shared bus-arm thread (#robots.motor_arm.MotorArm) over a #robots.damiao.DamiaoChain, which is MakerMods' own follower for it, from the control loop they run policies on it with, with every check it makes. The gripper is #robots.metal_gripper. Not ported: teleoperation, calibration (setting the motors' zero), the console's planner, its tracking-error check (the park before torque-off has the shared thread's stall and time limits instead), and the gripper's current-limited mode and holding thread (#robots.metal_gripper says why). Units: joints are the motor angles in radians, sign +1, no offset: MakerMods' frame, which is dream's Metal IK model (`dream_ik`'s Metal URDF, whose limits are these to the degree). The gripper runs linearly in its motor angle from the arm's `gripper_closed_deg` (0) to its `gripper_open_deg` (#GRIP_SCALE_MM, the loop's 1.0), both required and recorded per arm by the setup wizard. The loop's gripper is the Metal grip, the stroke in mm over #GRIP_SCALE_MM, what dream's Metal fine-tunes read and answer. Calibration: MakerMods' LeRobot calibration file carries nothing a driver reads. Their follower checks only that one exists (its homing offsets are 0, its ranges the soft limits); the zero lives in the motors, stored by LeRobot's calibration with the arm at its zero pose (upright, every joint at 0, the gripper closed). An arm needs its motors zeroed at that pose, and no file. @see ARM, JOINTS """ import math from collections.abc import Callable from typing import Any import numpy as np import numpy.typing as npt from robots import config, damiao, errors, metal_gripper, motor_arm ## The seven motors, base to gripper, the same on both arms: name, CAN id, Damiao motor model (#robots.damiao ## .MOTOR_LIMITS: MakerMods flash each with the ranges of its joint), MakerMods' follow `kp` and `kd`, and soft limits ## in degrees from the zero pose (the vendor's motor configuration). Every joint also carries #gravity_nm, as ## MakerMods' SDK follower does: with no gravity torque the shoulder sat 0.1 rad under its target and a lifted ## hand stayed on the table. Their SDK's stiffer gains are not taken: they go with its 120 Hz smoothed command stream, ## and on this 30 Hz tick they made the arm jerky. JOINTS = ( motor_arm.Joint("shoulder_pan", 1, "metal_jlo", 100.0, 5.0, (-160.0, 160.0)), motor_arm.Joint("shoulder_lift", 2, "metal_j2", 100.0, 5.0, (-180.0, 0.0)), motor_arm.Joint("elbow_flex", 3, "metal_jlo", 100.0, 5.0, (0.0, 180.0)), motor_arm.Joint("wrist_flex", 4, "metal_jlo", 50.0, 5.0, (-123.0, 81.0)), motor_arm.Joint("wrist_yaw", 5, "metal_jhi", 20.0, 0.6, (-85.0, 85.0)), motor_arm.Joint("wrist_roll", 6, "metal_jhi", 20.0, 0.6, (-145.0, 145.0)), motor_arm.Joint(metal_gripper.NAME, 7, "metal_jhi", 20.0, 0.6, metal_gripper.LIMITS_DEG), ) ## The arm's links for #gravity_nm, from MakerMods' `metal_with_gripper.urdf` (the SDK's): per joint, base to wrist, ## its origin in the link before it (xyz m, rpy rad), its axis, and the link it turns: mass kg, centre of mass m. LINKS = ( ((0.0, 0.0, 0.06675), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 0.893, (0.000693, -0.001221, 0.050197)), ((0.00075, 0.0, 0.055), (1.5708, 0.0, 0.0), (0.0, 0.0, 1.0), 1.028, (-0.185969, -0.001045, -0.000524)), ((-0.28, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 0.838, (0.13281, 0.052976, -0.000025)), ((0.215, 0.063, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), 0.444, (0.067326, 0.059806, 0.005043)), ((0.080817, 0.05072, 0.00025), (1.5708, 0.0, -0.015918), (0.0, 0.0, 1.0), 0.363, (0.002596, 0.000018, 0.039895)), ((0.0235, 0.0, 0.044), (-3.14159265330655, 0.0, 0.0), (1.0, 0.0, 0.0), 0.667, (0.05958, 0.0, -0.006779)), ) ## The SDK's factor on each joint's gravity torque (KdlSolver::FeedforwardTorqueCompensation). GRAVITY_FACTORS = (1.2, 1.15, 1.1, 1.15, 1.0, 1.0) GRAVITY_M_S2 = 9.81 ## The Metal grip, the loop's gripper unit and the one dream's Metal fine-tunes read and answer in, is the stroke in ## mm divided by this. GRIP_SCALE_MM = 100.0 def _rotation(axis: npt.NDArray[np.float64], angle: float) -> npt.NDArray[np.float64]: """The rotation by `angle` rad about the unit `axis` (Rodrigues). @param axis The unit axis, 3 numbers. @param angle The angle, radians. @return The 3x3 rotation matrix. """ k = np.array([[0.0, -axis[2], axis[1]], [axis[2], 0.0, -axis[0]], [-axis[1], axis[0], 0.0]]) rotation: npt.NDArray[np.float64] = np.eye(3) + math.sin(angle) * k + (1.0 - math.cos(angle)) * k @ k return rotation def _rpy(roll: float, pitch: float, yaw: float) -> npt.NDArray[np.float64]: """A URDF origin's rotation: yaw about z, then pitch about y, then roll about x, fixed axes. @param roll About x, radians. @param pitch About y, radians. @param yaw About z, radians. @return The 3x3 rotation matrix. """ x, y, z = np.eye(3) rotation: npt.NDArray[np.float64] = _rotation(z, yaw) @ _rotation(y, pitch) @ _rotation(x, roll) return rotation def gravity_nm(q_deg: tuple[float, ...]) -> tuple[float, ...]: """The torque each joint holds the arm against gravity with, times the SDK's #GRAVITY_FACTORS. Per joint: its axis dotted with the moment of the weights of every link it carries. @param q_deg The arm's joints, degrees, base to wrist. @return Per joint, base to wrist, its gravity torque, N.m. """ rotation, origin = np.eye(3), np.zeros(3) axes, pivots, weights = [], [], [] for (xyz, rpy, axis, mass, com), angle in zip(LINKS, q_deg, strict=True): origin = origin + rotation @ np.asarray(xyz) rotation = rotation @ _rpy(*rpy) axes.append(rotation @ np.asarray(axis)) pivots.append(origin) rotation = rotation @ _rotation(np.asarray(axis), math.radians(angle)) weights.append((origin + rotation @ np.asarray(com), mass * GRAVITY_M_S2 * np.array([0.0, 0.0, 1.0]))) return tuple( factor * float(sum(axes[i] @ np.cross(com - pivots[i], weight) for com, weight in weights[i:])) for i, factor in enumerate(GRAVITY_FACTORS) ) def _chain( side: str, cfg: config.ArmConfig, *, opener: Callable[[str], Any], clock: Callable[[], float], sleep: Callable[[float], Any], ) -> damiao.DamiaoChain: """The arm's Damiao motors, the gripper holding at `gripper_hold_torque_nm`. @throws ConfigError The config has no hold torque. """ del sleep hold_torque_nm = cfg.gripper_hold_torque_nm if hold_torque_nm is None: raise errors.ConfigError(f"arm '{side}': a Metal arm's gripper always holds; set gripper_hold_torque_nm") gripper = JOINTS[-1] def build_gripper(bus: damiao.DamiaoBus) -> metal_gripper.MetalGripper: return metal_gripper.MetalGripper( bus, gains=(gripper.kp, gripper.kd), hold_torque_nm=hold_torque_nm, clock=clock ) return damiao.DamiaoChain( side, cfg.can_channel, JOINTS, build_gripper, gravity=gravity_nm, opener=opener, clock=clock ) ## The Metal arm: 30 Hz (the Metal datasets' rate), parked before torque-off where it was opened, at 15 deg/s ## (MakerMods' console), the gripper open: its zero pose stands straight up, which is no place to go limp. ARM = motor_arm.ArmSpec( name="metal", ik="metal", tick_hz=30.0, rest_speed_deg_s=15.0, rest_rad=None, grip_scale_mm=GRIP_SCALE_MM, grip_margin_mm=2.0, temp_warn_c=55.0, temp_stop_c=65.0, chain=_chain, )
The SO-101
Section titled “The SO-101”"""An SO-101 arm, as a table for #robots.motor_arm; the only module that knows the SO-101. The SO-101 (The Robot Studio and LeRobot's arm) has five joints and a gripper on six Feetech STS3215 servos, one serial bus per arm. Its driver is the shared bus-arm thread (#robots.motor_arm.MotorArm) over a #robots.feetech.FeetechChain on LeRobot's own Feetech bus (the `so101` extra), with the checks, rates and gains of our original SO-101 follower. Units: joints in radians in the URDF's frame (dream's `so101_faas` model, one URDF per side), 0 at the LeRobot calibration's middle pose (#robots.feetech says why that holds on every calibrated arm). The arm fills the loop's first five joint slots; the sixth reads 0, where dream's IK holds the model's dummy sixth joint. The gripper runs linearly between the ends of its calibrated range, closed at `range_min` (the model's 0) and open at `range_max` (1): LeRobot's 0 to 100 gripper, the unit the checkpoint reads and the dream client makes from the grip. Calibration: each arm's own LeRobot calibration file (`calibration` in the config, written by `lerobot-calibrate` with the arm in its middle pose). An arm whose servos hold another calibration than the file does not start. @see ARM, JOINTS """ import pathlib from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, Any from robots import errors, feetech, motor_arm if TYPE_CHECKING: # Annotations only: config reads the gripper's ends from here. from robots import config ## The servo's whole turn, degrees: a joint's limits are its calibrated range (#robots.feetech.FeetechChain). _FULL_TURN_DEG = (-180.0, 180.0) ## The six servos, base to gripper, the same on both arms: name (LeRobot's), id, model, and the P and D registers ## LeRobot's SO-101 follower sets (16 and 32: its default P of 32 shakes). JOINTS = ( motor_arm.Joint("shoulder_pan", 1, "sts3215", 16.0, 32.0, _FULL_TURN_DEG), motor_arm.Joint("shoulder_lift", 2, "sts3215", 16.0, 32.0, _FULL_TURN_DEG), motor_arm.Joint("elbow_flex", 3, "sts3215", 16.0, 32.0, _FULL_TURN_DEG), motor_arm.Joint("wrist_flex", 4, "sts3215", 16.0, 32.0, _FULL_TURN_DEG), motor_arm.Joint("wrist_roll", 5, "sts3215", 16.0, 32.0, _FULL_TURN_DEG), motor_arm.Joint("gripper", 6, "sts3215", 16.0, 32.0, _FULL_TURN_DEG), ) ## The gripper's 0..1 as LeRobot's 0..100, the unit the thread ramps it in. GRIP_SCALE = 100.0 def gripper_ends(calibration_path: str) -> tuple[float, float]: """The gripper's ends from an arm's calibration file, for the config's `gripper_open_deg` and `gripper_closed_deg`. @param calibration_path The arm's LeRobot calibration file. @return `(open_deg, closed_deg)`: the calibrated range's high and low end. @throws ConfigError The file does not fit the arm (#robots.feetech.read_calibration). """ gripper = feetech.read_calibration(calibration_path, JOINTS)[JOINTS[-1].name] return feetech.ticks_to_deg(gripper.range_max), feetech.ticks_to_deg(gripper.range_min) def calibration_for(port: str, files: Sequence[str]) -> str: """Which of the operator's calibration files an arm's servos hold, read once from their EEPROM. @param port The arm's serial device. @param files The calibration files to choose from. @return The first file the servos agree with. """ held = feetech.held_calibration(port, JOINTS) for path in files: if not feetech.calibration_differences(feetech.read_calibration(path, JOINTS), held): return path names = ", ".join(pathlib.Path(path).name for path in files) raise errors.ArmError( f"none of your calibration files ({names}) is this arm's: its servos hold other homing offsets and ranges. " "Calibrate this arm with lerobot-calibrate, add the file it writes in step 0, then look again" ) def _chain( side: str, cfg: "config.ArmConfig", *, opener: Callable[..., Any], clock: Callable[[], float], sleep: Callable[[float], Any], ) -> feetech.FeetechChain: """The arm's servos on its serial port, with its calibration file. @throws ConfigError The config names no calibration file. """ if cfg.calibration is None: raise errors.ConfigError(f"arm '{side}': an SO-101 needs its LeRobot calibration file ('calibration')") return feetech.FeetechChain( side, cfg.can_channel, JOINTS, cfg.calibration, opener=opener, clock=clock, sleep=sleep ) ## The SO-101: a 60 Hz bus rate, parked before torque-off where it was opened (its middle pose ## stands up, which is no place to go limp) at 20 deg/s, the gripper open. ARM = motor_arm.ArmSpec( name="so101", ik="so101_faas", tick_hz=60.0, rest_speed_deg_s=20.0, rest_rad=None, grip_scale_mm=GRIP_SCALE, grip_margin_mm=3.0, temp_warn_c=50.0, temp_stop_c=60.0, chain=_chain, )