# Python SDK: complete text > Drive Asimov from Python. Every page under (15 pages) as Markdown, in sidebar order. Pages are separated by `---` lines and start with their own `#` title. Index of all docs: --- # Overview > menlo-sdk: walking, joint control, robot state, camera and audio for Asimov 1 from Python. - Page: https://docs.menlo.ai/sdk - Section: Python SDK `menlo-sdk` is the Python SDK for Menlo robots, and supports Asimov 1. It drives the robot with the robot's own verbs, `stand`, `set_velocity`, `damp` and `trajectory`, plus two the SDK adds: `balance` and `set_joints`. The package is `menlo`; the robot is the `menlo.asimov` subpackage. It is on [PyPI](https://pypi.org/project/menlo-sdk/) and its source is on [GitHub](https://github.com/menloresearch/menlo-sdk). Everything the SDK sends passes through the same arbiter and safety layer on the robot as the Drive Robot page and the gamepad; nothing in it bypasses the robot. > [!WARNING] > > **Before the robot walks** > > For a first run, hang the robot from its gantry hook with both feet on the floor and give it > 2 m of clear floor ahead. Nothing in the SDK is an emergency stop: keep the E-Stop in Asimov > Manager open, or be ready to cut power at the battery unit. Read [Safety](https://docs.menlo.ai/sdk/safety.md) first. ## Try It Each script below runs on a simulated Asimov 1: press **Run** and the robot opens in the corner of the page. Run them in order, Stand, then Balance, then Walk, as on a real robot. **Stand:** ```python # guard(robot) # optional: uncomment this and the import to stop on your rule try: # Returns once the robot reports STAND and has been upright for 0.5 s (armed): the # firmware enters MOVE only after that. robot.stand() except (NotReadyError, WaitTimeoutError) as exc: # no live state, a fault, or not armed print(exc) # what the robot reports and what to do sys.exit(1) print(f"robot mode {robot.get_state().mode.name}, armed {robot.armed}") ``` From `examples/stand.py` in the menlo-sdk repository (the excerpt the page shows). **Balance:** ```python # guard(robot) # optional: uncomment this and the import to stop on your rule try: robot.balance() # returns once the robot reports MOVE except (NotReadyError, WaitTimeoutError) as exc: # no live state, a fault, or not MOVE print(exc) # what the robot reports and what to do sys.exit(1) print(f"robot mode {robot.get_state().mode.name}, balancing in place") ``` From `examples/balance.py` in the menlo-sdk repository (the excerpt the page shows). **Walk:** ```python # guard(robot) # optional: uncomment this and the import to stop on your rule mode = robot.get_state().mode if mode is not Mode.MOVE: # this script's own rule: walk from MOVE only print(f"robot mode {mode.name}: walk.py walks in MOVE only; run balance.py first") sys.exit(1) try: # Held and re-sent at 10 Hz for DURATION_S, then zero velocity; returns after that. sent = robot.set_velocity(vx=VX, vy=VY, vyaw=VYAW, duration=DURATION_S) except NotReadyError as exc: # no live state (nothing sent), or a fault ended the walk print(exc) sys.exit(1) if sent.clamped: print("the SDK reduced the speed to the robot's limits:", sent.command) print(f"robot mode {robot.get_state().mode.name}, balancing in place") ``` From `examples/walk.py` in the menlo-sdk repository (the excerpt the page shows). **Read state:** ```python # robot.get_state() is the latest sample the robot sent. It is a snapshot: read it again # for newer values. A field the robot does not report is None, never a guess. s = robot.get_state() # Robot mode: DAMP (no actuator holds a position), STAND (a held standing pose, no # balance) or MOVE (the walking policy balances the robot, at zero or any velocity). print(f"robot mode {s.mode.name}") # Armed: the firmware accepts MOVE only after STAND has been held upright for 0.5 s. # None means the SDK cannot tell (no gravity vector reported). print(f"armed {robot.armed}") # Faulted: a critical alert latched DAMP. The robot stays in DAMP, and error_flags stay # set, until the firmware restarts. The preflight check names what latched. print(f"faulted {s.faulted}") for problem in robot.preflight("stand").problems: if problem.code == "faulted": print(f" {problem.message}") # Battery, from the battery management system. None when the robot reports none. if s.battery is not None: b = s.battery print( f"battery {b.soc_percent:.0f} %, {b.voltage_v:.1f} V, {b.current_a:+.1f} A, " f"warmest cell {b.max_cell_temp_c:.0f} °C, protecting {b.protecting}" ) else: print("battery not reported") # Actuators: one Joint per actuator, with the firmware's name, position (rad), velocity # (rad/s), current (A) and temperature (°C). The firmware warns at 60 °C and latches # DAMP at 80 °C. temps = sorted(((j.temp, j.name) for j in s.joints if j.temp is not None), reverse=True) if temps: hottest = ", ".join(f"{name} {temp:.0f} °C" for temp, name in temps[:HOTTEST]) print(f"hottest {hottest}") else: print("hottest actuator temperatures not reported") # IMU: gravity as the body sees it. z is close to -1 when the robot is upright; # upright is True below -0.8. euler is (roll, pitch, yaw) in rad from the IMU quaternion. if s.gravity is not None: gx, gy, gz = s.gravity print(f"gravity ({gx:+.2f}, {gy:+.2f}, {gz:+.2f}), upright {s.upright}") if s.euler is not None: roll, pitch, yaw = s.euler print(f"orientation roll {roll:+.2f}, pitch {pitch:+.2f}, yaw {yaw:+.2f} rad") # Alerts the firmware reports now. Severity 0 is critical: it latches DAMP. alerts = [f"{a.name}{' (critical)' if a.critical else ''}" for a in s.alerts] print(f"alerts {', '.join(alerts) or 'none'}") # Freshness: how old the sample is. Decisions to move are made on samples at most # 0.5 s old; robot.preflight() reports stale_state beyond that. print(f"state age {s.age_s * 1000:.0f} ms") # The same fields as a stream, a few times a second. for _ in range(STREAM_LINES): time.sleep(STREAM_PERIOD_S) s = robot.get_state() now = time.monotonic() rate = sum(1 for t in tuple(arrivals) if now - t <= 1.0) battery = f"{s.battery.soc_percent:.0f} %" if s.battery else "n/a" print( f"{s.mode.name:5} armed {robot.armed} upright {s.upright} faulted {s.faulted} " f"battery {battery} age {s.age_s * 1000:.0f} ms rate {rate:.0f} Hz" ) ``` From `examples/read_state.py` in the menlo-sdk repository (the excerpt the page shows). **Camera and audio:** ```python if robot.has("camera"): photo = robot.camera.photo() # the next fresh frame, rgb8 Path(PHOTO).write_bytes(photo.to_jpeg()) print(f"saved {PHOTO}, {photo.width}x{photo.height}") clip = robot.camera.capture_clip(CLIP_S, audio=robot.has("microphone")) frames = clip.save_frames(CLIP_DIR) print(f"saved {len(frames)} frames to {CLIP_DIR}/ at {clip.fps:.1f} fps") if clip.audio: print("saved", clip.save_wav(CLIP_WAV)) else: print("this connection carries no camera; use hybrid or livekit") if robot.has("speaker"): # 16-bit mono PCM: a sine wave at TONE_HZ for TONE_S. tone = b"".join( struct.pack(" What to check before a script runs, how to stand, balance and rest the robot, what to do when something goes wrong, what the SDK, the robot and the firmware each stop, what the SDK reports, and how to write your own guard. - Page: https://docs.menlo.ai/sdk/safety - Section: Python SDK The SDK is a client of the robot. It sends what you ask, bounded by your limits, and reads back what the robot reports. Safety is the firmware's job, command handling is the robot's, and a guard is your script's: the SDK does not refuse a command because of what the robot reports. When in doubt, open Asimov Manager and press the E-Stop. ## Before You Run a Script 1. **Support the robot**, as [Supporting the Robot](https://docs.menlo.ai/asimov/1/operate/safety.md#supporting-the-robot) describes: hanging from its gantry hook with both feet on the floor for a first stand and walk, hanging from its gantry hook or seated on a stool or bench for joint control, for STAND from MOVE and for DAMP. A walking robot needs 2 m of clear floor ahead of it. 2. **Clear the area.** Keep people, cables and furniture out of the robot's reach and keep the robot in sight. 3. **Have a way to stop the robot open.** Keep Asimov Manager open with its **E-Stop** in the sidebar or the phone top bar (it needs no drive session), and the battery unit within reach to cut power. [Stopping the Robot](https://docs.menlo.ai/asimov/1/operate/safety/stopping.md) explains each. 4. **Make sure nothing else is driving.** End any Drive Robot session and unpair the gamepad. Both outrank a script, and a paired gamepad holds control even while idle. 5. **Check the robot.** `python check.py` or `menlo status` reports battery, actuator temperatures, faults, alerts and whether the state stream is fresh. Neither sends anything. Decide for yourself whether to go ahead, or let [your own guard](https://docs.menlo.ai/sdk/safety.md#write-your-own-guard) decide. 6. **Start slow.** Pass `Robot(limits=Limits(vx=0.2, vy=0.2, vyaw=0.4))` or save limits on the robot, and use short `duration` values until the script behaves. > [!WARNING] > > **Nothing in the SDK is an emergency stop** > > `balance()`, `damp()` and `close()` are commands sent over a network link. None of them cuts > power, and none reaches a robot the link has lost. Keep the **E-Stop** open and the battery > unit within reach whenever the robot stands. ## Standing and Balancing The robot has three robot modes, and only one of them keeps it upright on its own. In **DAMP** no actuator holds a position. In **STAND** the actuators hold a standing pose and nothing balances it: a free-standing robot in STAND tips over. In **MOVE** the walking policy balances the robot, at zero velocity or any other. So the robot must be supported in DAMP and STAND, and stands free only once `balance()` has returned and it reports MOVE. This is the sequence for a script, and the order in which the [Quickstart](https://docs.menlo.ai/sdk/quickstart.md) runs it as separate files: ```python import sys from menlo.asimov import NotReadyError, Robot, RobotFaultedError, WaitTimeoutError with Robot().connect() as robot: # 1. The robot hangs from its gantry hook with both feet on the floor. try: robot.stand() # DAMP -> STAND; returns once the robot is armed robot.balance() # armed STAND -> MOVE at zero velocity; returns once MOVE is reported except RobotFaultedError as exc: # latched until the firmware restarts sys.exit(f"faulted: {exc}") except NotReadyError as exc: # no live state: nothing was sent sys.exit(str(exc)) except WaitTimeoutError as exc: # sent, but the robot did not arm or reach MOVE in time sys.exit(str(exc)) # 2. Only now: slacken the gantry until the robot carries its own weight. input("Robot balancing in MOVE. Slacken the gantry, then press Enter to walk. ") # 3. Walk. Every set_velocity() ends with zero velocity; the robot stays in MOVE. robot.set_velocity(vx=0.2, duration=3.0) robot.balance() # zero velocity: balancing in place # 4. Support the robot again before it leaves MOVE. input("Take up the gantry's slack so it holds the robot, then press Enter to damp. ") robot.damp() # every actuator stops holding its position ``` Why each step is where it is: 1. **`stand()` on the gantry hook, both feet on the floor.** STAND holds a pose and does not balance, so the hook carries the robot. `stand()` sends STAND and returns once the robot reports STAND and has been upright for 0.5 s: the firmware enters MOVE only after that, so `stand()` returning means the robot is armed. It raises `NotReadyError` with nothing sent only when there is no live state. 2. **`balance()` before the support comes off.** From an armed STAND, `balance()` sends zero velocity, which is what puts the robot in MOVE, and returns once the robot reports MOVE. It does not wait for arming: after `stand()` the robot is already armed. MOVE at zero velocity is the only state in which the robot stands free, so the hook keeps carrying the robot until `balance()` has returned: until then the robot is in STAND, and a robot in STAND that loses its support tips over. 3. **Slacken the gantry only after `balance()` returns.** The SDK cannot see the gantry; the script asks you. Slacken it gradually until the robot carries its own weight, with 2 m of clear floor ahead. 4. **Walk, then `balance()`.** `set_velocity()` holds the velocity for its `duration` and ends with zero velocity. `balance()` in MOVE is the same zero velocity, sent at once: it ends a walk and the robot balances in place. 5. **Support the robot before `damp()`.** `damp()` is sent at once, and a standing robot falls when its actuators let go. Take up the gantry's slack, or seat the robot on a stool or bench, first. A script cannot see the support, so this one asks before it damps; to go through STAND first, as the robot's own controls do ([Bring It Back Down](https://docs.menlo.ai/asimov/1/operate/drive/stand-up.md#bring-it-back-down)), see [Bringing the Robot to Rest](https://docs.menlo.ai/sdk/safety.md#bringing-the-robot-to-rest). Catch all three errors around `stand()` and `balance()`. A `RobotFaultedError` means the command was sent and a critical alert, a fall included, latched DAMP until the firmware restarts; a `NotReadyError` means there was no live state and nothing was sent; a `WaitTimeoutError` means the command was sent and the robot did not report the mode in time, so read `robot.get_state().mode` before you decide what to do next. Keep Asimov Manager open at the **E-Stop** throughout: nothing in the SDK is an emergency stop. ## Bringing the Robot to Rest The SDK sends every mode change you ask for, in any robot mode, and the firmware decides what it does. Two of them need the robot supported first, because the SDK cannot see the support: - **MOVE to STAND.** STAND has no balance loop: it stiffens the joints into a pose, and a free-standing robot asked to stand from MOVE tips over. `stand()` from MOVE is sent as asked, so hang the robot from its gantry hook or seat it on a stool or bench first. - **Anything to DAMP.** DAMP makes every actuator compliant, so a standing robot falls. Support the robot the same way before `damp()`. `rest.py` goes from MOVE to STAND to DAMP, the order the robot's own controls use. It asks first whether the robot is on its gantry hook or seated on a stool or bench, unless you set `YES = True`; sends STAND and waits until the robot reports it; then sends DAMP and waits until the robot reports that, printing each robot mode. A robot already in DAMP is left as it is: ```python mode = robot.get_state().mode print(f"robot mode {mode.name}") if mode in (Mode.DAMP, Mode.FAULT_DAMP): print("already at rest; nothing sent") sys.exit(0) if not YES: question = "Is the robot on its gantry hook or seated on a stool or bench? [y/N] " if input(question).strip().lower() not in ("y", "yes"): print("nothing sent") sys.exit(0) try: # STAND first: the robot holds its pose, so DAMP does not drop it from a walk. robot.stand(wait=False) robot.wait_until(lambda s: s.mode is Mode.STAND, timeout=STAND_TIMEOUT_S) print(f"robot mode {robot.get_state().mode.name}") robot.damp() # returns once the robot reports DAMP except (NotReadyError, WaitTimeoutError) as exc: # no live state, a fault, or not reported print(exc) sys.exit(1) print(f"robot mode {robot.get_state().mode.name}") ``` From `examples/rest.py` in the menlo-sdk repository (the excerpt the page shows). `rest.py` is not an emergency stop: for that, use the E-Stop in Asimov Manager, or cut power at the battery unit. ## If Something Goes Wrong 1. **Press the E-Stop in Asimov Manager, or cut power at the battery unit.** The E-Stop damps every actuator at once and a free-standing robot falls; use it when a robot lying on the floor is better than what is happening now. If the robot's software is not running, the E-Stop is disabled: cut power at the battery unit. Do not try to catch a falling robot. 2. **Stop the script.** Ctrl-C in a script that uses `with Robot().connect()` leaves the block, and `close()` sends zero velocity. A script that keeps running keeps re-sending its velocity at 10 Hz; `menlo balance` from another terminal does not end it. 3. **Read what the robot reports, and write it down.** `menlo status` shows the robot mode, a **FAULTED** badge and what latched, from the current alerts and the latched `error_flags`. In a script, `state.faulted` and the `faulted` line from `preflight()` name the causes, and the waits of `stand()`, `balance()`, `set_velocity()`, `set_joints()` and `wait_until()` raise `RobotFaultedError`. 4. **Recover the robot.** Follow [Recovering After an E-Stop or a Fall](https://docs.menlo.ai/asimov/1/operate/safety/stopping.md#recovering-after-an-e-stop-or-a-fall): support and inspect the robot. Its **Stop Robot** and **Start Robot** steps restart the firmware, so do step 3 first. 5. **Restart the firmware, if the recovery did not.** A critical alert holds the robot in DAMP, and `error_flags` set, until the firmware restarts; restarting clears the record of what latched. Use **Restart** on the **Firmware (RPU)** row of the [Troubleshoot page](https://docs.menlo.ai/asimov/1/operate/troubleshooting.md), or **Stop Robot** and **Start Robot** on Overview. Do not call `stand()` on a free-standing robot that is walking or falling. STAND has no balance loop: it stiffens the joints into a pose, and a free-standing robot in that pose tips over. End a walk with `balance()`, which leaves the robot in MOVE, balancing in place. ## Who Stops What | Layer | Stops | Does not stop | | - | - | - | | **SDK** | a held velocity: zero on `balance()`, `close()`, the end of a `with` block, a lost link | anything after a fault; another program's velocity | | **The robot** | velocity and trajectory in DAMP (dropped); a velocity 2 s after the last command on `udp` and `hybrid`; a trajectory 2 s after the last setpoint (DAMP) | a velocity a script keeps re-sending | | **Firmware** | MOVE before an armed STAND (the robot stays in STAND, nothing reports it); everything, on a critical alert (DAMP, latched) | a command because of where it came from: it obeys whichever arrived last; STAND from MOVE on a free-standing robot | The SDK refuses a command only when there is no live state. It also clamps every velocity to your `Limits`, runs every wait against fresh state, and fences a running `set_joints()` so that any verb ends it. `close()` sends zero velocity only when this `Robot` holds one; a `Robot` that sent nothing does not stop another program. After `close()` stops re-sending a trajectory, the robot enters DAMP 2 s later. Neither the robot nor the firmware checks command timestamps. ## Who Holds Control The robot gives the Drive Robot page priority over a paired gamepad, the gamepad over `udp`, and `udp` over `livekit`. The state stream does not say who holds control, so a walk that does not happen, with no fault and no refusal, is the first thing to check. > [!WARNING] > > **An idle paired gamepad locks the SDK out** > > A gamepad paired to the robot holds control while nobody touches it. Every velocity a script > sends is dropped without a report. Unpair the gamepad on the **Controller** page of Asimov > Manager before you run a script; see [Gamepad](https://docs.menlo.ai/asimov/1/operate/drive/gamepad.md#who-drives). ## Limits The firmware caps `vx` and `vy` at 0.4 m/s and `vyaw` at 0.8 rad/s. `Limits()` defaults to those caps and the SDK clamps every velocity to them before it leaves, so `Sent.clamped` is `True` exactly when the robot would not have walked at the speed you asked for. A tighter envelope is `Robot(limits=Limits(vx=0.2, vy=0.2, vyaw=0.4))`, `MENLO_LIMITS="0.2,0.2,0.4"`, or `limits` on a saved robot. Limits above the caps are sent as asked and the firmware clamps them. ## Arming MOVE is entered only from STAND held upright, gravity z below -0.87 (under 30 degrees of tilt), for 0.5 s. A velocity sent earlier is not refused and not reported: the robot stays in STAND. `stand()` returns once the robot is armed, so `stand()` then `balance()` enters MOVE, and `robot.armed` reads the same test the firmware applies. `balance()` and `set_velocity()` send without waiting for arming: a velocity that reaches an armed STAND puts the robot in MOVE, and `balance()` that reaches a STAND that is not armed times out saying so. The SDK counts the 0.5 s from its own samples, so a new session sees an armed robot as armed 0.5 s after it connects. A robot that reports no gravity leaves `robot.armed` as `None`. ## Faults A critical alert, such as a fall, actuator over-temperature, battery protection, a joint past its limit, lost actuator communication or a watchdog, makes the firmware latch DAMP. The latch, and `error_flags`, stay until the firmware restarts. The SDK reports it as `State.faulted` and as `faulted` from `preflight()`, and drops a held velocity without sending anything more. A command is still sent; the wait that sees the fault, in `stand()`, `balance()`, `set_velocity()`, `set_joints()` or `wait_until()`, raises `RobotFaultedError` with `.sent` set. `damp()` returns, since the robot is already in DAMP. ## Watchdogs | Watchdog | Where | What happens | | - | - | - | | **Velocity** | the robot, `udp` and `hybrid` | zero velocity 2 s after the last velocity command; the robot stays in MOVE, balancing | | **Trajectory** | the robot, every mode | DAMP 2 s after the last setpoint | | **Link** | SDK, every mode | no state for 2 s: zero velocity if one is held, `on_link_lost` fires, every verb raises `LinkLostError` until `close()` and `connect()` | A script that holds a velocity re-sends it at 10 Hz, so the velocity watchdog does not stop it: end it with `balance()`, a `duration`, or `close()`. On a `livekit` connection, Asimov Edge stops a held velocity when the SDK sends zero or leaves the room. A script that hangs while it holds a velocity keeps the robot walking until LiveKit drops the participant. Bound every hold with a `duration`, and prefer `udp` or `hybrid` for a control loop. ## What the SDK Reports The SDK does not refuse a command because of what the robot reports. Its robot mode, a latched fault, an alert, an actuator temperature or the battery never stop `stand()`, `balance()`, `set_velocity()`, `trajectory()` or `set_joints()`, and the firmware decides what a command does. The firmware warns at 60 °C and latches DAMP at 80 °C on an actuator, and warns below 20 % battery. The one refusal is no live state. `stand()`, `balance()` outside MOVE, `set_velocity()`, `trajectory()` and `set_joints()` read the latest state sample before they send; on a live stream that adds no delay. Without one (`no_state`, `stale_state`) they wait up to the command's `timeout`, then raise `NotReadyError` with nothing sent. After a STAND sent moments ago whose report has not arrived, they wait up to 1 s for that report, then send anyway. A closed `Robot` raises `NotConnectedError`, a lost link `LinkLostError` and a protocol version mismatch `ProtocolMismatchError`, at once. `trajectory()` and `set_velocity(hold=False)` check once and do not wait unless given a `timeout`. `balance()` in MOVE and `damp()` are sent at once. ```text not ready to move: the latest state is 1.2 s old (limit 0.5 s) (stale_state); check the network link to the robot (waited 5.0 s) ``` Waits stay truthful. `stand()` returns at STAND and armed, `balance()` at MOVE, `damp()` at DAMP. A latched fault seen during a wait raises `RobotFaultedError`, after the command was sent, and a robot that does not get there raises `WaitTimeoutError` saying what it reports: ```python from menlo.asimov import NotReadyError, Robot, RobotFaultedError, WaitTimeoutError with Robot().connect() as robot: try: robot.stand() robot.balance() robot.set_velocity(vx=0.3, duration=3.0) except RobotFaultedError as exc: # sent; latched until the firmware restarts print("faulted:", exc) except NotReadyError as exc: # no live state: nothing was sent print(exc) except WaitTimeoutError as exc: # sent, but the robot did not arm or reach MOVE in time print(exc) ``` `RobotFaultedError` is a `NotReadyError`, so catch it first to tell a latched fault apart. `robot.preflight(action)` lists the facts for `"stand"`, `"move"` (`balance()` and `set_velocity()`) or `"trajectory"` (`trajectory()` and `set_joints()`). It sends nothing, never waits and never raises for a robot condition. `check.ok` is `True` when nothing is blocking, which means there is live state; `check.problems` lists the problems, blocking first. Only the blocking codes stop a command; the others are information, and nothing in the SDK acts on them. `check.py` prints the raw facts and `preflight()` for all three actions: ```python # The SDK counts the 0.5 s a robot in STAND must be upright to arm from its own samples. time.sleep(0.6) s = robot.get_state() # one sample: every fact below comes from it print(f"robot mode {s.mode.name}, armed {robot.armed}, faulted {s.faulted}") print(f"alerts {', '.join(a.name for a in s.alerts) or 'none'}") temps = [j.temp for j in s.joints if j.temp is not None] print(f"hottest joint {max(temps):.0f} C" if temps else "joint temperatures not reported") print(f"battery {s.battery.soc_percent:.0f} %" if s.battery else "battery not reported") print(f"state {s.age_s:.2f} s old") for action in ("stand", "move", "trajectory"): print(robot.preflight(action)) # "ready to move" means live state, and the facts ``` From `examples/check.py` in the menlo-sdk repository (the excerpt the page shows). | Code | Blocks | Meaning | What clears it | | - | - | - | - | | `not_connected` | yes | closed, link lost, or protocol mismatch | `close()` and `connect()` | | `no_state` | yes | the session is open and the robot has not reported state | wait for the firmware; see [No State on udp or hybrid](https://docs.menlo.ai/sdk/troubleshooting.md#no-state-on-udp-or-hybrid) | | `stale_state` | yes | latest state older than 0.5 s | a command waits for the next sample; otherwise check the link | | `faulted` | no | a critical alert is latched, or the robot reports FAULT_DAMP; the alerts that caused it are named | restart the firmware | | `alerts` | no | the firmware reports active alerts, named | | | `not_armed` | no | `move` from STAND before the 0.5 s upright hold | hold STAND upright | ## Write Your Own Guard A rule about what your script will not drive through is yours to write. Read `robot.get_state()` once, decide, and only then send: ```python s = robot.get_state() # one sample; every fact from it if s.faulted or any(j.temp is not None and j.temp >= 80 for j in s.joints): raise SystemExit(f"not driving: robot mode {s.mode.name}, faulted {s.faulted}") ``` `guard.py` is an example guard to start from. Its limits are constants at the top of the file: `MAX_JOINT_TEMP_C` (80 °C, where the firmware latches DAMP), `MIN_BATTERY_PERCENT` (20 %), `REFUSE_WHEN_FAULTED` and `REFUSE_ON_ALERTS` (warning and critical alerts, including the firmware's warning at 60 °C). It prints what it finds and exits with status 1 when your rule fails: ```python def guard(robot: Robot) -> None: """Print what the robot reports, and exit with status 1 when your rule fails.""" s = robot.get_state() # one sample: every fact below comes from it stop: list[str] = [] print(f"guard: robot mode {s.mode.name}, armed {robot.armed}, faulted {s.faulted}") if s.faulted and REFUSE_WHEN_FAULTED: stop.append("the firmware latched DAMP; it stays so until the firmware restarts") temps = [(j.temp, j.name or f"joint {i}") for i, j in enumerate(s.joints) if j.temp is not None] if temps: hottest, joint = max(temps) print(f"guard: hottest joint {joint} {hottest:.0f} C") if hottest >= MAX_JOINT_TEMP_C: stop.append(f"{joint} is at {hottest:.0f} C (your limit {MAX_JOINT_TEMP_C:.0f} C)") else: print("guard: joint temperatures not reported") if s.battery is not None: print(f"guard: battery {s.battery.soc_percent:.0f} %") if s.battery.soc_percent < MIN_BATTERY_PERCENT: stop.append( f"battery at {s.battery.soc_percent:.0f} % (your limit {MIN_BATTERY_PERCENT:.0f} %)" ) if s.battery.protecting: stop.append("the battery management system is protecting the pack") else: print("guard: battery not reported") for alert in s.alerts: print(f"guard: alert {alert.name} (severity {alert.severity})") serious = sorted({a.name for a in s.alerts if a.severity <= 1}) # 0 critical, 1 warning if serious and REFUSE_ON_ALERTS: stop.append(f"active alerts: {', '.join(serious)}") if stop: print("guard: not going ahead: " + "; ".join(stop)) print("guard: this is your rule in guard.py; change it, or delete the guard(robot) line") sys.exit(1) ``` From `examples/guard.py` in the menlo-sdk repository (the excerpt the page shows). No example uses it by default. The motion examples, `stand.py`, `balance.py`, `walk.py`, `keyboard.py`, `stream_velocity.py`, `move_joints.py` and `wait_until.py`, carry it as two commented lines; uncomment both to run it before the script sends anything: ```python from guard import guard guard(robot) ``` Change the constants or change `guard()` to make the rule yours. Run on its own, `python guard.py` prints what it finds and sends nothing. ## Shutdown Leaving the `with` block calls `close()`: zero velocity if one is held, then the link drops. The robot stays in MOVE, balancing in place, and the Drive Robot page or the gamepad can take it from there. Call `damp()` at the end of a session only on a supported robot, hanging from its gantry hook or seated on a stool or bench: every actuator stops holding its position and a standing robot falls. `damp.py` asks before it sends, then waits for the robot to report DAMP: ```python # damp() is never refused, so there is no check here, only the question. if not YES: mode = robot.get_state().mode.name question = f"Robot mode {mode}. Is the robot supported? Damp now? [y/N] " if input(question).strip().lower() not in ("y", "yes"): print("nothing sent") sys.exit(0) try: robot.damp() # returns once the robot reports DAMP except WaitTimeoutError as exc: # sent, but DAMP was not reported: the message says what next print(exc) sys.exit(1) print(f"robot mode {robot.get_state().mode.name}") ``` From `examples/damp.py` in the menlo-sdk repository (the excerpt the page shows). Turning the robot off is in [Power](https://docs.menlo.ai/asimov/1/operate/power.md#turn-the-robot-off). ## Related - [Stopping the Robot](https://docs.menlo.ai/asimov/1/operate/safety/stopping.md): the E-Stop, pause, damp and cutting power - [Stand Up and Walk](https://docs.menlo.ai/asimov/1/operate/drive/stand-up.md): the same sequence from the Drive Robot page - [Move the Robot](https://docs.menlo.ai/sdk/move.md): stand, balance and walk - [Control Joints](https://docs.menlo.ai/sdk/joints.md): joint control on a supported robot - [Troubleshooting](https://docs.menlo.ai/sdk/troubleshooting.md): each error and its fix --- # Quickstart > Install menlo-sdk, save the robot, check it, then stand, balance, walk for 3 s and damp from Python. - Page: https://docs.menlo.ai/sdk/quickstart - Section: Python SDK By the end of this page the robot stands up from DAMP, balances on its own, walks forward for 3 s and rests again, from five short scripts. > [!WARNING] > > **Before the first walk** > > For a first run, hang the robot from its gantry hook with both feet on the floor and 2 m of > clear floor ahead. Keep Asimov Manager open at the **E-Stop**, or be ready to cut power at > the battery unit: nothing in the SDK is an emergency stop. Work through > [Before You Run a Script](https://docs.menlo.ai/sdk/safety.md#before-you-run-a-script) and > [Standing and Balancing](https://docs.menlo.ai/sdk/safety.md#standing-and-balancing) first. 1. ## Install Python 3.12 or newer. ```bash pip install menlo-sdk ``` or, in a project managed by uv, `uv add menlo-sdk`. One package drives every connection mode; there are no extras. 2. ## Get the Examples The scripts on this page are in the `examples` directory of the [menlo-sdk repository on GitHub](https://github.com/menloresearch/menlo-sdk/tree/main/examples). Clone it and run them from there: ```bash git clone https://github.com/menloresearch/menlo-sdk cd menlo-sdk/examples ``` Each code block below shows the main part of a script. The full script also imports the SDK, sets its constants and connects with `with Robot().connect() as robot:`, which waits for the robot's first state. 3. ## Get an SDK Credential The `hybrid` and `livekit` connection modes join the robot's LiveKit room with an SDK credential from Asimov Manager; `livekit` also carries commands through it. Skip this step for `udp`, which needs no credential. 1. In Asimov Manager, open **Developer** in the sidebar. Under **How a script connects**, note the **Manager URL**: it is the address the SDK uses to reach the robot. ![The Developer page's connection details: Manager URL, LiveKit URL and Room](https://docs.menlo.ai/manual/v1/assets/manager/developer-connection.png) You do not need the **LiveKit URL** or the **Room**. The SDK asks the robot for both each time it connects, and when the LiveKit URL reads `localhost`, the SDK uses the robot's address instead. 2. Under **Issue a credential**, enter a **Name** for the computer that will use it, such as `my-laptop`. Issue one per computer, so you can revoke one without cutting off the others. 3. Under **What it may do**, choose **Control** to drive the robot from your computer. **Observe** watches the camera and listens to the microphone only; the robot drops its commands. ![The Issue a credential form: a name, and the Observe and Control choice](https://docs.menlo.ai/manual/v1/assets/manager/developer-issue.png) 4. Select **Issue Credential**, then copy the credential with the copy button next to it. It is shown only this once: the robot keeps the credential's ID, not the credential, so it cannot show it again. If you lose it, revoke it and issue another. ![A newly issued credential, shown once with its copy button](https://docs.menlo.ai/manual/v1/assets/manager/developer-reveal.png) 5. The credential appears under **Issued credentials** with its role and ID. To take it back, select **Revoke** next to it; the computer holding it can no longer connect, and a session that is already running keeps working until its LiveKit token expires, at most 12 hours. ![Issued credentials, each with its role, ID, issue time and a Revoke button](https://docs.menlo.ai/manual/v1/assets/manager/developer-issued.png) 4. ## Save the Robot ```bash menlo setup ``` The wizard asks for a name, a connection mode, and what the mode needs: the robot's address for `udp`, the Manager URL and the credential for `livekit`, both for `hybrid`. It checks each field against the robot before it saves, and every script below then finds the robot with `Robot()` and no arguments. `udp` and `hybrid` carry commands and state on the robot's network, and the robot sends UDP state to one computer. In Asimov Manager, open **Advanced Settings** and, under **Asimov Edge**, set `udp-control` to on and `udp-state-host` to your computer's address, then select **Save & Restart Asimov Edge**. Without a saved robot, `export MENLO_UDP_HOST=` points the SDK at the robot for one shell. To build the connection in code, see [Connection Modes](https://docs.menlo.ai/sdk/connection-modes.md). 5. ## Check `check.py` connects, prints what the robot reports (robot mode, armed, faults, alerts, the hottest joint, battery and the state's age) and `preflight()` for a stand, a walk and a trajectory, and sends nothing. Run it before anything that moves the robot: ```python # The SDK counts the 0.5 s a robot in STAND must be upright to arm from its own samples. time.sleep(0.6) s = robot.get_state() # one sample: every fact below comes from it print(f"robot mode {s.mode.name}, armed {robot.armed}, faulted {s.faulted}") print(f"alerts {', '.join(a.name for a in s.alerts) or 'none'}") temps = [j.temp for j in s.joints if j.temp is not None] print(f"hottest joint {max(temps):.0f} C" if temps else "joint temperatures not reported") print(f"battery {s.battery.soc_percent:.0f} %" if s.battery else "battery not reported") print(f"state {s.age_s:.2f} s old") for action in ("stand", "move", "trajectory"): print(robot.preflight(action)) # "ready to move" means live state, and the facts ``` From `examples/check.py` in the menlo-sdk repository (the excerpt the page shows). ```bash python check.py ``` The SDK does not refuse a command because of what the robot reports: a fault, an alert, a hot actuator or a low battery is yours to judge, and the firmware decides what a command does. The one refusal is no live state. The scripts below carry `guard(robot)` from `guard.py` commented out: an example guard of your own that stops the script when the robot is faulted, has a warning or critical alert, has an actuator at 80 °C or more, or has a battery below 20 %. Uncomment its two lines in a script to turn it on, and edit its limits; see [Write Your Own Guard](https://docs.menlo.ai/sdk/safety.md#write-your-own-guard). 6. ## Stand With the robot in DAMP, hanging from its gantry hook with both feet on the floor: ```python # guard(robot) # optional: uncomment this and the import to stop on your rule try: # Returns once the robot reports STAND and has been upright for 0.5 s (armed): the # firmware enters MOVE only after that. robot.stand() except (NotReadyError, WaitTimeoutError) as exc: # no live state, a fault, or not armed print(exc) # what the robot reports and what to do sys.exit(1) print(f"robot mode {robot.get_state().mode.name}, armed {robot.armed}") ``` From `examples/stand.py` in the menlo-sdk repository (the excerpt the page shows). ```bash python stand.py ``` The actuators hold a standing pose and `stand()` returns once the robot is armed: STAND held upright for 0.5 s. It sends nothing else. Without live state, `stand()` raises `NotReadyError` with nothing sent, and the script prints why; when the robot does not arm within 10 s, it raises `WaitTimeoutError`. `stand()` is sent from any robot mode, but STAND has no balance loop: after a walk, hang the robot from its gantry hook or seat it on a stool or bench before you call it. 7. ## Balance With the robot armed and still on its gantry hook: ```python # guard(robot) # optional: uncomment this and the import to stop on your rule try: robot.balance() # returns once the robot reports MOVE except (NotReadyError, WaitTimeoutError) as exc: # no live state, a fault, or not MOVE print(exc) # what the robot reports and what to do sys.exit(1) print(f"robot mode {robot.get_state().mode.name}, balancing in place") ``` From `examples/balance.py` in the menlo-sdk repository (the excerpt the page shows). ```bash python balance.py ``` `balance()` sends zero velocity, which puts an armed robot in MOVE: the walking policy balances it in place, and this is the only robot mode in which it stands free. It returns once the robot reports MOVE, or raises `WaitTimeoutError` after 5 s. Once it has returned, slacken the gantry gradually until the robot carries its own weight. 8. ## Walk With the robot balancing in MOVE: ```python # guard(robot) # optional: uncomment this and the import to stop on your rule mode = robot.get_state().mode if mode is not Mode.MOVE: # this script's own rule: walk from MOVE only print(f"robot mode {mode.name}: walk.py walks in MOVE only; run balance.py first") sys.exit(1) try: # Held and re-sent at 10 Hz for DURATION_S, then zero velocity; returns after that. sent = robot.set_velocity(vx=VX, vy=VY, vyaw=VYAW, duration=DURATION_S) except NotReadyError as exc: # no live state (nothing sent), or a fault ended the walk print(exc) sys.exit(1) if sent.clamped: print("the SDK reduced the speed to the robot's limits:", sent.command) print(f"robot mode {robot.get_state().mode.name}, balancing in place") ``` From `examples/walk.py` in the menlo-sdk repository (the excerpt the page shows). ```bash python walk.py ``` What each line does: | Line | Effect | | - | - | | `# guard(robot)` | Your own rule from `guard.py`, off by default: uncomment it and its import to exit when the robot reports what it will not drive through | | `if mode is not Mode.MOVE` | This script's own rule: it walks in MOVE only | | `set_velocity(vx=VX, vy=VY, vyaw=VYAW, duration=DURATION_S)` | Walks at the set velocity for the duration; the SDK re-sends the velocity while it is held, sends zero velocity when the duration ends, and returns after that | | `except NotReadyError` | There was no live state and nothing was sent, or a fault ended the walk (a `RobotFaultedError` with `.sent` set); the message says what the robot reports and what to do | | `sent.clamped` | `True` when the SDK reduced the speed to the robot's limits; `sent.command` is what went out | After the walk the robot stays in MOVE, balancing in place. The velocity and duration are constants at the top of the file. Leaving the `with` block closes the connection; a held velocity gets a zero first. The script never changes the robot mode: on a robot in STAND it prints `robot mode STAND: walk.py walks in MOVE only; run balance.py first` and exits. That rule is the script's, not the SDK's: `set_velocity()` is sent in any robot mode. 9. ## Put the Robot Down `damp()` makes every actuator compliant. A standing robot folds, so support it first: take up the gantry's slack, or seat the robot on a stool or bench. `rest.py` goes from MOVE to STAND to DAMP instead, and asks first; see [Bringing the Robot to Rest](https://docs.menlo.ai/sdk/safety.md#bringing-the-robot-to-rest). ```python # damp() is never refused, so there is no check here, only the question. if not YES: mode = robot.get_state().mode.name question = f"Robot mode {mode}. Is the robot supported? Damp now? [y/N] " if input(question).strip().lower() not in ("y", "yes"): print("nothing sent") sys.exit(0) try: robot.damp() # returns once the robot reports DAMP except WaitTimeoutError as exc: # sent, but DAMP was not reported: the message says what next print(exc) sys.exit(1) print(f"robot mode {robot.get_state().mode.name}") ``` From `examples/damp.py` in the menlo-sdk repository (the excerpt the page shows). ```bash python damp.py ``` The script asks for confirmation unless `YES` is set to `True` at the top of the file. `damp()` is not an emergency stop; for that, use the E-Stop in Asimov Manager, or cut power at the battery unit ([Stopping the Robot](https://docs.menlo.ai/asimov/1/operate/safety/stopping.md)). ## What Ready Means Ready means live state. A command refuses only without it: it waits up to its `timeout` for a fresh sample (by default 10 s for `stand()`, 5 s for `balance()`, `set_velocity()` and `set_joints()`; `trajectory()` checks once), then raises `NotReadyError` with nothing sent. Every other fact is reported, not acted on: ```python from menlo.asimov import NotReadyError, Robot with Robot().connect() as robot: print(robot.preflight("move")) # the facts: blocking only without live state try: robot.set_velocity(vx=0.3, duration=3.0) except NotReadyError as e: print(e) # not ready to move: the latest state is 1.2 s old (limit 0.5 s) (stale_state); ... ``` `balance()` in MOVE and `damp()` are sent at once. The full picture is in [What the SDK Reports](https://docs.menlo.ai/sdk/safety.md#what-the-sdk-reports). ## Next Steps - [Move the Robot](https://docs.menlo.ai/sdk/move.md): turning, holding a velocity, limits - [Safety](https://docs.menlo.ai/sdk/safety.md): what the SDK does and does not do for you - [Examples](https://docs.menlo.ai/sdk/examples.md): every script in the repository, including `keyboard.py` for driving from the keyboard - [Command Line](https://docs.menlo.ai/sdk/cli.md): `menlo setup` to save a robot, `menlo status --watch` while you develop ## Related - [Drive from Python](https://docs.menlo.ai/asimov/1/operate/drive/python-sdk.md): the same path with the robot's settings, video and sound - [Stand Up and Walk](https://docs.menlo.ai/asimov/1/operate/drive/stand-up.md): the same sequence from the Drive Robot page - [menlo-sdk on PyPI](https://pypi.org/project/menlo-sdk/) - [menlo-sdk on GitHub](https://github.com/menloresearch/menlo-sdk) --- # Connection Modes > UDP, Hybrid and LiveKit: what each carries, what it needs, and how the SDK picks one. - Page: https://docs.menlo.ai/sdk/connection-modes - Section: Python SDK The SDK reaches the robot in one of three connection modes. The `Robot` object and every verb are the same in all three; the mode decides what the connection carries and where it works from. | Mode | Control and state | Camera and audio | Works from | | - | - | - | - | | `udp` | UDP on the robot's network | none | the robot's network | | `hybrid` | UDP on the robot's network | a LiveKit room | the robot's network | | `livekit` | a LiveKit room | a LiveKit room | wherever Asimov Manager is reachable | A saved robot carries a mode, so `Robot().connect()` needs no argument. Pass one to override it for a session: `connect("udp")`. ## In Code `connect.py` builds the connection in code. Set `MODE` at the top of the file to `"udp"`, `"hybrid"` or `"livekit"`; the three `ConnectionConfig` shapes sit side by side: ```python # udp: control and state over UDP on the robot's network. No camera or audio. udp = ConnectionConfig(udp=UdpConfig(host=ROBOT_ADDRESS)) # hybrid: control and state over UDP, camera and audio over LiveKit. hybrid = ConnectionConfig( udp=UdpConfig(host=ROBOT_ADDRESS), livekit=ManagerConfig(url=MANAGER_URL, credential=CREDENTIAL), ) # livekit: everything through the robot's LiveKit room, wherever Asimov Manager is reachable. livekit = ConnectionConfig(livekit=ManagerConfig(url=MANAGER_URL, credential=CREDENTIAL)) config = {"udp": udp, "hybrid": hybrid, "livekit": livekit}[MODE] try: with Robot(config).connect(MODE) as robot: state = robot.get_state() print(f"connected over {MODE} to {robot.info.endpoint}") print(f"robot mode {state.mode.name}, armed {robot.armed}") if state.battery is not None: print(f"battery {state.battery.soc_percent:.0f} %") else: print("battery not reported") capabilities = ("drive", "state", "battery", "camera", "microphone", "speaker") print("capabilities:", ", ".join(c for c in capabilities if robot.has(c))) except CompatibilityError as exc: # The robot answered, but its model or Robot OS line is not supported. # Updating the SDK or robot is appropriate; blindly retrying is not. print(f"incompatible robot: {exc}") except ConnectError as exc: # The connection itself failed: robot, credentials, room or transport. # Check the reported cause; a retry may make sense for a transient failure. print(f"could not connect: {exc}") ``` From `examples/connect.py` in the menlo-sdk repository (the excerpt the page shows). The other example scripts call `Robot()` with no config and read the environment or a saved robot instead; see [How the SDK Picks a Connection](https://docs.menlo.ai/sdk/connection-modes.md#how-the-sdk-picks-a-connection). ## UDP Commands go to the robot on UDP port 8850 and state comes back on port 8851. There is no media and no sign-in: anyone on the robot's network who can reach port 8850 can command it, so trust the network before you turn it on. The robot sends UDP state to one host. In Asimov Manager, set the Asimov Edge parameters `udp-control` to on and `udp-state-host` to your computer's address ([Asimov Manager](https://docs.menlo.ai/asimov/1/operate/asimov-manager.md#overview)). One client per state port: a second script on the same computer binds `UdpConfig(state_bind=("0.0.0.0", ))` and the robot's `udp-state-port` matches it. ## Hybrid Control and state travel as in udp, so a velocity command does not cross the internet. The camera, microphone and speaker travel over the robot's LiveKit room, which the SDK joins with an SDK credential from Asimov Manager. Use hybrid on the robot's network when a script needs the camera or sound. It needs the robot's address, its Asimov Manager URL and an SDK credential. Issue the credential on the **Developer** page of Asimov Manager ([Get an SDK Credential](https://docs.menlo.ai/sdk/quickstart.md#get-an-sdk-credential)). The credential's role applies to the LiveKit room: a **Control** credential can talk through the speaker, an **Observe** credential watches and listens only. Commands in hybrid travel over UDP, which has no sign-in, so the role does not limit driving. ## LiveKit Everything, commands included, goes through the robot's LiveKit room. Commands travel on the data topic `commands` and state on the data track `state`, at about 10 Hz. When the robot's Asimov Edge reads it, a non-zero velocity and a trajectory go on the SDK's own data track `commands` instead: a lost frame is replaced by the next one, where a lost packet would hold the rest of the stream back until it is resent. Mode commands and a zero velocity always go as packets. Use livekit away from the robot's network, or when an agent framework joins the same room and the SDK is one more participant in it. It needs the Asimov Manager URL and an SDK credential ([Get an SDK Credential](https://docs.menlo.ai/sdk/quickstart.md#get-an-sdk-credential)). The SDK asks Asimov Manager for a room token, joins, and reports `robot.info.endpoint` as `room@url as `. The credential's role applies: a **Control** credential drives, an **Observe** credential watches and listens, and the robot drops its commands. The Asimov Manager URL is the one you open in the browser: `http://192.168.22.32`, `http://asimov.local:8080` or a bare host name. The LiveKit URL Asimov Manager hands out is the one the robot itself uses; when it says `localhost`, the SDK substitutes the manager's host. A manager that redirects is reported as a `ConnectError`, not followed. Every SDK session joins the room as its own participant, `sdk---<6 hex>`. `ManagerConfig(label="...")` fixes the suffix so a restarted script replaces its previous session instead of joining beside it. To join with a token you minted yourself, pass `LiveKitConfig(url, room, token)` instead of `ManagerConfig`; one token is one participant. To use the room without the SDK at all, see [Without the SDK](https://docs.menlo.ai/sdk/without-the-sdk.md). ## How the SDK Picks a Connection `Robot()` with no argument builds its connection from the environment or a saved robot, in this order: 1. Environment variables: `MENLO_UDP_HOST`, or `MENLO_MANAGER_URL` and `MENLO_CREDENTIAL`, or both pairs. They are not merged with a saved robot. 2. A saved robot from `~/.menlo/robots.toml`: the one named by `MENLO_ROBOT`, else the file's default, else the only one. 3. Otherwise `ConnectError`, naming `menlo setup` and the variables. `MENLO_MODE` sets the mode `connect()` uses with no argument and `MENLO_LIMITS` the velocity limits, whichever source supplied the connection. `MENLO_HOME` moves the store directory. A saved robot holds everything one mode needs, and can hold more than one mode's fields: ```toml title="~/.menlo/robots.toml" default = "lab" [robots.lab] mode = "hybrid" udp_host = "192.168.22.32" manager_url = "http://192.168.22.32" credential = "..." room = "robot-menlo-0001" [robots.lab.limits] vx = 0.3 ``` `udp` needs `udp_host`; `hybrid` needs `udp_host`, `manager_url` and `credential`; `livekit` needs `manager_url` and `credential`. A mode whose field is missing raises `ConnectError` naming the field and the `menlo robots add` command that fills it. Save and change robots with the [command line](https://docs.menlo.ai/sdk/cli.md); the file is created with mode 0600 because it holds SDK credentials. ## What Connect Waits For `connect()` returns once the robot has reported state, so `robot.get_state()` is valid on the next line. It raises `ConnectError` after `timeout` (5 s by default) without state. On hybrid and livekit the media tracks are awaited for `media_timeout` (3 s); the capabilities the SDK claims are the tracks that arrived. `connect(require_state=False)` opens the room without waiting for the firmware: camera, microphone and speaker work at once. State unlocks when the first state frame arrives; a motion verb sent before then waits for it up to its `timeout`. A protocol version other than the one the SDK speaks raises `ProtocolMismatchError`. `allow_version_skew=True` connects anyway, and the robot may misread the commands the SDK sends. Update the SDK or the robot instead. > [!WARNING] > > **A lost link ends a held velocity** > > After 2 s without state the SDK raises `LinkLostError`, sends zero velocity if it holds one, > and every verb raises until you `close()` and `connect()` again. On `udp` and `hybrid`, the > robot also zeroes a velocity 2 s after the last command it received. On `livekit`, Asimov > Edge stops a held velocity when the SDK sends zero or leaves the room; see > [Watchdogs](https://docs.menlo.ai/sdk/safety.md#watchdogs). ## Related - [Quickstart](https://docs.menlo.ai/sdk/quickstart.md): point the SDK at the robot and run the first scripts - [Command Line](https://docs.menlo.ai/sdk/cli.md): `menlo setup` and `menlo robots` - [Drive from Python](https://docs.menlo.ai/asimov/1/operate/drive/python-sdk.md): the SDK credential and the UDP settings, step by step - [Asimov Manager](https://docs.menlo.ai/asimov/1/operate/asimov-manager.md): the robot's settings - [SDK Reference](https://docs.menlo.ai/sdk/reference.md#connection): `ConnectionConfig`, `UdpConfig`, `ManagerConfig`, `LiveKitConfig` --- # Move the Robot > stand, balance, set_velocity, what each command waits for, and the velocity limits. - Page: https://docs.menlo.ai/sdk/move - Section: Python SDK Walking is one verb, `set_velocity(vx, vy, vyaw)`, held for a duration or until you end it. Everything else on this page is about getting the robot into the robot mode that accepts it, and ending a walk safely. | Robot mode | What the robot does | Verb that reaches it | | - | - | - | | **DAMP** | every actuator compliant; the robot rests on a stool or bench, hangs from its gantry hook, or folds to the ground | `damp()` | | **STAND** | joints stiffened into the standing pose; no balance loop | `stand()` | | **MOVE** | the walking policy balances and walks | `balance()` from an armed STAND | Every verb is sent in any robot mode, and the firmware decides what it does. The firmware enters MOVE from STAND only once the robot is **armed**: STAND held upright for 0.5 s. In DAMP, the robot drops velocity commands and nothing reports it. The SDK refuses a command only without live state; a rule about the robot mode, a fault or a hot actuator is your script's, as in [Write Your Own Guard](https://docs.menlo.ai/sdk/safety.md#write-your-own-guard). > [!WARNING] > > **A walking robot needs clear floor** > > Support the robot for a first run, hanging from its gantry hook with both feet on the floor, > and keep 2 m of clear floor ahead. Keep Asimov Manager open at the **E-Stop**; nothing in > the SDK is an emergency stop. Work through > [Before You Run a Script](https://docs.menlo.ai/sdk/safety.md#before-you-run-a-script) and > [Standing and Balancing](https://docs.menlo.ai/sdk/safety.md#standing-and-balancing) first. ## Stand Up `stand()` puts the robot in STAND: the actuators hold a standing pose by position control alone, without a balance loop. Call it on a robot in DAMP that hangs from its gantry hook with both feet on the floor, as in [Stand Up and Walk](https://docs.menlo.ai/asimov/1/operate/drive/stand-up.md). `stand()` is also sent from MOVE: hang the robot from its gantry hook or seat it on a stool or bench first, or it tips over; see [Bringing the Robot to Rest](https://docs.menlo.ai/sdk/safety.md#bringing-the-robot-to-rest). ```python # guard(robot) # optional: uncomment this and the import to stop on your rule try: # Returns once the robot reports STAND and has been upright for 0.5 s (armed): the # firmware enters MOVE only after that. robot.stand() except (NotReadyError, WaitTimeoutError) as exc: # no live state, a fault, or not armed print(exc) # what the robot reports and what to do sys.exit(1) print(f"robot mode {robot.get_state().mode.name}, armed {robot.armed}") ``` From `examples/stand.py` in the menlo-sdk repository (the excerpt the page shows). To stop first on your own rule from `guard.py`, uncomment the two guard lines in `stand.py`. `stand()` waits for live state, then sends STAND; without live state it raises `NotReadyError` with nothing sent. Once sent, it reads the robot's own report and returns when the robot is armed. It raises `WaitTimeoutError` when that takes more than 10 s and `RobotFaultedError` when a fault latches meanwhile. ## Balance `balance()` puts the robot in MOVE at zero velocity: the walking policy balances it in place, and this is the only robot mode in which the robot stands free. Call it with the robot still supported, and slacken the gantry only after it returns. ```python # guard(robot) # optional: uncomment this and the import to stop on your rule try: robot.balance() # returns once the robot reports MOVE except (NotReadyError, WaitTimeoutError) as exc: # no live state, a fault, or not MOVE print(exc) # what the robot reports and what to do sys.exit(1) print(f"robot mode {robot.get_state().mode.name}, balancing in place") ``` From `examples/balance.py` in the menlo-sdk repository (the excerpt the page shows). Outside MOVE, `balance()` sends zero velocity as soon as there is live state, which is what puts an armed robot in MOVE, and returns once the robot reports MOVE; `WaitTimeoutError` when it does not within `timeout` (5 s by default), saying so when the robot was not armed. From DAMP it raises `WaitTimeoutError` at once: `the robot is in DAMP: stand() first`. In MOVE, `balance()` is sent at once: it ends any held velocity and sends zero, so it is also how a walk ends. The firmware reports STAND at once but enters MOVE only after STAND has been held upright, gravity z below -0.87, for 0.5 s. A velocity sent before that is neither refused nor reported: the robot stays in STAND. `stand()` returns only once the robot is armed, so `stand()` then `balance()` enters MOVE. `robot.armed` is the arming test as a property: `True` once armed or in MOVE, `False` in DAMP or before the hold has passed, `None` with no state, when the Robot is closed, in robot mode UNKNOWN, or in STAND when the robot reports no gravity. ## Walk `set_velocity()` is sent in any robot mode: in MOVE the robot walks, an armed STAND enters MOVE, and in DAMP the robot drops it. Without live state it raises `NotReadyError` with nothing sent. `walk.py` keeps a rule of its own: it walks in MOVE only, and exits naming `balance.py` otherwise. ```python # guard(robot) # optional: uncomment this and the import to stop on your rule mode = robot.get_state().mode if mode is not Mode.MOVE: # this script's own rule: walk from MOVE only print(f"robot mode {mode.name}: walk.py walks in MOVE only; run balance.py first") sys.exit(1) try: # Held and re-sent at 10 Hz for DURATION_S, then zero velocity; returns after that. sent = robot.set_velocity(vx=VX, vy=VY, vyaw=VYAW, duration=DURATION_S) except NotReadyError as exc: # no live state (nothing sent), or a fault ended the walk print(exc) sys.exit(1) if sent.clamped: print("the SDK reduced the speed to the robot's limits:", sent.command) print(f"robot mode {robot.get_state().mode.name}, balancing in place") ``` From `examples/walk.py` in the menlo-sdk repository (the excerpt the page shows). Axes: `vx` forward in m/s, `vy` left in m/s, `vyaw` counter-clockwise in rad/s. A walk is `set_velocity(vx=0.2, duration=3.0)`, a strafe `set_velocity(vy=0.15, duration=3.0)`, a turn on the spot `set_velocity(vyaw=0.3, duration=3.0)`; combine them in one call. ## Hold a Velocity By default `set_velocity()` needs a `duration`: the SDK re-sends the velocity at 10 Hz for that long, sends zero, and returns once the zero has gone out (`wait=True`). With `wait=False` it returns at once with a `Sent` and the hold runs in the background, with or without a `duration`, until something ends it: | The hold ends when | What is sent | | - | - | | `duration` seconds pass | zero velocity, by the SDK | | `balance()` | zero velocity | | another `set_velocity()` | the new velocity | | `stand()`, `damp()`, `trajectory()`, `set_joints()` | that verb | | `close()`, or the end of the `with` block | zero velocity, then the link drops | | the link is lost (no state for 2 s) | zero velocity; every verb raises until `close()` and `connect()` | | the firmware latches a fault or restarts | nothing; the hold is dropped | The next verb or the end of the `with` block cuts an unexpired `wait=False` hold short, so a script that calls `set_velocity(duration=3.0, wait=False)` and returns does not walk for 3 s. `set_velocity(hold=False)` sends exactly one packet and re-sends nothing: your own loop is the clock, as in `stream_velocity.py`. It takes no `duration` and no `wait`, and the live-state check runs once per call, so a live stream adds no delay between packets. On `udp` and `hybrid`, the robot zeroes the velocity 2 s after the last packet it received; it stays in MOVE, balancing. On `livekit`, Asimov Edge stops a held velocity when the SDK sends zero or leaves the room, so always bound a hold with a `duration`; see [Watchdogs](https://docs.menlo.ai/sdk/safety.md#watchdogs). ## Drive from the Keyboard `keyboard.py` turns key presses into short bounded holds of about 0.3 s, so releasing a key stops the robot. `w`/`s` walk forward and back, `a`/`d` strafe, `q`/`e` turn, space sends `balance()`, `t` stands (from MOVE it asks first whether the robot is on its gantry hook or seated on a stool or bench), `b` damps after asking, and `x` or Ctrl-C quits with zero velocity and `close()`. Every key is sent in any robot mode, and the status line shows what the robot reports. Uncomment its two guard lines to run `guard(robot)` before the first key. From DAMP, `t` then space brings the robot to STAND and then to MOVE. A one-line status shows the robot mode, arming, battery and the last command. The keyboard walks the robot backward, sideways and round as well as forward: keep clear floor all around it, not only ahead. ```python while True: show(robot, last) key = next_key(TICK_S) if key is None: continue if key in QUIT: break if key in MOVES: last = move(robot, key) elif key == " ": last = balance(robot) elif key == "t": last = stand(robot, next_key) elif key == "b": last = confirm_and_damp(robot, next_key) ``` From `examples/keyboard.py` in the menlo-sdk repository (the excerpt the page shows). ## End a Walk `balance()` sends zero velocity. The robot stays in MOVE and the walking policy keeps it balanced in place. End a walk this way; a `set_velocity()` with a `duration` does the same when the duration runs out. `stand()` after walking removes the balance loop and a free-standing robot falls; the SDK sends it as asked, so support the robot first. To finish a session in DAMP, support the robot first, hanging from its gantry hook or seated on a stool or bench, then run `rest.py` (MOVE, STAND, then DAMP, asking first) or `damp.py`; see [Bringing the Robot to Rest](https://docs.menlo.ai/sdk/safety.md#bringing-the-robot-to-rest). ## Turn by Heading `State.yaw` is the heading in radians, counter-clockwise. Turn until the heading has changed by an angle instead of guessing a duration: ```python import math from menlo.asimov import Robot with Robot().connect() as robot: before = robot.get_state().yaw robot.set_velocity(vyaw=0.3, duration=15.0, wait=False) # NotReadyError only without live state robot.wait_until( lambda s: s.yaw is not None and abs(math.remainder(s.yaw - before, math.tau)) >= math.radians(90), timeout=15.0, ) robot.balance() ``` `math.remainder` keeps the difference in (-pi, pi], so the wrap at pi does not count as a full turn. `wait_until` checks for a fault before it evaluates the predicate and raises `StateStaleError` when the stream goes quiet, so a robot that fell or stopped talking is never read as "turned". ## Limits The Motion Control Board firmware caps velocity at 0.4 m/s forward and sideways and 0.8 rad/s turning. `Limits()` defaults to those caps, so `Sent.clamped` is `True` exactly when the robot would not have walked at the speed you asked for; `sent.command` is the velocity that went out. Lower limits keep a script inside a smaller envelope: ```python from menlo.asimov import Limits, Robot robot = Robot(limits=Limits(vx=0.2, vy=0.2, vyaw=0.4)) ``` `Robot(limits=)` wins over `MENLO_LIMITS="vx,vy,vyaw"`, which wins over the saved robot's `[robots.NAME.limits]`, which wins over the defaults. Values above the firmware caps are sent as asked and the firmware clamps them. Negative or non-finite limits raise `ValueError`. ## Related - [Safety](https://docs.menlo.ai/sdk/safety.md#standing-and-balancing): the stand, balance, walk, damp sequence and why - [Read State](https://docs.menlo.ai/sdk/state.md): `robot.armed`, `wait_until`, faults - [Stand Up and Walk](https://docs.menlo.ai/asimov/1/operate/drive/stand-up.md): the same robot modes from the Drive Robot page - [SDK Reference](https://docs.menlo.ai/sdk/reference.md#set_velocity): `set_velocity`, `balance`, `stand`, `damp`, `Limits` - [Troubleshooting](https://docs.menlo.ai/sdk/troubleshooting.md): `NotReadyError`, `WaitTimeoutError` and `RobotFaultedError` --- # Control Joints > set_joints and trajectory: per-joint targets on a supported robot, with the walking policy off. - Page: https://docs.menlo.ai/sdk/joints - Section: Python SDK Two verbs put the actuators under position control. `set_joints(positions)` moves every joint to a pose for you; `trajectory(positions)` sends one setpoint and expects you to clock the next. > [!WARNING] > > **Joint control turns the walking policy off** > > While a `set_joints()` or a `trajectory()` is in force, nothing balances the robot. Use them > only with the robot supported, hanging from its gantry hook or seated on a stool or bench. A fall > latches DAMP until the firmware restarts. Work through > [Before You Run a Script](https://docs.menlo.ai/sdk/safety.md#before-you-run-a-script) first. ## Move to a Pose `set_joints` interpolates from the pose the robot last reported to the one you ask for, over `duration` seconds, and clocks the setpoints at `hz` from a thread. It returns once every joint is within `tolerance` radians of its target, then holds the target by re-sending it until another verb takes over. `move_joints.py` bends one elbow (`JOINT = "L_Elbow"`) and moves nothing else. Run `stand.py` first, keep the robot supported, and read what happens when the script exits before you run it. The script exits unless you set `ROBOT_SUPPORTED = True` at the top of the file. To stop on your own rule from `guard.py` before it moves anything, uncomment its two guard lines: ```python # guard(robot) # optional: uncomment this and the import to stop on your rule state = robot.get_state() # one sample: the pose to move from and back to start = state.joint_pos home = state.joint(JOINT).pos target = list(start) target[robot.info.joint_index(JOINT)] += TURN_RAD try: # Moves from the current pose over DURATION_S and returns within 0.05 rad of the # target. set_joints() holds it until the next verb. robot.set_joints(target, duration=DURATION_S) except (NotReadyError, WaitTimeoutError) as exc: # no live state, or the joints did not follow print(exc) sys.exit(1) print(f"{JOINT} moved from {home:.2f} to {robot.get_state().joint(JOINT).pos:.2f} rad") robot.set_joints(start, duration=DURATION_S) print(f"{JOINT} back at {robot.get_state().joint(JOINT).pos:.2f} rad") ``` From `examples/move_joints.py` in the menlo-sdk repository (the excerpt the page shows). `positions` is one radian value per actuator, `robot.info.dof` of them, in firmware order. `robot.info.joint_index(name)` gives the index of a named joint and `robot.info.joint_names` lists them all. `set_joints()` is sent in any robot mode; the firmware follows a trajectory in MOVE or in an armed STAND, and drops it in DAMP. It waits for live state, which also gives it a fresh pose to plan from; without live state it raises `NotReadyError` with nothing sent, and the script prints the message. > [!WARNING] > > **Support the robot in MOVE too** > > In MOVE the robot is usually standing free on its own balance. A `set_joints()` or a > `trajectory()` there turns the walking policy off, and a free-standing robot falls. The SDK > does not stop it. Before joint control in any robot mode, hang the robot from its gantry hook > or seat it on a stool or bench. `wait=False` returns once the plan is running. `timeout` bounds the whole call, the live-state check and the wait; left `None`, the check may wait 5 s and the target `duration + 2` s, and a joint that is not within `tolerance` by then raises `WaitTimeoutError`. The ankles are limited: 0.35 rad of pitch and 0.1 rad of roll. A target more than 0.02 rad past an ankle limit raises `ValueError` before anything is sent. ## Finish When a trajectory is left alone, the robot enters DAMP 2 s after the last setpoint. That is what happens when `move_joints.py` exits: the held target stops being re-sent and every actuator stops holding its position, which is why the robot must be supported. To end joint control on your own terms, send `damp()` yourself, with the robot still supported; see [Shutdown](https://docs.menlo.ai/sdk/safety.md#shutdown). ## Stream Your Own Setpoints `trajectory` is the raw form. Each call is one setpoint; you keep the clock, bound the loop, and end in DAMP: ```python import time deadline = time.monotonic() + 10.0 try: for target in controller: # one pose per tick, robot.info.dof values each if time.monotonic() > deadline: break robot.trajectory(target) # NotReadyError, nothing sent, on a stale stream time.sleep(0.02) # 50 Hz finally: robot.damp() # the robot is supported ``` Every `trajectory()` checks for live state once; on a live stream it reads one cached sample and adds no delay to the loop. The robot enters DAMP 2 s after the last setpoint, so a stalled loop leaves the robot in DAMP, not frozen in its last pose. `ValueError` when `len(positions) != robot.info.dof`, and for a target past an ankle limit. ## Gains Without `kp` and `kd`, the robot applies its own per-joint gain table. Pass both to override them, one value per joint; a lone `kp` or `kd` is a `ValueError`. A gain of 0 is not "no gain": the firmware substitutes its damping constants, so the joint does not hold a position. ## Which Command Is in Effect The firmware obeys whichever command arrived last. A `set_joints()` yields to any other verb: `damp()`, `stand()`, `balance()`, a velocity or a `trajectory()` from any thread ends it before its next setpoint leaves. A loop you clock with `trajectory()` does not. While it streams, a verb sent from another thread can be overwritten by your next setpoint, and nothing raises. Stop your loop, then send the verb. ## Wait for a Joint `wait_until.py` starts a `set_joints(wait=False)` and acts once the elbow has bent part of the way, with `robot.wait_until` reading the robot's own report. Like `move_joints.py`, it needs the robot supported and `ROBOT_SUPPORTED = True`, and carries the same two commented guard lines: ```python # guard(robot) # optional: uncomment this and the import to stop on your rule state = robot.get_state() # one sample: the pose to move from and back to start, home = state.joint_pos, state.joint(JOINT).pos target = list(start) target[robot.info.joint_index(JOINT)] += TURN_RAD try: robot.set_joints(target, duration=DURATION_S, wait=False) # returns at once, moving began = time.monotonic() passed = robot.wait_until(lambda s: s.joint(JOINT).pos >= home + PASS_RAD, timeout=5.0) except (NotReadyError, WaitTimeoutError) as exc: # no live state, a fault, or never got there print(exc) last = getattr(exc, "last", None) # the last state a wait saw, when there was one if last is not None and last.mode is Mode.DAMP: print("robot mode DAMP: the joints do not follow in DAMP, run stand.py first") sys.exit(1) took = time.monotonic() - began print(f"{JOINT} at {passed.joint(JOINT).pos:.2f} rad after {took:.1f} s of {DURATION_S} s") # A new set_joints() ends the first move where it is: back, and wait until there. robot.set_joints(start, duration=DURATION_S) print(f"{JOINT} back at {robot.get_state().joint(JOINT).pos:.2f} rad") ``` From `examples/wait_until.py` in the menlo-sdk repository (the excerpt the page shows). ## Related - [Safety](https://docs.menlo.ai/sdk/safety.md): faults, watchdogs, and what a fall latches - [Read State](https://docs.menlo.ai/sdk/state.md): `state.joints`, `state.joint(name)`, `info.joint_names` - [SDK Reference](https://docs.menlo.ai/sdk/reference.md#set_joints): `set_joints` and `trajectory` signatures --- # Read State > One snapshot of everything the robot reports, the facts `preflight()` reports, and how to wait on it. - Page: https://docs.menlo.ai/sdk/state - Section: Python SDK `robot.get_state()` returns the latest sample the robot reported, decoded: robot mode, joints, IMU, battery, alerts. Reading it costs nothing, because the robot streams it anyway. A field the robot does not report is `None`, never a guessed zero. `read_state.py` is a tour of the state: robot mode, arming, what latched, battery, the hottest actuators, gravity, state age and rate, alerts. It sends nothing and works in every connection mode. ```python # robot.get_state() is the latest sample the robot sent. It is a snapshot: read it again # for newer values. A field the robot does not report is None, never a guess. s = robot.get_state() # Robot mode: DAMP (no actuator holds a position), STAND (a held standing pose, no # balance) or MOVE (the walking policy balances the robot, at zero or any velocity). print(f"robot mode {s.mode.name}") # Armed: the firmware accepts MOVE only after STAND has been held upright for 0.5 s. # None means the SDK cannot tell (no gravity vector reported). print(f"armed {robot.armed}") # Faulted: a critical alert latched DAMP. The robot stays in DAMP, and error_flags stay # set, until the firmware restarts. The preflight check names what latched. print(f"faulted {s.faulted}") for problem in robot.preflight("stand").problems: if problem.code == "faulted": print(f" {problem.message}") # Battery, from the battery management system. None when the robot reports none. if s.battery is not None: b = s.battery print( f"battery {b.soc_percent:.0f} %, {b.voltage_v:.1f} V, {b.current_a:+.1f} A, " f"warmest cell {b.max_cell_temp_c:.0f} °C, protecting {b.protecting}" ) else: print("battery not reported") # Actuators: one Joint per actuator, with the firmware's name, position (rad), velocity # (rad/s), current (A) and temperature (°C). The firmware warns at 60 °C and latches # DAMP at 80 °C. temps = sorted(((j.temp, j.name) for j in s.joints if j.temp is not None), reverse=True) if temps: hottest = ", ".join(f"{name} {temp:.0f} °C" for temp, name in temps[:HOTTEST]) print(f"hottest {hottest}") else: print("hottest actuator temperatures not reported") # IMU: gravity as the body sees it. z is close to -1 when the robot is upright; # upright is True below -0.8. euler is (roll, pitch, yaw) in rad from the IMU quaternion. if s.gravity is not None: gx, gy, gz = s.gravity print(f"gravity ({gx:+.2f}, {gy:+.2f}, {gz:+.2f}), upright {s.upright}") if s.euler is not None: roll, pitch, yaw = s.euler print(f"orientation roll {roll:+.2f}, pitch {pitch:+.2f}, yaw {yaw:+.2f} rad") # Alerts the firmware reports now. Severity 0 is critical: it latches DAMP. alerts = [f"{a.name}{' (critical)' if a.critical else ''}" for a in s.alerts] print(f"alerts {', '.join(alerts) or 'none'}") # Freshness: how old the sample is. Decisions to move are made on samples at most # 0.5 s old; robot.preflight() reports stale_state beyond that. print(f"state age {s.age_s * 1000:.0f} ms") # The same fields as a stream, a few times a second. for _ in range(STREAM_LINES): time.sleep(STREAM_PERIOD_S) s = robot.get_state() now = time.monotonic() rate = sum(1 for t in tuple(arrivals) if now - t <= 1.0) battery = f"{s.battery.soc_percent:.0f} %" if s.battery else "n/a" print( f"{s.mode.name:5} armed {robot.armed} upright {s.upright} faulted {s.faulted} " f"battery {battery} age {s.age_s * 1000:.0f} ms rate {rate:.0f} Hz" ) ``` From `examples/read_state.py` in the menlo-sdk repository (the excerpt the page shows). | Field | Meaning | | - | - | | `state.mode` | `Mode.DAMP`, `Mode.STAND`, `Mode.MOVE`, `Mode.FAULT_DAMP` or `Mode.UNKNOWN` | | `state.joints` | one `Joint(name, pos, vel, current, temp)` per actuator, firmware order | | `state.joint("L_Knee")` | a joint by name; `KeyError` on an unknown name | | `state.joint_pos` | one radian value per actuator | | `state.gravity` | gravity projected into the body frame; z near -1 when upright | | `state.gyro`, `state.quat`, `state.euler`, `state.yaw` | angular rate, orientation, and heading in radians counter-clockwise | | `state.battery` | `Battery(voltage_v, current_a, soc_percent, max_cell_temp_c, protection)` or `None` | | `state.alerts`, `state.error_flags`, `state.faulted` | alerts and faults reported by the firmware | | `state.age_s` | seconds since this sample arrived | ## Check the Facts `robot.preflight(action)` reads the latest state and lists the facts for `"stand"`, `"move"` or `"trajectory"`: whether there is live state, a latched fault, active alerts, and in STAND whether the robot is armed. It sends nothing, never waits and never raises for a robot condition. `check.py` prints the raw facts and all three: ```python # The SDK counts the 0.5 s a robot in STAND must be upright to arm from its own samples. time.sleep(0.6) s = robot.get_state() # one sample: every fact below comes from it print(f"robot mode {s.mode.name}, armed {robot.armed}, faulted {s.faulted}") print(f"alerts {', '.join(a.name for a in s.alerts) or 'none'}") temps = [j.temp for j in s.joints if j.temp is not None] print(f"hottest joint {max(temps):.0f} C" if temps else "joint temperatures not reported") print(f"battery {s.battery.soc_percent:.0f} %" if s.battery else "battery not reported") print(f"state {s.age_s:.2f} s old") for action in ("stand", "move", "trajectory"): print(robot.preflight(action)) # "ready to move" means live state, and the facts ``` From `examples/check.py` in the menlo-sdk repository (the excerpt the page shows). `check.ok` is `True` when nothing is blocking, which means there is live state; `check.problems` lists the problems, blocking first, then information; `check.has(code)` tests one; `str(check)` is readable. Only `not_connected`, `no_state` and `stale_state` block; `faulted`, `alerts` and `not_armed` are information. Each code is in [What the SDK Reports](https://docs.menlo.ai/sdk/safety.md#what-the-sdk-reports). `stand()`, `balance()` outside MOVE, `set_velocity()`, `set_joints()` and `trajectory()` wait for live state before they send, up to `timeout` seconds, then raise `NotReadyError`, carrying `.preflight` and `.problems`, with nothing sent. Nothing else stops them: the robot mode, a fault, an alert, a hot actuator or a low battery is for your script to decide on, from `robot.get_state()`, as `guard.py` does; see [Write Your Own Guard](https://docs.menlo.ai/sdk/safety.md#write-your-own-guard). `robot.armed` is the arming test on its own: `True` in MOVE, or in STAND once the robot has been upright for 0.5 s; `False` in DAMP or before that; `None` without state, closed, in UNKNOWN, or in STAND with no gravity reported. ## Wait on the Robot Waits read the robot's own report, never a sleep. The code below moves the robot, so it belongs after the [checklist](https://docs.menlo.ai/sdk/safety.md#before-you-run-a-script) and [Standing and Balancing](https://docs.menlo.ai/sdk/safety.md#standing-and-balancing): ```python if robot.get_state().mode is Mode.DAMP: robot.stand() # returns once the robot reports STAND and is armed robot.balance() # returns once the robot reports MOVE robot.set_velocity(vx=0.2, duration=2.0) # checks the robot, then sends robot.wait_until(lambda s: s.mode is Mode.MOVE and s.upright, timeout=10.0) ``` `stand()`, `balance()`, `damp()`, `set_joints(wait=True)` and `wait_until` read the robot's report and raise `WaitTimeoutError` (also a `TimeoutError`) when the condition is not met in time, with `.last` holding the last state seen; `.sent` on a command carries what went out. A stream that goes quiet raises `StateStaleError` instead: a robot that did not reach the state and a stream that stopped need different fixes. A fault is checked before the predicate and raises `RobotFaultedError`, so a fall is never read as success. `stale_after` on `wait_until` defaults to the link timeout of 2 s. ## Upright `state.upright` is `True` when gravity z is below -0.8, about 37 degrees of tilt, and `None` when the robot reports no gravity: unknown and fallen are different answers. It is not the arming test; the firmware arms at -0.87, under 30 degrees, and `robot.armed` reads that. ## Faults `state.faulted` is `True` when `error_flags` is set or any alert is critical (severity 0). A critical alert, such as a fall, actuator over-temperature, battery protection, a joint past its limit, lost actuator communication or a watchdog, makes the firmware latch DAMP. It stays latched, and `error_flags` stay set, until the firmware restarts. The robot may report it as `Mode.FAULT_DAMP`. Commands are still sent; the waits of `stand()`, `balance()`, `set_velocity()`, `set_joints()` and `wait_until` raise `RobotFaultedError`; `preflight()` reports `faulted`; nothing a script sends clears it. `alert.name` is the firmware's name for an alert, `alert.critical` its severity test. ## What the SDK Knows About the Body ```python info = robot.info info.dof, info.joint_names # 25 and the firmware's actuator order on Asimov 1 info.capabilities # frozenset({'drive', 'state', 'battery', 'camera', ...}) info.protocol_version, info.limits, info.endpoint, info.transport ``` Joint names come from `menlo.asimov.robots.ASIMOV_1_BIPED_JOINTS`, chosen by the reported joint count. `robot.has("camera")` and `robot.require("drive", "battery")` test the capabilities; the set is what this connection carries, so it holds no media on udp. ## Callbacks For event-driven code, register a callback instead of polling. Callbacks run on the transport thread, the one that delivers state: keep them short. `robot.damp()` from a callback, such as `on_alert` damping on an alert, sends DAMP and returns at once. The other commands that wait for the robot, and `wait_until()`, raise `RuntimeError` there with nothing sent; pass `wait=False`, or call them from your own thread. | Callback | Arguments | | - | - | | `robot.on_state` | every accepted `State` | | `robot.on_mode_change` | `(before, after)`, both `Mode` | | `robot.on_alert` | `(alert, change)`, with `change` `"raised"` or `"cleared"` | | `robot.on_link_lost` | the `LinkLostError` | ## Related - [Move the Robot](https://docs.menlo.ai/sdk/move.md): what to do once the robot is ready - [Safety](https://docs.menlo.ai/sdk/safety.md#what-the-sdk-reports): every preflight code - [SDK Reference](https://docs.menlo.ai/sdk/reference.md#state): every field and type --- # Camera and Audio > Frames, clips, microphone and speaker over the robot's LiveKit room, on hybrid and livekit. - Page: https://docs.menlo.ai/sdk/media - Section: Python SDK The robot publishes its camera and microphone as tracks in its LiveKit room and plays an audio track you publish. The SDK carries them in the `hybrid` and `livekit` connection modes; `udp` carries drive and state only. One `pip install menlo-sdk` covers all of it. ## Ask First Capabilities are what this connection carries, so test rather than assume: ```python if robot.has("camera"): frame = robot.camera.photo() robot.require("drive", "camera") # UnsupportedError when one is missing robot.info.capabilities # frozenset({'drive', 'state'}) on udp ``` The full set is `drive`, `state`, `battery`, `camera`, `microphone` and `speaker`. A capability is claimed from a track that arrived within `media_timeout` (3 s) of connecting. A room that publishes no video makes `robot.has("camera")` `False` and `robot.camera` raise `UnsupportedError`, rather than hand out a stream that never yields. ## A Photo, a Clip and a Tone `camera_and_audio.py` saves a photo and a short clip with sound, then plays a tone on the speaker. It moves nothing and needs the `hybrid` or `livekit` connection mode: ```python if robot.has("camera"): photo = robot.camera.photo() # the next fresh frame, rgb8 Path(PHOTO).write_bytes(photo.to_jpeg()) print(f"saved {PHOTO}, {photo.width}x{photo.height}") clip = robot.camera.capture_clip(CLIP_S, audio=robot.has("microphone")) frames = clip.save_frames(CLIP_DIR) print(f"saved {len(frames)} frames to {CLIP_DIR}/ at {clip.fps:.1f} fps") if clip.audio: print("saved", clip.save_wav(CLIP_WAV)) else: print("this connection carries no camera; use hybrid or livekit") if robot.has("speaker"): # 16-bit mono PCM: a sine wave at TONE_HZ for TONE_S. tone = b"".join( struct.pack("= SECONDS: break with wave.open(PATH, "wb") as wav: wav.setnchannels(chunks[0].channels) wav.setsampwidth(2) # 16-bit samples wav.setframerate(chunks[0].sample_rate_hz) wav.writeframes(b"".join(c.data for c in chunks)) print(f"saved {PATH}, {recorded_s:.1f} s at {chunks[0].sample_rate_hz} Hz") ``` From `examples/record_audio.py` in the menlo-sdk repository (the excerpt the page shows). `chunks()` yields `AudioChunk`s in order, 16-bit PCM, each with `data`, `sample_rate_hz`, `channels` and `duration_s`; it raises `WaitTimeoutError` when the microphone is quiet for `timeout` (5 s). A consumer that falls behind loses chunks, counted in `microphone.dropped`. ## Play a Sound `play_audio.py` plays a WAV file, `hello.wav` in the directory you run it from, on the robot's speaker, one second at a time. With no `hello.wav` there, it plays a one-second 440 Hz tone: ```python if not robot.has("speaker"): print("this connection carries no speaker; use hybrid or livekit") sys.exit(1) if os.path.exists(PATH): with wave.open(PATH, "rb") as wav: if wav.getsampwidth() != 2: print(f"{PATH} is not 16-bit PCM; convert it first") sys.exit(1) rate, channels = wav.getframerate(), wav.getnchannels() pcm = wav.readframes(wav.getnframes()) name = PATH else: # 16-bit mono PCM: one second of a 440 Hz sine wave rate, channels, name = 16_000, 1, f"a 440 Hz tone (no {PATH} here)" pcm = b"".join( struct.pack(" Every state sample and every command as JSON lines, and how to read the file back. - Page: https://docs.menlo.ai/sdk/recording - Section: Python SDK `robot.record(path)` writes every state sample the robot sent and every command the script sent to one file, one JSON object per line, in order. Nothing is sampled or averaged. `record_and_replay.py` records a few seconds of state, then reads the file back. It sends nothing to the robot: ```python # Every state sample and every command sent while the block runs goes to PATH. with Robot().connect() as robot, robot.record(PATH) as recording: time.sleep(SECONDS) print(f"recorded {recording.samples} states and {recording.commands_written} commands") # Each line is one JSON object; "kind" says whether it is a state or a command. lines = list(load(PATH)) states = [line for line in lines if line["kind"] == "state"] print("robot modes seen:", dict(Counter(s["mode"] for s in states))) if len(states) > 1: rate = (len(states) - 1) / (states[-1]["t"] - states[0]["t"]) print(f"state rate {rate:.0f} Hz") ``` From `examples/record_and_replay.py` in the menlo-sdk repository (the excerpt the page shows). `record` is a context manager: recording stops when the block exits, including when it exits because of an exception, which is the run you want the file for. `recording.samples` and `recording.commands_written` count what went in. ## Read It Back `menlo.asimov.recording.load(path)` yields one dict per line. `kind` is `"state"` or `"sent"`, `t` is `time.monotonic()` when the line was written (subtract the first line's `t` for the time since the recording began), and a state line carries the robot mode as `mode` beside the fields of `State`. ## What It Is Good For | Use | Why | | - | - | | **A bug report** | a fall or a robot that did not move is easier to read from the file than to describe | | **Comparing runs** | the same script on two robots, or before and after a change, gives two files with the same shape | | **Checking a loop** | the `t` of the `sent` lines shows whether a control loop held its rate | ## Related - [Read State](https://docs.menlo.ai/sdk/state.md): the fields in a state line - [SDK Reference](https://docs.menlo.ai/sdk/reference.md#recording): `record`, `Recording` and `load` --- # Command Line > menlo: save a robot, check it, and stand, balance, walk and damp it from a terminal. - Page: https://docs.menlo.ai/sdk/cli - Section: Python SDK `pip install menlo-sdk` installs the `menlo` command. It saves robots for the SDK and drives one through the same verbs a script uses. `stand`, `balance`, `walk` and `damp` show what they are about to do, with the robot's facts, and ask before they send anything. The facts are for you to judge: no command refuses because of them, and the firmware decides what a command does. The one refusal is no live state. `balance` on a robot already in MOVE sends at once without asking. Every command is sent to the robot; none is an emergency stop. ```bash menlo --robot NAME --mode {udp,hybrid,livekit} menlo --version menlo -h ``` `--robot` picks a saved robot, `--mode` overrides its connection mode for this command. Without them, the command uses `MENLO_ROBOT`, then the default saved robot, then the only saved robot. ## Setup ```bash menlo setup ``` The wizard asks for a name, a connection mode, and only the fields that mode needs: the robot's address for `udp`, the Asimov Manager URL and an SDK credential for `livekit`, both for `hybrid`. The credential is typed masked and never printed back. Each field is checked live before it is saved: | Check | What passes | | - | - | | **Credential** | `accepted, role control, room robot-...`; a credential with the Observe role saves with a warning: it can watch, not drive over livekit | | **udp** | state arrives from the address; the message names the robot mode it saw | | **livekit** | the room is joined; the message lists the tracks it found | A failed check asks "Save anyway?". When another robot is already the default, the wizard asks whether this one should be. `--no-check` skips the live checks. The wizard needs a terminal; without one it exits 2. SDK credentials come from the Developer page in Asimov Manager; [Drive from Python](https://docs.menlo.ai/asimov/1/operate/drive/python-sdk.md#get-an-sdk-credential) shows the steps. Saved robots live in `~/.menlo/robots.toml`, readable only by you. ## Robots ```bash menlo robots # table: default mark, name, mode, address, manager, room menlo robots add lab --mode hybrid --udp 192.168.1.20 --manager https://manager.example --credential ... menlo robots add lab --limits 0.3,0.3,0.6 menlo robots use lab menlo robots remove lab ``` `add` on an existing name keeps the saved values it is not given, so the second `add` above only sets limits. Flags it needs and does not have are asked for in a terminal; with `--no-input`, missing flags exit 2. `--default` makes the robot the default; `--no-check` skips the live check. With every flag it needs, or with `--no-input`, a failed check saves nothing and exits 1; in the wizard, you can choose to save despite a failed check. `use` and `remove` exit 1 on a name that is not saved. ## Status ```bash menlo status menlo status --watch ``` Connects, reads state for a second, and prints a panel: the robot, its connection mode and address; a badge, NOT READY when there is no live state, FAULTED when the firmware latched DAMP, READY otherwise, with the reason; the robot mode and whether it is armed; battery; the hottest joint; faults; alerts; the state rate; and whether the state is fresh. It sends nothing. `--watch` refreshes until `q` or Ctrl-C. ## Stand, Balance, Walk, Damp ```bash menlo stand menlo balance menlo walk --vx 0.2 --duration 3 menlo walk --vyaw 0.3 --duration 2 menlo damp ``` | Command | What it does | | - | - | | `stand` | from any robot mode. A robot already in STAND is sent nothing; if it has not armed, `menlo stand` waits up to 10 s for it to arm and exits 3 when it does not. From MOVE it first warns to hang the robot from its gantry hook or seat it on a stool or bench: STAND has no balance loop. Asks, sends `stand()` and waits up to 10 s for the robot to report STAND and arm, then prints `Armed: ready to balance, menlo balance`. Exit 3 when it does not arm | | `balance` | outside MOVE, asks, sends zero velocity and waits up to 5 s for the robot to report MOVE, then prints `Balancing in MOVE: ready to walk, e.g. menlo walk --vx 0.3 --duration 3`. From DAMP or an unarmed STAND it exits 3 saying why. In MOVE, never asks: sends zero velocity twice, 0.1 s apart, and the robot stays in MOVE, balancing in place. A script that holds a velocity re-sends it at 10 Hz and must itself be stopped | | `walk` | `--duration` is required, above 0 and at most 10 s; at least one of `--vx`, `--vy`, `--vyaw` must be nonzero. Asks, holds the velocity for the duration, then sends zero velocity: the robot stays in MOVE, balancing in place. The firmware walks in MOVE only: a walk that leaves the robot outside MOVE exits 3 with `Run menlo balance first`. Ctrl-C sends zero velocity and exits 130. A fault that ends the walk early is named, with a note that it latches until the firmware restarts, and exits 3 | | `damp` | asks, sends `damp()` and waits up to 10 s for the robot to report DAMP, then prints `Robot mode DAMP.`, or the fault that holds it. Hang the robot from its gantry hook or seat it on a stool or bench first | > [!WARNING] > > **damp is not an emergency stop** > > DAMP makes every actuator compliant: a standing robot folds to the ground, so hang it from > its gantry hook or seat it on a stool or bench first. In an emergency use the **E-Stop** in > Asimov Manager, or cut power at the battery unit; see > [Stopping the Robot](https://docs.menlo.ai/asimov/1/operate/safety/stopping.md). ### Confirm Before Sending `stand`, `balance` outside MOVE, `walk` and `damp` print one line: the robot, its connection mode and address, the robot's facts (robot mode, armed, faults, active alerts, the hottest joint, battery), and what will happen. Then they ask `Proceed? [y/N]`. ```text $ menlo walk --vx 0.2 --duration 3 lab (hybrid, 192.168.22.32) · MOVE · armed · faults none · alerts none · hottest joint 41 C (L_Knee) · battery 82 % → walk vx 0.20 m/s, vy 0.00 m/s, vyaw 0.00 rad/s for 3.0 s, then balance in place Proceed? [y/N] y Walking. Ctrl-C ends the walk. Walk done. Robot mode MOVE, balancing in place. ``` ```text $ menlo stand lab (udp, 192.168.22.32) · DAMP · faults none · alerts none · hottest joint 38 C (L_Knee) · battery 82 % → stand, then wait until armed Proceed? [y/N] y Standing. Waiting for the robot to arm (0.5 s upright)... Armed: ready to balance, menlo balance ``` ```text $ menlo balance lab (udp, 192.168.22.32) · STAND · armed · faults none · alerts none · hottest joint 41 C (L_Knee) · battery 82 % → balance: MOVE at zero velocity, the walking policy balances the robot Proceed? [y/N] y Balancing in MOVE: ready to walk, e.g. menlo walk --vx 0.3 --duration 3 ``` ```text $ menlo damp lab (udp, 192.168.22.32) · MOVE · armed · faults none · alerts none · hottest joint 45 C (L_Knee) · battery 80 % → damp: every actuator stops holding its position and a standing robot falls, so the robot must be supported. Not an emergency stop: use the E-Stop in Asimov Manager, or cut power at the battery unit. Proceed? [y/N] ``` 1. Read the line and judge the facts: a fault, an alert, a hot joint or a low battery does not stop the command. A speed above the robot's velocity limits shows the value that is sent, then the one you asked for, for example `vx 0.40 m/s (asked 0.60)`. 2. Type `y` and press Enter to go ahead. Enter alone, or anything else, cancels: the command prints `Cancelled; nothing sent.` and exits 4. `-y` or `--yes` prints the line and goes ahead without asking. With no terminal to ask on and no `--yes`, the command sends nothing and exits 2. ### Not Feasible The one refusal is no live state. Before the plan, `stand`, `balance` and `walk` check for a fresh state sample. Without one they do not ask: they print `Not feasible:` on stderr, send nothing and exit 3: ```text Not feasible: no fresh state from lab: the latest state is 1.2 s old (limit 0.5 s). Check the link with `menlo status`. ``` On `udp` or `hybrid`, a robot that never reports state is often a firewall; see [No State on udp or hybrid](https://docs.menlo.ai/sdk/troubleshooting.md#no-state-on-udp-or-hybrid). A command that was sent and did not get there also exits 3, with what the robot reports: `balance` in DAMP (`the robot is in DAMP: stand() first`), `balance` on a robot that has not armed, `walk` that left the robot outside MOVE, a `stand` that does not arm within 10 s, and a fault during a command. ## For Scripts and Other Programs `menlo robots --json` and `menlo status --json` print one JSON object and nothing else. `--yes` runs `stand`, `balance`, `walk` and `damp` without a question; branch on the exit code. A script or another program runs `menlo status --json` first, judges the facts itself, then runs `menlo balance --yes` and `menlo walk ... --yes`: ```bash menlo status --json | jq '.ready, .robot_mode, .faults, .alerts, .max_joint_temp_c' menlo walk --vx 0.2 --duration 3 --yes ``` `status` carries `robot`, `mode`, `host`, `verdict`, `ready` (there is live state), `problems` (each with `code`, `message`, `blocking`), `robot_mode`, `armed`, `battery_percent`, `faults`, `alerts`, `error_flags`, `max_joint_temp_c`, `state_rate_hz`, `state_age_s` and `fresh`. `robots` carries `default` and a `robots` list with `name`, `default`, `mode`, `udp_host`, `manager_url`, `room`, `credential_saved` and `limits`; the credential itself is never printed. ## Exit Codes | Code | Meaning | | - | - | | **0** | done | | **1** | an error; the message is `menlo : ` on stderr | | **2** | usage: a missing flag, a bad value, a wizard without a terminal, or a question with no terminal and no `--yes` | | **3** | not feasible or not reached: no live state (`Not feasible:` is printed, nothing sent), or the command was sent and the robot did not get there (not armed in time, still in DAMP, a fault) | | **4** | cancelled: you answered no; nothing was sent | | **130** | interrupted with Ctrl-C | ## Related - [Connection Modes](https://docs.menlo.ai/sdk/connection-modes.md): what each mode needs - [Safety](https://docs.menlo.ai/sdk/safety.md#standing-and-balancing): the stand, balance, walk, damp sequence and why - [What the SDK Reports](https://docs.menlo.ai/sdk/safety.md#what-the-sdk-reports): every code `preflight()` reports - [SDK Reference](https://docs.menlo.ai/sdk/reference.md#store-and-cli): the store the CLI writes --- # Without the SDK > State, commands, camera and audio over the robot's LiveKit room with the livekit and asimov-protocol packages alone. - Page: https://docs.menlo.ai/sdk/without-the-sdk - Section: Python SDK The robot's LiveKit room carries everything the `livekit` connection mode uses: state and commands as data messages, the camera and the microphone as tracks. Any LiveKit client can join it. This page shows how, in Python, without `menlo-sdk`; the scripts are in the `livekit_raw/` folder of the [examples](https://docs.menlo.ai/sdk/examples.md#without-the-sdk). ```bash pip install livekit asimov-protocol export MENLO_CREDENTIAL=... # an SDK credential from Asimov Manager ``` `asimov-protocol` holds the protobuf messages; `RobotState` and `RobotCommand` are what the SDK sends and reads. Set `MANAGER_URL` in `manager_token.py` to your Asimov Manager address. The role of the credential applies: an Observe credential can read state and the tracks but its commands are dropped ([Connection Modes](https://docs.menlo.ai/sdk/connection-modes.md#livekit)). > [!WARNING] > > **These scripts skip what the SDK does for you** > > No limits, no link watchdog, no zero velocity on exit and no fence between commands. Run > `send_commands.py` only with the robot hanging from its gantry hook, and keep Asimov > Manager open at the **E-Stop**. Work through > [Before You Run a Script](https://docs.menlo.ai/sdk/safety.md#before-you-run-a-script) first. ## A Join Token Asimov Manager issues join tokens at `POST /api/livekit/token` to a request that carries an SDK credential as a Bearer token. The answer names the LiveKit `url`, the `room`, the `token`, your participant `identity` and the credential's `role`. `manager_token.py` fetches one; it refuses redirects, so the credential is never forwarded to another host, and it rewrites a `localhost` LiveKit URL to the manager's host, which is what a robot that runs its own LiveKit server reports. ```python class NoRedirect(urllib.request.HTTPRedirectHandler): """Refuse every redirect: urllib would send the credential on to the new address.""" def redirect_request(self, *args: Any, **kwargs: Any) -> None: return None def fetch_grant(manager: str = MANAGER_URL, credential: str = CREDENTIAL) -> dict[str, Any]: """The LiveKit URL, the robot's room and a join token, from Asimov Manager.""" if not credential: sys.exit("Set MENLO_CREDENTIAL to an SDK credential from Asimov Manager.") request = urllib.request.Request( manager.rstrip("/") + "/api/livekit/token", data=b"{}", method="POST", headers={"Authorization": f"Bearer {credential}", "Content-Type": "application/json"}, ) with urllib.request.build_opener(NoRedirect).open(request, timeout=5) as response: grant: dict[str, Any] = json.load(response) # url, room, token, identity, role # The URL is the one the robot uses itself; localhost there is Asimov Manager's host. url = urlsplit(grant["url"]) if url.hostname in ("localhost", "127.0.0.1"): host = urlsplit(manager).hostname or "" netloc = host if url.port is None else f"{host}:{url.port}" grant["url"] = url._replace(netloc=netloc).geturl() return grant ``` From `examples/livekit_raw/manager_token.py` in the menlo-sdk repository (the excerpt the page shows). The other scripts in the folder import `fetch_grant()` from this file. ## Read State The robot publishes `RobotState` on the `state` data track at the firmware's state rate. `read_state.py` joins, decodes each message with `RobotState.FromString` and prints the mode, protocol version and sequence number for 5 s: ```python async def print_states(track: rtc.RemoteDataTrack) -> None: async for frame in track.subscribe(): state = asimov_state_pb2.RobotState.FromString(bytes(frame.payload)) mode = asimov_common_pb2.ControlMode.Name(state.current_mode) print(f"{mode} protocol {state.protocol_version} sequence {state.sequence}") async def main() -> None: grant = fetch_grant() room = rtc.Room() readers: set[asyncio.Task[None]] = set() def on_data_track(track: rtc.RemoteDataTrack) -> None: if track.info.name == "state": task = asyncio.ensure_future(print_states(track)) readers.add(task) # keep a reference so the task is not collected task.add_done_callback(readers.discard) room.on("data_track_published", on_data_track) await room.connect(grant["url"], grant["token"]) try: await asyncio.sleep(SECONDS) finally: await room.disconnect() ``` From `examples/livekit_raw/read_state.py` in the menlo-sdk repository (the excerpt the page shows). `current_mode` is the firmware's mode enum, `error_flags` the latched fault bits, and `active_alerts` the current alerts. The field list is in [The Protocol](https://docs.menlo.ai/sdk/reference.md#the-protocol). ## Send a Command Commands are `RobotCommand` messages published as reliable data on the `commands` topic. Each carries `protocol_version = 1`, a `sequence` you increment, and `timestamp_us`. The robot drops a command whose protocol version it does not speak, and reports nothing. A robot whose participant attribute `asimov.commands_track` is `"1"` also reads a data track named `commands` that you publish. Use it for a stream of setpoints, a velocity or a trajectory: a lost frame is replaced by the next, where a lost packet holds the rest back until it is resent. Every frame needs its `sequence`, and the robot drops a setpoint older than a command it already took from you, so keep STAND, DAMP and a zero velocity on the topic. `send_commands.py` keeps a guard of its own, always on, unlike `guard.py` in the SDK examples: it listens to state for 2 s and sends nothing when the state is stale, the protocol version is wrong, a critical alert or `error_flags` is set, the battery is protecting itself or below 20 %, or an actuator is at 60 °C or more. The limits are constants at the top of the file; change them as you need. If the robot is in DAMP, it sends one STAND and exits. ```python reason = why_not_stand(*latest) if latest else "no state received" if reason is not None: print("not sending STAND:", reason) return 1 payload = command(asimov_common_pb2.CONTROL_MODE_STAND) await room.local_participant.publish_data(payload, reliable=True, topic="commands") ``` From `examples/livekit_raw/send_commands.py` in the menlo-sdk repository (the excerpt the page shows). A velocity is the same message with `set_velocity` filled in. Without the SDK, nothing re-sends it, so send zero velocity yourself before you leave the room. Asimov Edge stops a held velocity when a participant sends zero or leaves the room ([Watchdogs](https://docs.menlo.ai/sdk/safety.md#watchdogs)). ## Camera The camera is the robot's video track. `camera.py` subscribes, takes one frame from a `VideoStream`, converts it to RGB and writes `frame.ppm`: ```python async def save_one_frame(track: rtc.Track, done: asyncio.Future[str]) -> None: stream = rtc.VideoStream(track) async for event in stream: rgb = event.frame.convert(rtc.VideoBufferType.RGB24) header = f"P6 {rgb.width} {rgb.height} 255\n".encode() Path(PATH).write_bytes(header + bytes(rgb.data)) done.set_result(f"saved {PATH}, {rgb.width}x{rgb.height}") break await stream.aclose() async def main() -> None: grant = fetch_grant() room = rtc.Room() done: asyncio.Future[str] = asyncio.get_running_loop().create_future() tasks: set[asyncio.Task[None]] = set() def on_track(track: rtc.Track, *_: object) -> None: if track.kind == rtc.TrackKind.KIND_VIDEO and not tasks: tasks.add(asyncio.ensure_future(save_one_frame(track, done))) room.on("track_subscribed", on_track) await room.connect(grant["url"], grant["token"]) try: print(await asyncio.wait_for(done, TIMEOUT_S)) finally: await room.disconnect() ``` From `examples/livekit_raw/camera.py` in the menlo-sdk repository (the excerpt the page shows). ## Audio The microphone is the robot's audio track. `audio.py` reads an `AudioStream` for a few seconds and writes `microphone.wav`: ```python async def record(track: rtc.Track, done: asyncio.Future[str]) -> None: stream = rtc.AudioStream(track) chunks: list[bytes] = [] rate = channels = 0 async for event in stream: frame = event.frame rate, channels = frame.sample_rate, frame.num_channels chunks.append(bytes(frame.data)) if sum(len(c) for c in chunks) >= SECONDS * rate * channels * 2: break await stream.aclose() with wave.open(PATH, "wb") as wav: wav.setnchannels(channels) wav.setsampwidth(2) # 16-bit samples wav.setframerate(rate) wav.writeframes(b"".join(chunks)) done.set_result(f"saved {PATH}, {SECONDS:.0f} s at {rate} Hz") async def main() -> None: grant = fetch_grant() room = rtc.Room() done: asyncio.Future[str] = asyncio.get_running_loop().create_future() tasks: set[asyncio.Task[None]] = set() def on_track(track: rtc.Track, *_: object) -> None: if track.kind == rtc.TrackKind.KIND_AUDIO and not tasks: tasks.add(asyncio.ensure_future(record(track, done))) room.on("track_subscribed", on_track) await room.connect(grant["url"], grant["token"]) try: print(await asyncio.wait_for(done, SECONDS + TIMEOUT_S)) finally: await room.disconnect() ``` From `examples/livekit_raw/audio.py` in the menlo-sdk repository (the excerpt the page shows). To play sound on the robot, publish an audio track of your own; the robot plays it on its speaker. ## Related - [Connection Modes](https://docs.menlo.ai/sdk/connection-modes.md): the `livekit` mode and the SDK credential - [Camera and Audio](https://docs.menlo.ai/sdk/media.md): the same tracks through the SDK - [Safety](https://docs.menlo.ai/sdk/safety.md): what the SDK adds on top of the wire, and what it does not - [SDK Reference](https://docs.menlo.ai/sdk/reference.md#the-protocol): the protocol messages - [Robot API](https://docs.menlo.ai/asimov/1/program/api.md): the HTTP API of Asimov Manager --- # Coding Agents > Give a coding agent the menlo-sdk skill and the docs, so the scripts it writes use the SDK the way it expects. - Page: https://docs.menlo.ai/sdk/coding-agents - Section: Python SDK A coding agent writes better scripts for Asimov when it knows how the SDK behaves: which command does what, what the robot must be doing first, and that guards are the script's job. Two things give it that: the **menlo-sdk skill**, a usage guide the agent loads when you ask it for robot code, and the docs as plain text in **llms.txt**. > [!WARNING] > > **The agent drives a real robot** > > A script an agent writes moves the robot like any other script. Read it before you run it, > and follow [Safety](https://docs.menlo.ai/sdk/safety.md): support the robot, hanging from its gantry hook or seated > on a stool or bench, and keep the E-Stop in Asimov Manager open, or be ready to cut power at > the battery unit. ## Install the Skill The skill is in the [skills/menlo-sdk](https://github.com/menloresearch/menlo-sdk/tree/main/skills/menlo-sdk) folder of the SDK repository, in the Agent Skills format, so most coding agents can load it. ### Claude Code Add the repository as a plugin marketplace, then install the plugin: ```text /plugin marketplace add menloresearch/menlo-sdk /plugin install menlo-sdk@menlo ``` `/plugin` then lists `menlo-sdk@menlo`, and the skill is `menlo-sdk:menlo-sdk`. To get a newer version later, run `/plugin update menlo-sdk@menlo`. ### Codex, pi, oh-my-pi and Other Agents Install it with the `skills` installer: ```bash npx skills add menloresearch/menlo-sdk ``` It copies the skill to `~/.agents/skills/menlo-sdk`, the folder Codex, pi and oh-my-pi read, and links it for the other agents it finds on your computer. Add `-g -y` to skip the questions. ### By Hand Copy the `skills/menlo-sdk` folder from the repository into the skills folder your agent reads: `~/.agents/skills/` for Codex, pi and oh-my-pi, or `~/.claude/skills/` for Claude Code. ## Try It Ask your agent for a script, for example: ```text Using menlo-sdk, walk my Asimov forward at 0.3 m/s for 3 s and end balancing in place. ``` With the skill, the answer uses the SDK's own calls: ```python robot.set_velocity(vx=0.3, duration=3.0) # walks for 3 s, then sends zero velocity robot.balance() # stays in MOVE, balancing in place ``` ## What the Skill Teaches - How to connect in each [connection mode](https://docs.menlo.ai/sdk/connection-modes.md) and what each one carries. - The commands, what each waits for, and the errors they raise. - That the SDK does not refuse a command because of what the robot reports, so a script writes its own guard from `robot.get_state()`, as [guard.py](https://docs.menlo.ai/sdk/safety.md#write-your-own-guard) does. - The order to bring the robot up and down: support it before MOVE to STAND and before DAMP. - Where the full documentation is. ## Give an Agent the Docs For an agent without the skill, or for questions the skill does not cover, point it at the docs as plain text: | File | What it holds | | - | - | | [llms.txt](https://docs.menlo.ai/llms.txt) | An index of every docs page, one line each, with a short glossary; the SDK pages are under "Python SDK" | | [sdk/llms-full.txt](https://docs.menlo.ai/sdk/llms-full.txt) | The full text of every SDK page in one file | | [llms-full.txt](https://docs.menlo.ai/llms-full.txt) | The full text of every docs page in one file | Each page is also available as Markdown: add `.md` to its URL, for example [sdk/quickstart.md](https://docs.menlo.ai/sdk/quickstart.md). Other sections with more than one page have their own `llms-full.txt` under the section's URL, and llms.txt links to each one. ## Related - [Quickstart](https://docs.menlo.ai/sdk/quickstart.md): the first walk, step by step - [Safety](https://docs.menlo.ai/sdk/safety.md): what to check before a script moves the robot, and writing a guard - [Examples](https://docs.menlo.ai/sdk/examples.md): the scripts the skill points to --- # Examples > The runnable scripts that ship with the SDK, grouped by what they show. - Page: https://docs.menlo.ai/sdk/examples - Section: Python SDK Each file is one short, runnable script, kept in the [examples](https://github.com/menloresearch/menlo-sdk/tree/main/examples) directory of the SDK repository. Every script except `connect.py` and the `livekit_raw/` scripts connects to the saved robot (`menlo setup`), or to the robot the `MENLO_*` environment variables describe; set `MENLO_ROBOT=NAME` to pick another saved robot. The settings a script uses, such as a speed, a duration or a joint name, are constants at the top of the file. Read the docstring at the top of a file before you run it: it says what the robot must be doing. Before a script that moves the robot, work through [Before You Run a Script](https://docs.menlo.ai/sdk/safety.md#before-you-run-a-script). A script with a **Run** button runs on a simulated Asimov 1: the robot opens in the corner of the page. Its questions about supporting the robot are answered yes there, since the simulation holds the robot up. The SDK sends what a script asks and reports what the robot says; it refuses a command only when there is no live state. A guard is yours: `guard.py` is an example of one, and no script uses it by default. Each motion script carries two commented guard lines; uncomment them to stop the script, before it sends anything, when the robot reports what your rule will not drive through, and edit the limits in `guard.py`. Nothing here is an emergency stop: use the E-Stop in Asimov Manager, or cut power at the battery unit. ```bash pip install menlo-sdk git clone https://github.com/menloresearch/menlo-sdk.git cd menlo-sdk python examples/check.py ``` ## Check and Guard | Script | What it shows | | - | - | | [check.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/check.py) (runs on the simulated robot) | the robot's facts (robot mode, armed, faults, alerts, the hottest joint, battery, state age) and `preflight()` for stand, move and trajectory; sends nothing | | [guard.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/guard.py) (runs on the simulated robot) | an optional guard of your own: joint temperature, battery, a latched fault and active alerts, with limits at the top of the file; prints what it finds and exits with status 1 when the rule fails. Off by default: the motion scripts carry it commented out | ## Connect | Script | What it shows | | - | - | | [connect.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/connect.py) | the `udp`, `hybrid` and `livekit` configs side by side in code; set `MODE` at the top and it prints the endpoint, robot mode, arming, battery and capabilities | ## State | Script | What it shows | | - | - | | [read_state.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/read_state.py) (runs on the simulated robot) | a tour of `robot.get_state()`: mode, arming, faults, battery, the hottest actuators, gravity, alerts, state age and rate, and the mode and alert callbacks | ## Stand, Balance, Walk, Rest, Damp Run them in this order, with the robot on its feet, hanging from its gantry hook. | Script | What it shows | | - | - | | [stand.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/stand.py) (runs on the simulated robot) | `stand()` from any robot mode; it returns once the robot is armed, and the script prints the `NotReadyError` or `WaitTimeoutError` otherwise. From MOVE, hang the robot from its gantry hook or seat it on a stool or bench first | | [balance.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/balance.py) (runs on the simulated robot) | `balance()` from an armed STAND: the robot enters MOVE and balances in place; the script prints the `NotReadyError` or `WaitTimeoutError` otherwise | | [walk.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/walk.py) (runs on the simulated robot) | a bounded `set_velocity(duration=3.0)` in MOVE: the SDK holds the velocity, sends zero, and the robot balances in place; reports `sent.clamped`. Walking in MOVE only is the script's own rule | | [stream_velocity.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/stream_velocity.py) (runs on the simulated robot) | `set_velocity(hold=False)` from your own 50 Hz loop, one packet per tick, then `balance()`; MOVE only, the script's own rule | | [rest.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/rest.py) (runs on the simulated robot) | MOVE to STAND to DAMP, after asking whether the robot is on its gantry hook or seated on a stool or bench; prints each robot mode | | [damp.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/damp.py) (runs on the simulated robot) | `damp()` on a supported robot, after asking; it returns once the robot reports DAMP | ## Keyboard | Script | What it shows | | - | - | | [keyboard.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/keyboard.py) | drive from the keyboard with short bounded holds: `w`/`s` walk, `a`/`d` strafe, `q`/`e` turn, space `balance()`, `t` stand (asks first in MOVE), `b` damp after asking, `x` quit | ## Joints | Script | What it shows | | - | - | | [move_joints.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/move_joints.py) (runs on the simulated robot) | `set_joints()` on one named joint, on a supported robot; exits unless `ROBOT_SUPPORTED = True` is set in the file; the robot enters DAMP 2 s after the script exits | | [wait_until.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/wait_until.py) (runs on the simulated robot) | `set_joints(wait=False)`, then `wait_until()` acts the moment the joint passes an angle in the robot's own report, on a supported robot; exits unless `ROBOT_SUPPORTED = True` | ## Media | Script | What it shows | | - | - | | [camera_and_audio.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/camera_and_audio.py) (runs on the simulated robot) | a photo, a short clip saved as JPEG frames with its sound as WAV, and a tone on the speaker; `hybrid` or `livekit` | | [record_audio.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/record_audio.py) (runs on the simulated robot) | three seconds of the microphone saved as WAV | | [play_audio.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/play_audio.py) (runs on the simulated robot) | a WAV file played on the robot's speaker, one second at a time | ## Recording | Script | What it shows | | - | - | | [record_and_replay.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/record_and_replay.py) (runs on the simulated robot) | `robot.record()` for three seconds, then reading the file back with `recording.load()` | ## Without the SDK The scripts in `livekit_raw/` use only the `livekit` and `asimov-protocol` packages; see [Without the SDK](https://docs.menlo.ai/sdk/without-the-sdk.md). They read `MENLO_CREDENTIAL` and the `MANAGER_URL` set in `manager_token.py`. | Script | What it shows | | - | - | | [livekit_raw/manager_token.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/livekit_raw/manager_token.py) | a join token from Asimov Manager; the other scripts in the folder import it | | [livekit_raw/read_state.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/livekit_raw/read_state.py) | `RobotState` from the `state` data track for 5 s | | [livekit_raw/send_commands.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/livekit_raw/send_commands.py) | its own guard by hand, then one STAND `RobotCommand` on the `commands` topic; the robot must hang from its gantry hook | | [livekit_raw/camera.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/livekit_raw/camera.py) | one frame from the video track, saved as PPM | | [livekit_raw/audio.py](https://github.com/menloresearch/menlo-sdk/blob/main/examples/livekit_raw/audio.py) | the microphone track, saved as WAV | ## Related - [Quickstart](https://docs.menlo.ai/sdk/quickstart.md): check, stand, balance, walk and damp, step by step - [Safety](https://docs.menlo.ai/sdk/safety.md#write-your-own-guard): writing your own guard, and bringing the robot to rest - [Command Line](https://docs.menlo.ai/sdk/cli.md): the same verbs without writing a script --- # SDK Reference > The public surface of menlo-sdk: Robot, connection configs, preflight, Sent, State, media, the store, transports and errors. - Page: https://docs.menlo.ai/sdk/reference - Section: Python SDK Everything here is importable from `menlo.asimov` unless a module is named. `menlo.__version__` is the distribution version. Units are metres per second, radians per second, radians, degrees Celsius. ## Where to Start | Do this | Use | | - | - | | say where the robot is | [`Connection`](https://docs.menlo.ai/sdk/reference.md#connection), [`Robot`](https://docs.menlo.ai/sdk/reference.md#robot) | | read the facts | [`preflight`, `armed`](https://docs.menlo.ai/sdk/reference.md#preflight) | | balance in place, walk, strafe, turn | [`balance`](https://docs.menlo.ai/sdk/reference.md#balance), [`set_velocity`](https://docs.menlo.ai/sdk/reference.md#set_velocity) | | stand up, or go compliant | [`stand`](https://docs.menlo.ai/sdk/reference.md#stand), [`damp`](https://docs.menlo.ai/sdk/reference.md#damp) | | pose a joint | [`set_joints`](https://docs.menlo.ai/sdk/reference.md#set_joints), [`trajectory`](https://docs.menlo.ai/sdk/reference.md#trajectory) | | wait for something | [`wait_until`](https://docs.menlo.ai/sdk/reference.md#wait_until); `stand`, `balance` and `damp` wait for their robot mode themselves | | read what it reports | [`State`](https://docs.menlo.ai/sdk/reference.md#state), [`get_state`](https://docs.menlo.ai/sdk/reference.md#properties-and-callbacks) | | check what it can do | [`has`, `require`](https://docs.menlo.ai/sdk/reference.md#properties-and-callbacks), [`RobotInfo`](https://docs.menlo.ai/sdk/reference.md#state) | | see what went out | [`Sent`](https://docs.menlo.ai/sdk/reference.md#sent), [`Outcomes`](https://docs.menlo.ai/sdk/reference.md#outcomes) | | pictures and sound | [`Media`](https://docs.menlo.ai/sdk/reference.md#media) | | record a run | [`record`](https://docs.menlo.ai/sdk/reference.md#recording) | | save a robot for next time | [`Store and CLI`](https://docs.menlo.ai/sdk/reference.md#store-and-cli) | | handle failure | [`Errors`](https://docs.menlo.ai/sdk/reference.md#errors) | ## Connection ```python ConnectionConfig(udp=None, livekit=None, limits=None, mode=None, name=None, hints={}) ``` | Member | | | - | - | | `udp: UdpConfig \| None` | the robot's address on the local network | | `livekit: ManagerConfig \| LiveKitConfig \| None` | the room, through Asimov Manager or directly | | `limits: Limits \| None` | velocity limits for this robot | | `mode: ConnectMode \| None` | the connection mode `connect()` uses when given none | | `name` | the saved robot this config came from, if any | | `available_modes() -> tuple[ConnectMode, ...]` | which of `"udp"`, `"hybrid"`, `"livekit"` this config can reach | | `default_mode() -> ConnectMode` | `mode` when set, else `only_mode()` | | `only_mode() -> ConnectMode` | the mode the set slots imply: `udp` alone is udp, `livekit` alone is livekit, both are `hybrid`; `ConnectError` with none set | | `ConnectionConfig.from_environment(environ=None, *, robot=None)` | from `MENLO_*`, else the saved robot | | `transport_for(mode, ...)` | builds the transport for a mode | | Config | | | - | - | | `UdpConfig(host, command_port=8850, state_bind=("0.0.0.0", 8851), state_source=None)` | commands to `host:8850`, state on `state_bind`. `state_source` pins the one address state may come from; without it, samples that do not match this robot are dropped | | `ManagerConfig(url, credential, label=None, timeout=5.0)` | Asimov Manager mints the room and a join token per connect. `.host`; `.resolve()`; `.check() -> ManagerGrant(url, room, identity, role)` validates the credential without joining | | `LiveKitConfig(url, room, token)` | room details you hold; `token` is a string or a callable minting one per join. One token is one participant | | `default_label()` | the label the SDK uses for this host | The LiveKit identity is `sdk---<6 random hex>`; `robot.info.endpoint` reads `room@url as ` on `livekit` and `host:8850 + room@url as ` on `hybrid`. Two sessions with the same label evict each other. ## `Robot` ```python Robot(source: ConnectionConfig | Transport | None = None, *, limits=None, link_timeout=2.0) ``` `None` resolves the robot from the environment, else the saved robot. `limits` here wins over `MENLO_LIMITS`, which wins over the saved robot's limits, which win over `Limits()`. ### `connect` ```python connect(mode=None, *, timeout=5.0, media_timeout=3.0, connect_timeout=10.0, allow_version_skew=False, require_state=True, persist=None) -> Robot ``` Attach on `"udp"`, `"hybrid"` or `"livekit"`; `mode` may be left out when the config names one or can reach only one. Returns once the first `State` has arrived and its protocol version matches. Raises `ConnectError` before touching the network when the config lacks what the mode needs, naming the `menlo robots add` command that fixes it. `media_timeout` bounds the wait for camera, microphone and speaker tracks. `require_state=False` returns as soon as the connection is open. `persist=True`, or `MENLO_PERSIST=1`, saves the robot after a successful connect with a `ManagerConfig`. `close()` then `connect()` again to switch modes. `open(*, timeout=5.0, allow_version_skew=False, require_state=True)` does the same over a `Transport` passed to the constructor. `RuntimeError` on an open robot. ### Preflight ```python Action = Literal["stand", "move", "trajectory"] preflight(action: Action = "move") -> Preflight armed: bool | None ``` `preflight` is a report of the facts. It reads the latest state, sends nothing, never waits and never raises for a robot condition. `action` is `"stand"`, `"move"` (`balance()` and `set_velocity()`) or `"trajectory"` (`set_joints()` and `trajectory()`). Only the blocking codes, which all mean no live state, stop a command; see [Verbs](https://docs.menlo.ai/sdk/reference.md#verbs). `armed` is `True` in MOVE and in STAND once the robot has been upright (gravity z below -0.87) for 0.5 s since STAND began; `False` in DAMP or before; `None` with no state, closed, in UNKNOWN, or in STAND with no gravity. | `Preflight` member | | | - | - | | `action` | the action checked | | `problems: tuple[Problem, ...]` | blocking first, then information | | `state: State \| None` | the sample the check read | | `armed: bool \| None` | | | `ok: bool` | no blocking problem: there is live state | | `blocking: tuple[Problem, ...]` | `not_connected`, `no_state` or `stale_state` | | `has(code) -> bool` | | | `str()` | `ready to move` or `not ready to move:`, followed by one ` - code: message` line per problem, information suffixed ` (information)` | | `explain()` | one line: `not ready to move: message (code); fix. ...`, blocking problems only; the message of the `NotReadyError` a command raises | `Problem(code, message, blocking)`; `str()` is `code: message`. Blocking: `not_connected`, `no_state`, `stale_state`. Information, which nothing in the SDK acts on: `faulted` (the alerts that latched DAMP, named), `alerts` (active firmware alerts, named) and `not_armed` (`move` from STAND before the arming hold). The codes and their meaning are in [What the SDK Reports](https://docs.menlo.ai/sdk/safety.md#what-the-sdk-reports). State older than 0.5 s is stale; armed means gravity z below -0.87 for 0.5 s. The SDK holds no joint temperature or battery threshold: write your own rule, as in [Write Your Own Guard](https://docs.menlo.ai/sdk/safety.md#write-your-own-guard). ### Verbs Each returns a `Sent`. The robot reports no per-command verdict: `Sent.outcome` stays `None` and `wait_outcome()` returns `Unknown` in every mode. Read the effect from `robot.get_state()`. Every verb is sent in any robot mode, and the firmware decides what it does. The robot mode, a latched fault, an alert, a joint temperature or the battery never stop one. The one refusal is no live state: `set_velocity`, `stand`, `balance` outside MOVE, `set_joints` and `trajectory` read one cached sample before they send, which adds no delay on a live stream. Without one (`no_state`, `stale_state`) they wait up to `timeout`, then raise `NotReadyError` with nothing sent. After a STAND sent moments ago whose report has not arrived, they wait up to 1 s for that report, then send anyway. A closed `Robot` raises `NotConnectedError`, a lost link `LinkLostError` and a protocol version mismatch `ProtocolMismatchError`, at once. `balance` in MOVE and `damp` are sent at once. A wait that sees a latched fault after the command was sent raises `RobotFaultedError` with `.sent` set. #### `set_velocity` ```python set_velocity(vx=0.0, vy=0.0, vyaw=0.0, *, duration=None, wait=None, hold=True, timeout=None) -> Sent ``` Walk. Sent in any robot mode: in MOVE the robot walks; in an armed STAND it enters MOVE; in DAMP the robot drops it. Without live state it waits up to `timeout` (5 s by default), then raises `NotReadyError` with nothing sent. Clamped to `limits`; re-sent at 10 Hz until `balance()`, another verb, `close()`, or `duration` seconds pass, when zero is sent. `wait` defaults to `True`: block until the hold has ended and its zero has gone out, or another verb took over; that needs a `duration`, else `ValueError`. `wait=False` returns once sent and keeps the velocity until the next command, or until `duration`. `hold=False` sends exactly one packet and holds nothing, for a loop that clocks its own commands; the live-state check is made once, as in `trajectory()`, and `duration` or `wait=True` with it is a `ValueError`. `ValueError` on a non-finite value or a non-positive duration. See [Move the Robot](https://docs.menlo.ai/sdk/move.md). #### `balance` ```python balance(*, timeout=5.0, wait=True) -> Sent ``` Zero velocity: the robot is in MOVE and the walking policy balances it in place. In MOVE it is sent at once; it ends any velocity hold and sends zero, so this is how a walk ends. Outside MOVE it sends zero velocity as soon as there is live state, without waiting for arming. From an armed STAND that puts the robot in MOVE; with `wait`, it returns once the robot reports MOVE, and raises `WaitTimeoutError` when the whole call passes `timeout`, saying so when the robot was not armed. From DAMP it raises `WaitTimeoutError` at once: "the robot is in DAMP: stand() first". `RobotFaultedError` when the wait sees a latched fault. Not an emergency stop. #### `stand` ```python stand(*, timeout=10.0, wait=True) -> Sent ``` Put the robot in STAND: the actuators hold the standing pose, without a balance loop. Sent from any robot mode. From MOVE, hang the robot from its gantry hook or seat it on a stool or bench first: a free-standing robot tips over. Sends STAND once and, with `wait`, returns when the robot reports STAND and is armed; `WaitTimeoutError` when the whole call passes `timeout`, `RobotFaultedError` when a fault latches meanwhile. `wait=False` returns once sent. Ends a running `set_joints()` and a held velocity. #### `damp` ```python damp(*, timeout=5.0, wait=True) -> Sent ``` Every actuator compliant now. A standing robot folds to the ground, so hang it from its gantry hook or seat it on a stool or bench first. Sent at once, whatever the robot's state. With `wait`, returns once the robot reports DAMP or FAULT_DAMP, `WaitTimeoutError` after `timeout`. Not an emergency stop: in an emergency use the E-Stop in Asimov Manager, or cut power at the battery unit. #### `set_joints` ```python set_joints(positions, *, duration=2.0, hz=50.0, kp=None, kd=None, wait=True, tolerance=0.05, timeout=None) -> Sent ``` Sent in any robot mode; the firmware follows a trajectory in MOVE or an armed STAND. Waits for live state first (a stale pose is waited out), then interpolates from the last reported pose to `positions` over `duration`, clocking `trajectory()` setpoints from a thread at `hz`, then holds the target until another verb. Any verb from any thread ends it before its next setpoint leaves. `wait=True` blocks until every joint is within `tolerance` rad, `WaitTimeoutError` otherwise. An ankle target more than 0.02 rad past the firmware's limits (0.35 rad pitch, 0.1 rad roll) is a `ValueError` before anything is sent. `timeout` bounds the whole call; left `None`, the live-state check may wait 5 s and the target `duration + 2` s. See [Control Joints](https://docs.menlo.ai/sdk/joints.md). #### `trajectory` ```python trajectory(positions, *, kp=None, kd=None, timeout=0.0) -> Sent ``` One setpoint, radians, firmware order; clock these yourself or use `set_joints`. Sent in any robot mode. Checks for live state once, with no delay on a live stream, so a loop at 50 Hz can call this. On a stale stream it raises `NotReadyError` at once and sends nothing; pass `timeout` to wait that long instead. `ValueError` unless `len(positions) == info.dof`, or when only one of `kp` and `kd` is given. A gain of 0 is not "no gain": the firmware substitutes its damping constants, so the joint does not hold a position. `None` applies the robot's per-joint gain table. The robot enters DAMP 2 s after the last setpoint. ### Waits Every wait reads the robot's own report, checks for a fault before its predicate, and refuses to succeed on a stale stream. `stand()`, `balance()`, `damp()` and `set_joints(wait=True)` wait this way for their own effect. #### `wait_until` ```python wait_until(predicate, *, timeout=10.0, stale_after=None, poll=0.05) -> State ``` Blocks until `predicate(state)` is true and returns that first `State`. Raises `WaitTimeoutError` (the message names the robot mode and the age of the last sample), `StateStaleError` when the stream goes quiet for `stale_after`, and `RobotFaultedError` when a fault latches. `stale_after` defaults to `link_timeout`. A wait for one robot mode is `wait_until(lambda s: s.mode is Mode.MOVE)`. ### Properties and Callbacks | Name | Type | Notes | | - | - | - | | `config` | `ConnectionConfig` | what this Robot was bound to | | `info` | `RobotInfo` | transport, endpoint, dof, joint names, protocol version, limits, capabilities | | `has(cap)`, `require(*caps)` | `bool`, raises `UnsupportedError` | this connection's set: `drive`, `state`, `battery`, `camera`, `microphone`, `speaker` | | `camera`, `microphone`, `speaker` | `Camera`, `Microphone`, `Speaker` | see Media; `UnsupportedError` when the connection does not carry them | | `record(path)` | `Recording` | context manager: every state sample and every command as JSON lines | | `get_state()` | `State` | the latest sample; `NotConnectedError` before the first | | `armed` | `bool \| None` | see Preflight | | `connected` | `bool` | open and not `LinkLostError` | | `outcomes()` | `Iterator[Refused]` | received refusals, oldest first; empty with this robot | | `on_state` | `Callable[[State], None] \| None` | every accepted sample, on the transport thread | | `on_alert` | `Callable[[Alert, str], None] \| None` | an alert `"raised"` or `"cleared"` | | `on_mode_change` | `Callable[[Mode, Mode], None] \| None` | before, after | | `on_refused` | `Callable[[Refused], None] \| None` | never fires with this robot | | `on_link_lost` | `Callable[[LinkLostError], None] \| None` | | | `close()` | | zero velocity if held, drop the link; idempotent; never raises | `Robot` is a context manager; `__exit__` calls `close()`. ## `Sent` | Member | Type | Meaning | | - | - | - | | `name` | `str` | the verb: `set_velocity`, `balance`, `stand`, `damp`, `trajectory`; `set_joints()` sends its setpoints as `trajectory` | | `sequence` | `int` | the command's sequence number | | `command` | `Velocity \| ModeCommand \| Trajectory` | what went out, after clamping | | `clamped` | `bool` | `command` differs from what you asked | | `sent_at` | `float` | `time.monotonic()` | | `outcome` | `Applied \| Refused \| None` | non-blocking; `None` while pending | | `wait_outcome(timeout=None)` | `Applied \| Refused \| Unknown` | `None` uses the transport default | | `require(timeout=None, *, unknown_ok=True)` | as above | raises `CommandRefusedError`; with `unknown_ok=False` also `OutcomeUnknownError` | ## Outcomes | Type | Fields | | - | - | | `Applied` | `sequence` | | `Refused` | `sequence`, `reason: Refusal`, `detail: str` (diagnostic text; never branch on it), `verb` | | `Unknown` | `sequence`, `waited_s`, `verb` | `Refusal` (IntEnum): `UNSPECIFIED`, `FW_DAMPED`, `FAULT_DAMPED`, `GATE`, `UNSUPPORTED_SOURCE`, `BAD_LENGTH`, `EMPTY_TRAJECTORY`, `NON_FINITE`, `PARSE`, `UNKNOWN_COMMAND`, `UNKNOWN_MODE`, `SHUTTING_DOWN`, `NO_CAMERA`, `NOT_ACTIVE`, `UNRECOGNIZED`; `retryable` property; `Refusal.from_wire()`. ## State ```python @dataclass(frozen=True) class State: mode: Mode # DAMP | STAND | MOVE | FAULT_DAMP | UNKNOWN joints: tuple[Joint, ...] # firmware order gravity: tuple[float, float, float] | None # body frame; z near -1 when upright gyro: tuple[float, float, float] | None # rad/s quat: tuple[float, float, float, float] | None # w, x, y, z error_flags: int alerts: tuple[Alert, ...] sequence: int fw_timestamp_us: int protocol_version: int battery: Battery | None # None when the robot reports no battery received_at: float edge_timestamp_us: int # Asimov Edge's wall clock (µs); livekit only, 0 on udp and hybrid # properties age_s: float upright: bool | None # gravity z < -0.8; None without gravity euler: tuple[float, float, float] | None # roll, pitch, yaw (rad) from quat yaw: float | None # rad, counter-clockwise, (-pi, pi] faulted: bool # FAULT_DAMP, error_flags or any critical alert joint_pos: tuple[float, ...] def joint(self, name: str) -> Joint # KeyError on an unknown name ``` `Joint(name, pos, vel, current, temp)`: `vel`, `current` and `temp` are `None` when the robot did not report them. `Alert(id, severity, value, threshold, source_id, first_set_us=0)` with `critical` (`severity == 0`) and `name`. `Battery(voltage_v, current_a, soc_percent, max_cell_temp_c, protection: BatteryProtection)` with `charging` and `protecting`; `BatteryProtection` is an `IntFlag`. `RobotInfo(transport, endpoint, dof, joint_names, protocol_version, limits, capabilities)` with `joint_index(name)`, `has(capability)` and a readable `str()`. `Limits(vx=0.4, vy=0.4, vyaw=0.8)`: the defaults are the firmware caps (0.4 m/s, 0.4 m/s, 0.8 rad/s). `Limits.parse("0.3,0.3,0.6")`. Negative or non-finite values raise `ValueError`. ## Media ```python robot.camera.photo(*, timeout=5.0) -> Frame # one fresh frame; WaitTimeoutError when quiet robot.camera.latest() -> Frame | None # newest frame; None before the first robot.camera.frames(*, timeout=5.0) # iterator, always the newest frame robot.camera.subscribe(cb) # cb(Frame) on the transport thread robot.camera.stream(*, timeout=5.0) # every frame, in order robot.camera.capture_clip(seconds, audio=True) -> Clip robot.microphone.chunks(*, timeout=5.0) # every AudioChunk in order; .dropped counts loss robot.speaker.play(chunk) robot.speaker.play_pcm(pcm_s16le, sample_rate_hz=16000, channels=1) ``` `Frame(width, height, encoding, data, stride_bytes, key_frame, frame_id, timestamp_ns, sequence)` with `shape`, `age_s`, `to_numpy()`, `to_jpeg(quality=85)`. `AudioChunk(sample_rate_hz, channels, samples_per_channel, encoding, data, stream_id, timestamp_ns, sequence)` with `duration_s`, `to_numpy()`. `Clip(frames, audio, started_at)` with `duration_s`, `fps`, `save_wav(path) -> Path`, `save_frames(dir)`, `save_mp4(path, *, fps=None) -> Path`, `frames_as_numpy()`. numpy, Pillow and OpenCV are needed only at the call that uses them, and named in the `ImportError`. ## Recording ```python with robot.record("run.jsonl") as rec: ... rec.samples, rec.commands_written from menlo.asimov import recording for line in recording.load("run.jsonl"): # dicts with kind "state" | "sent", t, mode ... ``` ## Store and CLI `~/.menlo/robots.toml` (`MENLO_HOME` moves it), `0600` in a `0700` directory. | | | | - | - | | `RobotStore()` | `get(name=None)`, `put(robot, *, default=None, allow_manager_change=False)`, `remove(name)`, `use(name)`, `names`, `save()`; `len()`, iteration and `in` | | `StoredRobot(name, manager_url=None, credential=None, room=None, mode=None, udp_host=None, limits=None)` | `resolved_mode()`, `missing(mode)`, `fix_command(mode)`, `manager(label=)`, `connection(label=)` | | `menlo.asimov.store.persist(config, room, *, name=None, mode=None)` | what `connect(persist=True)` calls: records the manager, credential, room, `udp_host`, `mode` and `limits`; `ValueError` without a `ManagerConfig` | | Command | | | - | - | | `menlo setup [--no-check]` | wizard: name, mode, that mode's fields, live checks | | `menlo robots [--json]` | the saved robots | | `menlo robots add NAME --mode --udp --manager --credential --limits VX,VY,VYAW [--default] [--no-check] [--no-input]` | add or update; unspecified values are kept | | `menlo robots remove NAME`, `menlo robots use NAME` | forget, make default | | `menlo status [--watch] [--json]` | readiness, robot mode, battery, hottest joint, faults, alerts, state rate | | `menlo stand [-y]`, `menlo balance [-y]`, `menlo walk --vx --vy --vyaw --duration S [-y]`, `menlo damp [-y]` | the verbs; each prints a plan with the robot's facts and asks `Proceed? [y/N]`, `-y`/`--yes` goes ahead without asking. `Not feasible:` only without live state; `balance` in MOVE sends at once without asking | | `menlo --robot NAME --mode MODE`, `menlo --version` | | Environment: `MENLO_ROBOT`, `MENLO_MODE`, `MENLO_UDP_HOST`, `MENLO_MANAGER_URL`, `MENLO_CREDENTIAL`, `MENLO_LIMITS`, `MENLO_HOME`, `MENLO_PERSIST`. `MENLO_MANAGER_URL` and `MENLO_CREDENTIAL` go together; one alone is a `ConnectError`. Environment wins over the saved robot and is not merged with it. See [Command Line](https://docs.menlo.ai/sdk/cli.md). ## Transports `UdpTransport(host, *, command_port, state_bind, state_source)`, `LiveKitTransport(url, room, *, token, media_timeout, connect_timeout)`, `HybridTransport(host, *, livekit_url, room, token, command_port, state_bind, ...)`. All implement `Transport`; a `ConnectionConfig` builds the right one for the mode. `LiveKitTransport.identity` and `.room` read back what the token claimed. ## Errors ``` MenloError ConnectError ProtocolMismatchError(expected, observed) NotConnectedError LinkLostError NotReadyError(message, *, action, preflight) # .problems, .has(code) RobotFaultedError(message, *, state, sent=None) # plus action, preflight WaitTimeoutError(message, *, last, sent=None) # also TimeoutError StateStaleError CommandRefusedError(refused) OutcomeUnknownError(unknown) # also TimeoutError UnsupportedError(capability, transport) ``` `NotReadyError` means there was no live state to send against (`no_state` or `stale_state`) within the command's `timeout`; nothing was sent. A closed `Robot` raises `NotConnectedError`, a lost link `LinkLostError`, a protocol version mismatch `ProtocolMismatchError`. It reads `not ready to : (); `, with ` (waited s)` appended when the command waited. `RobotFaultedError` is raised by a wait that saw a latched fault after the command went out; `sent` is set. `WaitTimeoutError.sent` is the command whose effect did not arrive. Caller mistakes are builtins: `ValueError` (non-finite velocity, limit or duration, wrong trajectory length, a lone kp or kd, an unknown connection mode), `KeyError` (unknown joint name), `RuntimeError` (`open()` on an open robot). A mode the config cannot reach raises `ConnectError`. ## Threading `Robot` is synchronous and thread-safe. Callbacks run on the transport thread, the one that delivers state: keep them short. `robot.damp()` from a callback, such as `on_alert` damping on an alert, sends DAMP and returns at once. The other commands that wait for the robot, and `wait_until()`, raise `RuntimeError` there with nothing sent; pass `wait=False`, or call them from your own thread. ## Per-Robot Tables `menlo.asimov.robots.ASIMOV_1_BIPED_JOINTS` is the 25-actuator order of the Asimov 1 biped firmware profile, chosen by the reported joint count. `menlo.asimov.robots.PROTOCOL_VERSION` is the protocol version the SDK was built against; `connect()` compares it with what the robot echoes and raises `ProtocolMismatchError` on a difference. ## The Protocol Commands on udp go to port 8850 and state arrives on 8851, each datagram one bare `asimov.io.RobotCommand` or `RobotState`. On livekit, commands are data messages on the `commands` topic and state is the `state` data track. A robot whose participant attribute `asimov.commands_track` is `"1"` also reads a `commands` data track from each client: the SDK sends a non-zero velocity and a trajectory there, and Asimov Edge orders it against the topic by sequence number, dropping a setpoint older than a command it already took. Every command carries `protocol_version = 1`, a sequence number and `timestamp_us`. UDP commands are not authenticated; the SDK credential and its role apply to the LiveKit room: every command on livekit, and the camera and audio on hybrid. [Without the SDK](https://docs.menlo.ai/sdk/without-the-sdk.md) and the `livekit_raw/` examples speak it with the `livekit` and `asimov-protocol` packages alone. --- # Troubleshooting > What each SDK error means and what to do about it. - Page: https://docs.menlo.ai/sdk/troubleshooting - Section: Python SDK Start with `menlo status`: it connects, reads state for a second, and prints what the robot reports without sending anything. The SDK refuses a command only when there is no live state; everything else the robot reports is for your script to judge. ## `ConnectError`: Nothing to Connect To `Robot()` found neither `MENLO_UDP_HOST` nor `MENLO_MANAGER_URL` with `MENLO_CREDENTIAL` in the environment, and no saved robot. Run `menlo setup`, or pass a `ConnectionConfig`. With several robots saved and no default, `menlo robots use NAME` picks one, or set `MENLO_ROBOT`. `MENLO_MANAGER_URL` without `MENLO_CREDENTIAL`, or the reverse, is the same error: they go together. ## `ConnectError`: The Saved Robot Lacks What the Mode Needs The message names the fix, such as `menlo robots add lab --udp `. `hybrid` needs the robot's address, the Asimov Manager URL and an SDK credential; `udp` the address; `livekit` the Manager URL and the credential. `cfg.available_modes()` says which modes a config can reach. ## `ConnectError`: Asimov Manager Refused the Credential The SDK credential is wrong or revoked, or the URL is not Asimov Manager. Issue a new one on the Developer page of Asimov Manager with the Control role ([Get an SDK Credential](https://docs.menlo.ai/asimov/1/operate/drive/python-sdk.md#get-an-sdk-credential)) and run `menlo setup` again. A credential with the Observe role connects but cannot drive on livekit. A manager that redirects is reported rather than followed: use the address it redirected to. ## `ConnectError`: No State From the Robot on UDP The robot never reported in. The robot sends UDP state to one address, so check, in order: 1. `udp-control` is on in the Asimov Edge parameters in Asimov Manager. 2. `udp-state-host` is this machine's address as the robot sees it, and `udp-state-port` is the port the SDK binds (8851 by default). 3. Nothing blocks port 8851 inbound: a firewall or a VPN. See [No State on udp or hybrid](https://docs.menlo.ai/sdk/troubleshooting.md#no-state-on-udp-or-hybrid). `menlo robots add NAME --udp HOST` runs this check and prints the same advice. ## No State on udp or hybrid On `udp` and `hybrid`, the robot listens for commands on UDP port 8850 and sends its state to one address: the `udp-state-host` and `udp-state-port` (8851 by default) in the Asimov Edge parameters. Commands go out from your computer, but state comes in to it, so a firewall on your computer that blocks inbound UDP 8851 from the robot leaves the SDK with no state: `connect()` raises `ConnectError`, a command raises `NotReadyError` with `no_state` or `stale_state`, and `menlo stand`, `balance` and `walk` print `Not feasible:`. `livekit` is not affected. First check that `udp-state-host` is this computer's address as the robot sees it; the robot sends state to that one host only. Then allow inbound UDP 8851 from the robot: - **Linux** with ufw: `sudo ufw allow from to any port 8851 proto udp`. With firewalld: `sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="" port port="8851" protocol="udp" accept'`, then `sudo firewall-cmd --reload`. - **macOS**: the firewall allows or blocks per application. Open **System Settings > Network > Firewall > Options** and allow incoming connections for the Python you run the SDK with, or answer **Allow** when macOS asks the first time a script connects. - **Windows**: answer **Allow** for private networks when Windows asks the first time a script connects, or in an administrator PowerShell run `New-NetFirewallRule -DisplayName "Asimov state" -Direction Inbound -Protocol UDP -LocalPort 8851 -Action Allow`. Run `menlo status` again: the state rate and a fresh sample show that state arrives. ## `ConnectError`: Could Not Bind the State Port Another process holds port 8851; one client per port on udp. Close it, or use `state_bind=("0.0.0.0", )` and set `udp-state-port` to match. ## `ProtocolMismatchError` The robot speaks another protocol version than the SDK was built against. Update whichever is behind. `connect(allow_version_skew=True)` proceeds anyway, and the robot may misread the commands the SDK sends. ## `NotReadyError` There was no live state to send against, and nothing was sent. `stand()`, `balance()` outside MOVE, `set_velocity()`, `set_joints()` and `trajectory()` read the latest state sample before they send. The codes are `no_state` (the robot has not reported) and `stale_state` (the latest sample is older than 0.5 s); both are waited out for up to the command's `timeout` first, and the message then ends in `(waited s)`. A closed `Robot` raises `NotConnectedError`, a lost link `LinkLostError` and a protocol version mismatch `ProtocolMismatchError` instead, at once. `e.problems` carries them, `e.has(code)` tests one and `e.preflight` is the whole report. Check the link with `menlo status`. On `udp` or `hybrid`, see [No State on udp or hybrid](https://docs.menlo.ai/sdk/troubleshooting.md#no-state-on-udp-or-hybrid). The robot mode, a fault, an alert, a hot actuator or a low battery never raise `NotReadyError`: the command is sent and the firmware decides. A rule against them is yours to write; see [Write Your Own Guard](https://docs.menlo.ai/sdk/safety.md#write-your-own-guard). ## `RobotFaultedError` A wait found `state.faulted` set after the command was sent: a critical alert, such as a fall, over-temperature or battery protection, has latched DAMP. The message and `state.alerts` name it; write it down before anything restarts the firmware, since restarting clears the record of what latched. Nothing a script sends clears it. Then follow [Recovering After an E-Stop or a Fall](https://docs.menlo.ai/asimov/1/operate/safety/stopping.md#recovering-after-an-e-stop-or-a-fall) to support and inspect the robot; its **Stop Robot** and **Start Robot** steps restart the firmware. See [If Something Goes Wrong](https://docs.menlo.ai/sdk/safety.md#if-something-goes-wrong). `RobotFaultedError` is a `NotReadyError`, so `except NotReadyError` catches it too; catch it first to tell a fault apart. `e.sent` is the command that went out. ## `WaitTimeoutError` A command was sent and the robot did not report the effect in time. `e.last` is the last state seen and `e.sent` what went out. - `stand()`: the robot did not report STAND and arming within `timeout` (10 s). See the next section. - `balance()` from STAND: the robot did not report MOVE within `timeout` (5 s) after the zero velocity went out. The message says when the robot was not armed: wait until `robot.armed` is `True`, then `balance()` again. Otherwise another controller may hold it: the Asimov Manager Drive Robot page or a paired gamepad outranks a script, and a command it outranks has no effect. - `balance()` from DAMP: raised at once, `the robot is in DAMP: stand() first`. - `damp()`: the robot did not report DAMP within `timeout` (5 s). Check that state is still arriving with `menlo status`, and that a `trajectory()` loop is not overwriting the verb. - `set_joints(wait=True)`: a joint did not reach its target within `tolerance`. It may be blocked, or the gains may be too soft to hold it. - `wait_until()`: the predicate stayed false; the message names the robot mode and the age of the last sample. ## `stand()` Times Out and the Robot Stays DAMP - **A fault is latched**: `stand()` raises `RobotFaultedError` instead; see above. - **The robot dropped the command**: another source holds control. The Drive Robot page outranks a paired gamepad, which outranks udp, which outranks livekit, and a paired gamepad holds control while idle. Unpair it and try again. - **The robot reports STAND but is not armed**: it is not upright. The firmware arms after 0.5 s of STAND under 30 degrees of tilt; `robot.armed` reads the test. ## The Robot Tipped Over After `stand()` in MOVE `stand()` is sent from any robot mode. STAND has no balance loop, so a free-standing robot asked to stand from MOVE tips over. Before `stand()` in MOVE, hang the robot from its gantry hook or seat it on a stool or bench; `rest.py` asks first. To stand still after a walk, call `balance()`: zero velocity keeps the robot in MOVE, balancing in place. See [Bringing the Robot to Rest](https://docs.menlo.ai/sdk/safety.md#bringing-the-robot-to-rest). ## `set_velocity` Returned but the Robot Did Not Walk In order of likelihood: 1. The hold was cut short: with `wait=False`, `set_velocity` returns at once, and the next verb or the end of the `with` block ends the hold. Keep the connection open for the duration, or leave `wait` at its default so the call returns after the hold. 2. The robot is not in MOVE. `set_velocity()` is sent in any robot mode: in DAMP the robot drops it, and in a STAND that is not armed it leaves the robot in STAND. MOVE is entered only from STAND held upright for 0.5 s, and an early velocity is neither refused nor reported. Check `state.mode` and `robot.armed`, and call `stand()` then `balance()` first. 3. Another source holds control; see above. The state stream does not say who does. ## A `stand()` or `damp()` Did Nothing A loop is streaming `trajectory()` setpoints and the next setpoint overwrote the verb. A `stand()` sent into the loop is overwritten this way. A `damp()` usually holds, because the robot drops trajectories once it reports DAMP, but a setpoint that arrives first still wins. Stop the loop, then send the verb. A `set_joints()` does not have this problem: any verb ends it. ## `StateStaleError` The robot went quiet for longer than `stale_after` (default: the link timeout, 2 s) during `wait_until()` or a command's wait. Treat it as absent, not slow: the connection dropped, the robot's software stopped, or it is reporting to a different machine. `LinkLostError` follows. A stream that is merely late before a command is sent is `stale_state`, waited out and then a `NotReadyError`. ## `LinkLostError` No state for 2 s. The SDK sent zero velocity if it held one, and every verb now raises this until you `close()` and `connect()` again. On udp and hybrid, the robot also zeroes the velocity 2 s after the last command it received. ## `NotConnectedError` `robot.get_state()` or `damp()` before the robot reported (after `connect(require_state=False)`), or any verb after `close()`. `close()` during a `set_velocity(..., wait=True)` raises this in the waiting thread. ## `UnsupportedError` This connection does not carry that capability. `camera`, `microphone` and `speaker` need `hybrid` or `livekit`; on those, a capability is claimed only from a track that arrived within `media_timeout` of connecting. Gate with `robot.has("camera")`. ## `ImportError` Naming Pillow, numpy or OpenCV `Frame.to_jpeg`, `to_numpy`, `Clip.save_frames` and `Clip.save_mp4` need those packages at call time. The SDK does not depend on them; install the one named. ## Every `Sent.wait_outcome()` Returns `Unknown` The robot reports no per-command verdict, so `Unknown` is what every command gets and `on_refused` never fires. `Unknown` is neither success nor refusal: read the effect with `wait_until` and `robot.get_state()`, or let `stand()`, `balance()` and `damp()` wait for it. ## Velocity Is Slower Than Asked Check `sent.clamped` and `sent.command`. The SDK clamps to `Limits`, whose defaults are the firmware caps of 0.4 m/s and 0.8 rad/s; a robot does not walk faster than that. A tighter limit came from `Robot(limits=)`, `MENLO_LIMITS`, or the saved robot's `limits`. ## Two Sessions Keep Disconnecting Each Other Both joined the room with the same identity. With `ManagerConfig`, each session gets its own unless you set the same `label`; with `LiveKitConfig`, one token is one participant, so mint two. ## Related - [Safety](https://docs.menlo.ai/sdk/safety.md): what each layer stops, what the SDK reports, and your own guard - [Troubleshooting the Robot](https://docs.menlo.ai/asimov/1/operate/troubleshooting.md): problems that are not the SDK's