# Examples Small, runnable examples of building on Roborun from your own files. [docs/BUILDING.md](https://roborun.app/docs/building/llm.txt) explains each extension point; `roborun new my-robot` writes a starter project with a driver, rules and a task client. | File | What it shows | Run it | | --- | --- | --- | | `minimal_arm.py` | The smallest arm driver: an `ArmAdapter` with `read()` and `command()` | `python minimal_arm.py` (starts it on a station on a free port) | | `folder_camera.py` | Your own camera: a class whose `read()` returns RGB images | `python folder_camera.py FOLDER_OF_IMAGES` | | `keep_out_box.py` | A rules file: the gripper stays out of a box on the table | `python keep_out_box.py` | | `robot_client.py` | A command line on `roborun_sdk.client.Robot`: tasks, live stream, Stop, a camera frame | `roborun python robot_client.py status` (needs `roborun up`) | | `rover.py` (+ `my_rover.yaml`, `my_rover.xml`) | Your own robot body: a diff-drive rover with a fixed camera, its profile and its simulation model | `roborun python rover.py` (offline), `--mujoco` (simulated), `install` (then `roborun up --profile my_rover --sim room`) | | `llm_tools.py` | The robot as an LLM's tools: specs (JSON Schema) and `call_tool()` for look, run a task, arm state, Stop | `roborun python llm_tools.py tools` | | `dreamlabs_policy.py` | A DreamLabs policy (Dream-1) on two YAM arms through Roborun, from Python: check, shadow, run | `roborun python dreamlabs_policy.py check` (needs `pip install 'roborun-sdk[dreamlabs]'` and your DreamLabs credentials) | | `my_policy.py` | Your own policy: a provider that sways the wrist, run as a Roborun task through every limit and Stop | `roborun policy run --provider my_policy.py:Sway --arms left --prompt "sway"` (needs `roborun up`) | Run them with `roborun python FILE`: Roborun's own Python, where `roborun_sdk` is installed. `roborun docs --examples DIR` copies them out of an installed Roborun. ## The files ### dreamlabs_policy.py Also at https://roborun.app/docs/examples/dreamlabs_policy.py ```python """Run a DreamLabs policy (Dream-1) on your arms through Roborun, from Python. pip install 'roborun-sdk[dreamlabs]' # DreamLabs' client (dreamlabs-client) and the face blur # set up your DreamLabs credentials as DreamLabs documents them (DREAM_API_KEY, or ~/.dreamlabs/credentials) roborun up # two YAM arms, cameras top, left and right roborun python dreamlabs_policy.py check # offline: does the model fit this robot? nothing is sent roborun python dreamlabs_policy.py shadow # asks the model, moves nothing, reports what it would do roborun python dreamlabs_policy.py run "fold the towel" DreamLabs' model chooses the motion; Roborun plays it through its own limits (the per-tick cap, the seam and age checks, the joint and tool speed limits, your rules file), holds the arms when an answer is late, and Stop (the page, the viewer, `roborun stop`) ends the run at once. The run is a Roborun task: its record, its recording and a dataset episode are not sent to DreamLabs; like any other task's, they go to your Roborun history (roborun up --no-data-sync keeps them on this computer). The request timing is kept in log/policy// and never leaves this computer. What is sent to DreamLabs while a run is active: the prompt, both arms' joint angles, grippers and tool poses (computed from the joint angles), and recent camera frames (face-blurred), with your DreamLabs key. Nothing is sent by `check`. """ import sys from roborun_sdk import policy MODEL = 'dreamlabs/dream-1-beta' def main(argv): what = argv[0] if argv else 'check' if what == 'check': print(policy.check('dreamlabs', model=MODEL)) return 0 # consent=True: you agree, for this run only, to send what the docstring above lists to DreamLabs. Without it (and # without an answer stored by `roborun policy run` in a terminal) the run is refused and nothing is sent. if what == 'shadow': report = policy.run('dreamlabs', model=MODEL, prompt=' '.join(argv[1:]) or 'fold the towel', shadow=True, seconds=20, consent=True) print(report) return 0 result = policy.run('dreamlabs', model=MODEL, prompt=' '.join(argv[1:]) or 'fold the towel', arms='both', seconds=60, consent=True) print(result.task_id, result.status, result.stop_reason, result.message) return 0 if result.status in ('done', 'stopped') else 1 if __name__ == '__main__': sys.exit(main(sys.argv[1:])) ``` ### folder_camera.py Also at https://roborun.app/docs/examples/folder_camera.py ```python """Your own camera: any class with read() returning an RGB image. This one plays the JPEG/PNG images of a folder in a loop, which is handy for replaying a recording; swap read() for your camera's SDK. cameras: top: source: /path/to/folder_camera.py:FolderCamera folder: /path/to/images # every other key in the camera's section is passed to __init__ fps: 10 Roborun constructs it with whichever of role, width, height, fps its __init__ names, plus the extra keys. Optional methods: open() -> {serial, intrinsics, depth_scale_m}, close(), set_exposure_us(us). To give depth, return {rgb, depth_z16} from read() and depth_scale_m from open(); the overhead camera needs depth. python folder_camera.py /path/to/images # opens it the way Roborun does and reads three frames """ import time from pathlib import Path import cv2 class FolderCamera: def __init__(self, folder, role='top', fps=10): self.files = sorted(p for p in Path(folder).expanduser().iterdir() if p.suffix.lower() in ('.jpg', '.jpeg', '.png')) if not self.files: raise ValueError(f'no images in {folder}') self.role, self.period, self.index, self.next_at = role, 1.0 / float(fps), 0, 0.0 def open(self): return dict(serial=f'folder:{self.files[0].parent.name}') def read(self): now = time.monotonic() if now < self.next_at: return None # no new frame yet self.next_at = now + self.period image = cv2.imread(str(self.files[self.index % len(self.files)])) self.index += 1 return cv2.cvtColor(image, cv2.COLOR_BGR2RGB) if __name__ == '__main__': import sys from roborun_sdk.cameras import CustomSource source = CustomSource(f'{Path(__file__).resolve()}:FolderCamera', 'top', settings=dict(fps=10), extra=dict(folder=sys.argv[1])) model = source.open() print('opened:', {k: model[k] for k in ('serial', 'width', 'height') if k in model}) frames = 0 while frames < 3: item = source.read() if item is not None: frames += 1 print('frame', item['sensor_frame'], item['rgb'].shape, item['rgb'].dtype) time.sleep(0.02) source.close() ``` ### keep_out_box.py Also at https://roborun.app/docs/examples/keep_out_box.py ```python """Rules: a keep-out box. The gripper may not enter a box on the table (for example, where a person or a fixture is). rules: /path/to/keep_out_box.py # in robot.yaml; applies to every arm built on StreamedArm check() runs for every arm command. state['tool_position_m'] is where the gripper is now (metres, the arm's base frame), from the arm's model; it is None for an arm without one, and this rule then lets commands through. Refusing makes the arm brake and hold where it is; Roborun ends the task with "your rules file refused this motion" if it lasts. To leave the box, take the arm out by hand or with Home after editing the rule: a rule that refuses every command keeps the arm still. python keep_out_box.py # calls check() the way an arm does, with two measured gripper positions """ BOX_MIN_M = (0.30, -0.10, -0.05) # x, y, z: the box's near corner, arm base frame BOX_MAX_M = (0.50, 0.10, 0.30) def inside(point): return all(lo <= v <= hi for v, lo, hi in zip(point, BOX_MIN_M, BOX_MAX_M)) def check(side, positions_rad, gripper, state): tool = state.get('tool_position_m') if tool is not None and inside(tool): return False return None if __name__ == '__main__': q = [0.0, -0.5, 1.0, 0.0, 0.5, 0.0] print('gripper at (0.40, 0.00, 0.10):', check('left', q, 1.0, dict(tool_position_m=[0.40, 0.00, 0.10]))) print('gripper at (0.20, 0.25, 0.10):', check('left', q, 1.0, dict(tool_position_m=[0.20, 0.25, 0.10]))) ``` ### llm_tools.py Also at https://roborun.app/docs/examples/llm_tools.py ```python """Robot tools for your LLM: the specs to give its tool-calling API, and one function that runs a call. from llm_tools import TOOLS, call_tool # 1. pass TOOLS to your LLM as its tools (name, description, input_schema: JSON Schema; # rename input_schema to `parameters` if your provider calls it that) # 2. for each tool call it makes: result = call_tool(name, arguments) # 3. send `result` back as the tool result. A camera image comes back as # {"type": "image", "media_type": "image/jpeg", "data": }: pass it on as an image block roborun python llm_tools.py tools # the specs, as JSON roborun python llm_tools.py call look '{"camera": "top"}' # run one call by hand Errors never raise out of call_tool: they come back as {"error": {"code", "message", "retryable"}} so the model can read them and decide (wait and retry when retryable, change the request when not). Stop is always available and is never refused; tell your model to call it on any doubt. Camera frames are face-blurred by the robot before they reach this code, so they may be sent to a hosted LLM. `look` only sends the top, left and right cameras and refuses any other (a humanoid's head frame, for one, is not face-blurred yet). """ import base64 import json import sys from roborun_sdk.client import Robot, RobotError LOOK_CAMERAS = ('top', 'left', 'right') # the only cameras `look` sends to the model: their frames are face-blurred TOOLS = [ {'name': 'robot_status', 'description': 'What the robot is: its profile, whether it is ready, which arms and cameras are connected, and the task ' 'running now, if any. Call it first.', 'input_schema': {'type': 'object', 'properties': {}, 'additionalProperties': False}}, {'name': 'look', 'description': 'See the table now: the newest image from a camera (top looks down on the whole table; left and right are ' 'on the wrists). Faces are blurred.', 'input_schema': {'type': 'object', 'properties': {'camera': {'type': 'string', 'enum': list(LOOK_CAMERAS), 'default': 'top'}}, 'additionalProperties': False}}, {'name': 'arm_state', 'description': 'Where each arm is: joint angles (rad), gripper opening (0 closed .. 1 open), tool position (mm, robot frame). ' 'The gripper opening does not tell whether an object is held (a jaw around a wide cup reads nearly open): ' 'use the outcome that run_task returns.', 'input_schema': {'type': 'object', 'properties': {}, 'additionalProperties': False}}, {'name': 'run_task', 'description': 'Have the robot do one physical task described in plain words, such as "pick up the cup" or "put the cup ' 'back where it was", and wait until it ends. Returns status (done, stopped, failed), the number of moves, ' 'a message and outcome: outcome.holding.left / .right is what that arm holds now ({object, lifted_mm, ' 'evidence, verified}), null when the robot measured it empty, or "unknown" when it did not check that arm; ' 'outcome.placed lists what the task let go of. When an arm you need is "unknown", use look before relying ' 'on it. mode "preview" plans and shows the motion without moving anything (outcome is null).', 'input_schema': {'type': 'object', 'required': ['prompt'], 'additionalProperties': False, 'properties': { 'prompt': {'type': 'string', 'minLength': 1, 'maxLength': 1500}, 'mode': {'type': 'string', 'enum': ['run', 'preview'], 'default': 'run'}, 'arm': {'type': 'string', 'enum': ['left', 'right', 'both'], 'description': 'leave out to let the robot choose'}, 'timeout_s': {'type': 'number', 'default': 300, 'description': 'stop the task if it runs longer than this'}}}}, {'name': 'stop', 'description': 'Stop all motion now. Always available, never refused. Use it whenever something looks wrong.', 'input_schema': {'type': 'object', 'properties': {}, 'additionalProperties': False}}, ] def _task_result(task): keep = ('id', 'status', 'moves', 'message', 'error', 'error_info', 'elapsed_s') out = {k: task.get(k) for k in keep if task.get(k) is not None} out['outcome'] = task.get('outcome') # kept when null: "nothing to report" is an answer the model can read return out def call_tool(name, arguments=None, robot=None): """Run one tool call: a JSON-serialisable result, an image block for `look`, or {"error": {...}}.""" robot = robot or Robot() args = dict(arguments or {}) try: if name == 'robot_status': return robot.status() if name == 'look': camera = args.get('camera', 'top') if camera not in LOOK_CAMERAS: # the schema's enum is advice to the model, not a check: enforce it here return {'error': {'code': 'invalid', 'retryable': False, 'message': f'camera must be one of {", ".join(LOOK_CAMERAS)}, not {camera!r}'}} jpeg = robot.frame(camera) return {'type': 'image', 'media_type': 'image/jpeg', 'data': base64.b64encode(jpeg).decode()} if name == 'arm_state': state = robot.state() return {'arms': {side: {k: arm.get(k) for k in ('ok', 'joints_rad', 'gripper', 'tool_mm')} for side, arm in (state.get('arms') or {}).items()}} if name == 'run_task': task = robot.run(args['prompt'], mode=args.get('mode', 'run'), arm=args.get('arm'), timeout=float(args.get('timeout_s', 300))) return _task_result(task) if name == 'stop': return robot.stop() return {'error': {'code': 'unknown_tool', 'message': f'no tool named {name!r}', 'retryable': False}} except TimeoutError as exc: return {'error': {'code': 'timeout', 'message': f'{exc}; the task was stopped', 'retryable': True}} except KeyError as exc: return {'error': {'code': 'invalid', 'message': f'missing argument {exc}', 'retryable': False}} except RobotError as exc: return {'error': {'code': exc.code, 'message': exc.message, 'retryable': exc.retryable}} def main(argv): if argv[:1] == ['tools']: print(json.dumps(TOOLS, indent=1)) return 0 if argv[:1] == ['call'] and len(argv) >= 2: result = call_tool(argv[1], json.loads(argv[2]) if len(argv) > 2 else {}) if isinstance(result, dict) and result.get('type') == 'image': result = dict(result, data=f"<{len(result['data'])} base64 characters>") print(json.dumps(result, indent=1)) return 1 if isinstance(result, dict) and 'error' in result else 0 print(__doc__) return 2 if __name__ == '__main__': sys.exit(main(sys.argv[1:])) ``` ### minimal_arm.py Also at https://roborun.app/docs/examples/minimal_arm.py ```python """The smallest arm driver Roborun accepts: a class with read() and command(). roborun up --left /path/to/minimal_arm.py:MinimalArm # or in robot.yaml: arm: /path/to/minimal_arm.py:MinimalArm roborun station --adapter minimal_arm:MinimalArm # just the station, from this folder Roborun calls command() at its 30 Hz tick with a target that is already smooth and step-limited, and read() every tick. A plain adapter like this one does not get the 100 Hz shaping, the guards or your rules file: build on StreamedArm for those (see `roborun new` and docs/BUILDING.md). This one moves software joints at a bounded speed, so it runs anywhere. python minimal_arm.py # runs it on a Roborun station for two seconds and prints the station's view of it """ import time from roborun_sdk.embodiment import ArmAdapter class MinimalArm(ArmAdapter): home = [0.0, -0.5, 1.0, 0.0, 0.5, 0.0] # rad, one per joint limits = [(-2.6, 2.6)] * 6 def __init__(self, bus=None): # bus: the arm's address from robot.yaml or --left ARM@ADDRESS self.bus = bus self.q, self.jaw = list(self.home), 1.0 self.target, self.at = (list(self.home), 1.0), time.monotonic() def command(self, positions_rad, gripper): # replace with: send these to your motors self.target = (list(positions_rad), float(gripper)) def read(self): # replace with: read your motors now = time.monotonic(); step = self.joint_speed_rad_s * min(0.1, now - self.at); self.at = now self.q = [a + max(-step, min(step, b - a)) for a, b in zip(self.q, self.target[0])] self.jaw += max(-step, min(step, self.target[1] - self.jaw)) return dict(positions_rad=list(self.q), gripper=self.jaw) if __name__ == '__main__': import json import urllib.request from roborun_sdk.embodiment import run_station arm = MinimalArm() arm.connect() station, server = run_station(arm, port=0) # port 0: any free port, so it never meets a running robot try: time.sleep(2) with urllib.request.urlopen(server.url + '/supervisor/pose', timeout=3) as response: pose = json.load(response) print(json.dumps(dict(station=server.url, left=pose.get('left') or pose), default=str)[:600]) finally: server.close() ``` ### my_policy.py Also at https://roborun.app/docs/examples/my_policy.py ```python """Your own policy on Roborun: a provider that sways the wrist by 0.1 rad around where the arm is. roborun up --sim cup # two simulated arms (or your own arms) roborun policy check --provider my_policy.py:Sway --arms left roborun policy run --provider my_policy.py:Sway --arms left --seconds 20 --prompt "sway the wrist" roborun policy run --provider my_policy.py:Sway --option amplitude=0.05 --arms left --prompt "sway less" roborun python my_policy.py # the same from Python A provider gets observations (measured joints, the target the station last played, camera frames) and returns chunks: per arm, rows of absolute targets [q_1..q_n, gripper] at `hz`, in radians, with the gripper as an open fraction (0 closed, 1 open). Roborun's station plays them through every limit (the per-tick cap, the seam check, the joint and tool speed limits, your rules file), holds the arm when a chunk is late, and Stop ends the run at once. Every run is a task: its record, its recording and a dataset episode are on this computer like any other task's. """ import math from roborun_sdk.policy import Chunk, Provider, plain_needs class Sway(Provider): name = 'sway' def __init__(self, amplitude=0.1, period=4.0, hz=30.0): if not 0 < float(amplitude) <= 0.3: raise ValueError('amplitude: 0 .. 0.3 rad') self.amplitude, self.period, self.hz = float(amplitude), float(period), float(hz) self.start_t = None def needs(self, spec): """Offline: which arms it drives and what it wants to see. Here: every arm of the run, no cameras.""" self.arms = {arm.side: arm for arm in spec.arms} return plain_needs(tuple(self.arms), frame_hz=2.0, version='sway example 1') def act(self, obs): """48 rows (1.6 s at 30 Hz) from the observation's time on: the last joint swings around where it started.""" if self.start_t is None: self.start_t = obs.t self.center = {side: list(state.commanded_rad) for side, state in obs.arms.items()} rows = {} for side, arm in self.arms.items(): out = [] for i in range(48): t = obs.t - self.start_t + i / self.hz q = list(self.center[side]) q[-1] += self.amplitude * math.sin(2 * math.pi * t / self.period) out.append(q + ([1.0] if arm.gripper else [])) # the gripper stays open rows[side] = out return Chunk(rows, hz=self.hz) if __name__ == '__main__': from roborun_sdk import policy result = policy.run(Sway(), prompt='sway the wrist', arms='left', seconds=20) print(result.task_id, result.status, result.message) ``` ### my_rover.xml Also at https://roborun.app/docs/examples/my_rover.xml ```xml ``` ### my_rover.yaml Also at https://roborun.app/docs/examples/my_rover.yaml ```yaml # A body profile: what Roborun tells the motion service about your robot, and the limits it plays every move within. # Put it (and my_rover.xml) in ~/.config/roborun/bodies/ (python rover.py install does that); the file name is the profile id. # Checked when it is read: `roborun profiles` lists it, or says which field is wrong. label: My rover maker: me description: A diff-drive rover with one fixed camera on a mast. kind: wheeled # wheeled (also: rover) or humanoid base: wheeled # wheeled or legged arms: 0 head_dof: 0 # 0: the camera is fixed (1: it pitches, 2: it pitches and turns) limits: vx_m_s: [-0.2, 0.5] # forward speed range, m/s (+x forward) vy_m_s: [0, 0] # sideways: none on a diff drive vyaw_rad_s: [-1.0, 1.0] # turning rate range, rad/s (+ counter-clockwise) camera: # the one camera every move is planned from size_px: [640, 480] hfov_deg: 90 eye_height_m: 0.35 # the camera's height above the floor pitch_rad: 0.2 # tilted down this much (+ looks down) lens: a 90 degree USB webcam footprint_m: 0.25 # the base's radius: the obstacle guard keeps this clear motion: # optional: how commands are shaped (these are the defaults, but a quicker turn) accel_m_s2: [0.5, 0.5] accel_yaw_rad_s2: 1.5 sim: # optional: roborun up --profile my_rover --sim room model: my_rover.xml # an MJCF file next to this one: a base body with a free joint, and a camera base_body: base_link head_camera: head ``` ### robot_client.py Also at https://roborun.app/docs/examples/robot_client.py ```python """Drive the robot on this computer from the command line, with roborun_sdk.client.Robot (the typed client for the local API). roborun python robot_client.py status roborun python robot_client.py run "pick up the cup" [--preview] [--stop-after 5] roborun python robot_client.py stop roborun python robot_client.py frame top top.jpg # the camera now, faces blurred In your own code: from roborun_sdk.client import Robot, RobotError robot = Robot() # http://127.0.0.1:8120, this computer only task = robot.run('pick up the cup') # start it and wait until it ends; mode='preview' moves nothing print(task['status'], task['message']) robot.stop() # all motion, like the app's Stop `roborun python` runs this file with Roborun's own Python, where roborun_sdk is installed. """ import json import sys import time from roborun_sdk.client import Robot, RobotError, RobotUnavailable def main(argv, robot=None): sys.stdout.reconfigure(line_buffering=True) robot = robot or Robot() try: if argv[:1] == ['status']: print(json.dumps(robot.status(), indent=1)) return 0 if argv[:1] == ['stop']: print(json.dumps(robot.stop())) print(json.dumps(robot.stop_status())) return 0 if argv[:1] == ['frame'] and len(argv) >= 3: data = robot.frame(argv[1]) with open(argv[2], 'wb') as out: out.write(data) print(f'{argv[1]}: {len(data)} bytes -> {argv[2]}') return 0 if argv[:1] == ['run'] and len(argv) >= 2: stop_after = float(argv[argv.index('--stop-after') + 1]) if '--stop-after' in argv else None task = robot.start(argv[1], mode='preview' if '--preview' in argv else 'run') print('started', task['id'], task['status']) started, last = time.monotonic(), None for view in robot.live(task['id']): if (view['status'], view.get('message')) != last: last = (view['status'], view.get('message')) print(f"{view.get('elapsed_s') or 0:6.1f}s {view['status']:8s} {view.get('message') or ''}") if stop_after is not None and time.monotonic() - started > stop_after and view['status'] == 'running': print('stopping:', robot.stop_task(task['id'])['status']) stop_after = None final = robot.task(task['id']) print(json.dumps({k: final.get(k) for k in ('id', 'status', 'moves', 'message', 'error')})) return 0 if final['status'] in ('done', 'stopped') else 1 except RobotUnavailable as exc: print(exc.message, file=sys.stderr) return 3 except RobotError as exc: print(f'{exc.status} {exc.code}: {exc.message}' + (' (try again)' if exc.retryable else ''), file=sys.stderr) return 2 print(__doc__) return 2 if __name__ == '__main__': sys.exit(main(sys.argv[1:])) ``` ### rover.py Also at https://roborun.app/docs/examples/rover.py ```python """Your own robot body: a diff-drive rover with one fixed camera, from your own files (my_rover.yaml, my_rover.xml, this file). python rover.py offline: drives the rover through Roborun's player (50 Hz, the profile's limits, Stop), then prints the request a move would send to the motion service (nothing is sent) python rover.py --mujoco the same in Roborun's MuJoCo simulation of my_rover.xml, in the room scene python rover.py install copies my_rover.yaml and my_rover.xml to ~/.config/roborun/bodies, then: roborun up --profile my_rover --sim room the rover simulated, its local API on 127.0.0.1:8120 roborun up --profile my_rover --body /path/to/rover.py:Rover this class, on your robot `Rover` below is simulated (it integrates its own odometry and draws a picture): replace the marked lines with your motor controller and camera. Run it with Roborun's Python: roborun python rover.py """ from __future__ import annotations import argparse import json import math import os import shutil import sys import threading import time from pathlib import Path from roborun_sdk.body import BaseAdapter, HeadAdapter HERE = Path(__file__).resolve().parent PROFILE = HERE / 'my_rover.yaml' class RoverBase(BaseAdapter): """A diff-drive base: forward speed and turning rate (no sideways), stopped when commands stop coming (the deadman).""" kind = 'wheeled' def __init__(self, limits, deadman_s=0.3): self.limits, self.deadman_s = limits, deadman_s self.lock = threading.Lock() self.x = self.y = self.yaw = 0. self.v = self.w = 0. self.commanded = dict(vx=0., vy=0., vyaw=0.) self.at = self.sent = time.monotonic() def _advance(self): now = time.monotonic() if now - self.sent > self.deadman_s: # no fresh command: the base stops by itself self.v = self.w = 0. dt, self.at = now - self.at, now self.yaw += self.w * dt self.x += self.v * math.cos(self.yaw) * dt self.y += self.v * math.sin(self.yaw) * dt def command(self, vx, vy, vyaw): clamp = lambda v, lo_hi: min(lo_hi[1], max(lo_hi[0], float(v))) with self.lock: self._advance() self.v, self.w = clamp(vx, self.limits['vx_m_s']), clamp(vyaw, self.limits['vyaw_rad_s']) self.commanded = dict(vx=self.v, vy=0., vyaw=self.w) self.sent = time.monotonic() # your robot: send (self.v, self.w) to the motor controller here def stop(self): with self.lock: self._advance() self.v = self.w = 0. self.commanded = dict(vx=0., vy=0., vyaw=0.) # your robot: brake (zero velocity; never a power-off) def state(self): with self.lock: self._advance() # your robot: odometry from the wheel encoders return dict(x=self.x, y=self.y, yaw=self.yaw, vx=self.v, vy=0., vyaw=self.w, commanded=dict(self.commanded), t=time.time()) class FixedCamera(HeadAdapter): """The one camera, fixed on a mast (dof 0). frame() needs only the JPEG: its size, intrinsics, height and tilt come from the profile's camera section.""" dof = 0 def __init__(self, base, camera): self.base, self.camera = base, camera def command(self, pitch, yaw): pass # a fixed camera does not move def state(self): return dict(pitch=float(self.camera.get('pitch_rad', 0.)), yaw=0.) def frame(self): # your robot: grab a frame from the camera and return its JPEG bytes import numpy as np from PIL import Image import io w, h = self.camera['size_px'] yaw = self.base.state()['yaw'] img = np.zeros((h, w, 3), np.uint8) horizon = int(h * 0.42) img[:horizon] = (205, 215, 225) # wall img[horizon:] = (150, 140, 125) # floor door = int((0.5 - yaw / math.radians(90)) * w) # a door straight ahead at the start, sliding across as the rover turns if -60 < door < w + 60: img[int(h * 0.15):horizon, max(0, door - 60):max(0, min(w, door + 60))] = (120, 80, 50) out = io.BytesIO() Image.fromarray(img).save(out, 'JPEG', quality=85) return dict(jpeg=out.getvalue()) class Rover: """What `roborun up --body rover.py:Rover` makes: an object with .base and .head. `profile` is the body's profile (a dict), given because the constructor names it; any other key of robot.yaml's `body:` section would be a keyword argument.""" profile = 'my_rover' # the profile it runs when roborun up names none def __init__(self, profile): self.base = RoverBase(profile['robot']['limits'], profile['motion']['deadman_s']) self.head = FixedCamera(self.base, profile['camera']) def close(self): self.base.stop() # ---------------------------------------------------------------------------------------------------- offline demo DRIVE = ([dict(t=i / 10, vx=0.4, vy=0., vyaw=0.) for i in range(15)] # forward 1.5 s + [dict(t=1.5 + i / 10, vx=0.2, vy=0., vyaw=0.8) for i in range(10)]) # then a left arc def demo(use_mujoco=False): from roborun_sdk.body import profiles from roborun_sdk.body.jobs import build_request from roborun_sdk.body.player import Watch, play pid = profiles.add_file(PROFILE) # roborun up reads ~/.config/roborun/bodies; this demo, the file here profile = profiles.load(pid) if use_mujoco: from roborun_sdk.body.sim import BodySim sim = BodySim(pid, scene='room') base, head, close = sim.base, sim.head, sim.close print(f'{profile["label"]}: MuJoCo simulation of {profile["sim"]["model"]}, room scene') else: rover = Rover(profile) base, head, close = rover.base, rover.head, rover.close print(f'{profile["label"]}: this file\'s simulated rover') try: frame = head.frame() request = build_request(pid, frame, 'drive to the door and stop in front of it', duration_s=3) print('a move would send the motion service (not sent: this demo is offline):') for key, value in request.items(): print(f' {key}: {json.dumps(value)}') before = base.state() watch = Watch(pid, base, head).start() # the obstacle guard (without depth: slow, and at most 0.4 m per move) try: stop = threading.Event() played = play(DRIVE, base, head, pid, stop=stop, watch=watch) finally: watch.close() for _ in range(40): # a braking base comes to rest within its stop deceleration after = base.state() if abs(after['vx']) < 0.01 and abs(after['vyaw']) < 0.02: break time.sleep(0.05) moved = math.hypot(after['x'] - before['x'], after['y'] - before['y']) print(f"played {played['played_s']:.2f} s{' (stopped: ' + played['guard_stop']['event'] + ')' if played.get('guard_stop') else ''}: " f"moved {moved:.2f} m, turned {math.degrees(after['yaw'] - before['yaw']):.0f} deg, " f"now at rest: {abs(after['vx']) < 0.01 and abs(after['vyaw']) < 0.02}") finally: close() return 0 def install(): home = Path(os.environ.get('ROBORUN_HOME') or Path.home() / '.config' / 'roborun') / 'bodies' home.mkdir(parents=True, exist_ok=True) for f in (PROFILE, HERE / 'my_rover.xml'): shutil.copy2(f, home / f.name) from roborun_sdk.body import profiles profiles.load('my_rover') # checked, as roborun up will print(f'installed my_rover in {home}') print('simulate it: roborun up --profile my_rover --sim room') print(f'your own robot: roborun up --profile my_rover --body {Path(__file__).resolve()}:Rover') return 0 if __name__ == '__main__': ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('action', nargs='?', choices=('demo', 'install'), default='demo') ap.add_argument('--mujoco', action='store_true', help='the demo in the MuJoCo simulation of my_rover.xml') a = ap.parse_args() sys.exit(install() if a.action == 'install' else demo(a.mujoco)) ```