Show your robot in Live View
Live View is the platform page, at {{platform_url}}/live, that shows your robot’s cameras as video and its status, and takes the next task from a prompt box: a viewer types a task, presses Start, watches the robot run it, and presses Stop. If our control loop runs your robot (dreamcli robot up, see Getting started), the robot shows up there on its own. If you run your own control loop, dream.LiveViewClient puts it there: you stream each observation to it, and it hands back the task a viewer sends and tells your loop when a viewer pressed Start or Stop.
The whole program below runs as it is and shows a black picture; replace its FakeCamera with your camera driver and the print with your control loop.
import base64 import time import cv2 import numpy as np import dream ROBOT_ID = "rbt_0123456789abcdef" # your robot's id: the robot_id under live: in ~/.dreamlabs/station.yaml TICKS = 60 # how many ticks this program runs before it stops class Episode: """The robot's status as the page shows it: `running` from a viewer's Start until Stop, else `idle`. The page shows the task and its Stop button only while the status is `running`. Attributes: - status: What stream() reports. """ def __init__(self) -> None: """Starts idle.""" self.status = "idle" def on_change(self, event: dream.EventChange) -> None: """The callback: a Start begins an episode; a Stop, or a new task while running, ends it. It runs on the Live View client's thread, so it only records the change; the loop acts on it. @param event What the viewer did. """ self.status = "running" if event is dream.EventChange.start else "idle" def main() -> None: """Streams every tick with the episode's status and reads the viewer's task.""" camera = FakeCamera() episode = Episode() with dream.LiveViewClient(ROBOT_ID) as live: live.register_callback(episode.on_change) for _ in range(TICKS): obs = {key: camera.read() for key in ("video.overhead", "video.wrist_l", "video.wrist_r")} obs["state.right_arm"] = [0.0] * 6 live.stream(obs, episode.status) task = live.get_prompt() # None until a viewer sends one if task and episode.status == "running": print("running:", task) # your control loop runs the task here time.sleep(1 / 30) class FakeCamera: """Stands in for your camera driver: one 640x360 frame per read, as a base64 JPEG.""" def read(self) -> str: """One frame. @return The frame, a base64 JPEG. """ _, jpeg = cv2.imencode(".jpg", np.zeros((360, 640, 3), dtype=np.uint8)) return base64.b64encode(jpeg.tobytes()).decode() if __name__ == "__main__": main()
The three calls and the callback
Section titled “The three calls and the callback”live.stream(obs, status)whenever you have something new: every tick of your loop, every camera frame, or from a thread of your own. The client does all of its work on its own thread, which reads your newest call 60 times a second, so when and how often you call it never slows your loop and never changes the video.obsis the observation you handDreamClient.set_observation(), frames and state in one mapping; the frames become the page’s cameras (What the page shows) and the other keys are not sent.statusis the robot’s state as the page shows it:idle,runningorerror. It returns at once and never waits on the network. The first call connects and fixes the cameras; every later call carries the same ones.live.get_prompt()is the task a viewer last sent from the page, orNoneuntil one does. Read it on every tick: a viewer can send a new task at any time.live.register_callback(fn)registersfn, called withdream.EventChange.startwhen a viewer presses Start, and withdream.EventChange.endwhen a viewer presses Stop or sends a new task while the robot runs (get_prompt()then holds the new task). The callback runs on the client’s own thread, not your loop’s, so keep it short: record what happened, asEpisode.on_changeabove does, and let the loop act on it at its next tick.
Use the client as a with block, as above, or call live.close() when you are done; either ends the connection.
What the page shows
Section titled “What the page shows”Each video.<role> key of obs, one base64 JPEG, is a camera on the page. The three roles of the YAM’s observation land where the page expects them; any other role shows under its own name.
Key in obs |
On the page |
|---|---|
video.overhead |
top, the main picture |
video.wrist_l |
left, the left side panel |
video.wrist_r |
right, the right side panel |
video.<other role> |
A panel named <other role> |
The status decides which buttons the page offers. It shows Start while the robot is idle or error, and shows the task and its Stop button only while the robot is running. So report running from the moment your callback gets EventChange.start until the episode ends, with EventChange.end or because your loop finished the task; a loop that keeps reporting idle after a Start leaves the viewer with no task shown and no way to stop. The page’s Home and Reset arms buttons are answered “not supported” unless your callback takes them (Everything the station does): the client moves no arms, your loop does. Your code also chooses the model: the page shows the checkpoint your DreamClient runs (with dream_client=client) and locks its model and action pickers, because a model picked there would never reach your loop.
With Dream-1 in the same loop
Section titled “With Dream-1 in the same loop”DreamClient and LiveViewClient are two clients in one loop, each with its own connection. Build the Live View client with dream_client=client: while the robot is running it then reports each round trip of the model to the page, as the station does. The page shows a run as “Dream-1 is getting ready” until the first one arrives, so without it the banner never clears. On every tick the loop hands the same cameras and state to both: client.set_observation(frames, observation) for the model, with frames at the model’s small size, and live.stream({**shown, **observation}, status) for the page, with the same images encoded at 640 pixels wide, Live View’s own width. The model’s small frames would look blurred stretched across the page. The task the model runs is live.get_prompt(), and the viewer’s Start and Stop drive the episode: a Start begins one, so the loop calls client.reset_episode() and reports running; a Stop ends it, so the loop resets again, reports idle and holds the arms. The program below is The whole loop in one file with Live View added; the callback only queues what the viewer pressed, and the loop reads the queue once a tick.
import base64 import queue import time import cv2 import dream import numpy as np ROBOT_ID = "rbt_0123456789abcdef" # your robot's id: the robot_id under live: in ~/.dreamlabs/station.yaml CAMERAS = ("overhead", "wrist_l", "wrist_r") PARTS = { "right_arm": [0, 6], "right_gripper": [6, 7], "left_arm": [7, 13], "left_gripper": [13, 14], } VIDEO = {role: f"observation.images.{role}" for role in CAMERAS} YAM = {"state": PARTS, "action": PARTS, "video": VIDEO} pressed = queue.SimpleQueue() # what viewers pressed; the callback runs on the Live View client's thread # dream_client=client: the page hears the model's round trips, and stops showing the run as getting ready. with dream.DreamClient() as client, dream.LiveViewClient(ROBOT_ID, dream_client=client) as live: client.policy({"checkpoint": "dreamlabs/dream-1-beta", "embodiment": YAM, "ik": {"arm": "yam", "head": "joint"}}) live.register_callback(pressed.put) status = "idle" rows = [] for _ in range(60): # Your robot now: each camera's newest image, then each arm's # 6 joints in radians and its gripper, 0 closed to 1 open. images = {role: np.zeros((360, 640, 3), np.uint8) for role in CAMERAS} right, left = np.zeros(7), np.zeros(7) frames, shown = {}, {} # the model's small frames, and the page's at its own 640 px width for role, image in images.items(): ok, jpeg = cv2.imencode(".jpg", cv2.resize(image, (320, 176))) frames[f"video.{role}"] = base64.b64encode(jpeg.tobytes()).decode() ok, jpeg = cv2.imencode(".jpg", cv2.resize(image, (640, 360))) shown[f"video.{role}"] = base64.b64encode(jpeg.tobytes()).decode() observation = { "state.right_arm": right[:6], "state.right_gripper": right[6:], "state.left_arm": left[:6], "state.left_gripper": left[6:], } # A viewer pressed Start, or Stop, since the last tick: the status the page shows follows, and the # episode starts over with a fresh session and empty frames. while not pressed.empty(): status = "running" if pressed.get() is dream.EventChange.start else "idle" client.reset_episode() rows = [] # The same cameras, sharper, and the same state; arms= draws the robot on the page. arms = {"right": (right[:6], right[6]), "left": (left[:6], left[6])} live.stream({**shown, **observation}, status, arms=arms) task = live.get_prompt() if status != "running" or not task: time.sleep(1 / 20) continue # the arms hold until a viewer presses Start with a task observation["prompt"] = task client.set_observation(frames, observation) # Chunk played: ask for the next 48 rows. The arms hold meanwhile. if not rows: try: action = client.get_action() except dream.DreamServerError as error: if not error.retryable: raise time.sleep(error.retry_after_s or 1.0) continue rows = list(zip(action["q_r_chunk"], action["q_l_chunk"])) # Your arms: send them this row, inside your speed and joint limits. right_target, left_target = rows.pop(0) time.sleep(1 / 20) # 20 rows a second
Everything about the model’s calls, the chunks and the safety of the arms is as Your own control loop says; Live View changes none of it.
Everything the station does, from your own loop
Section titled “Everything the station does, from your own loop”Our control loop is one more caller of this same client: dreamcli robot up builds a LiveViewClient, calls stream() 60 times a second and answers every button with its own calls. Everything it shows, your loop can show too, with optional keywords to stream() and options to the callback:
| What the page shows or offers | How |
|---|---|
| The robot drawn in 3D as it moves | stream(..., arms={"left": (q, gripper), "right": (q, gripper)}): each arm’s joint angles in radians and its gripper, 0 closed to 1 open; None for an arm that does not answer |
| Why the arms are not moving | stream(..., error="..."), or (message, code) with a short code; leave it out while nothing is wrong |
| The task, the run number, the model, the step count | stream(..., prompt=..., run=..., model=(checkpoint, action_space), steps=...); with steps the page offers a step count where the platform offers one (a Steps pill beside the model; not every platform does), which live.get_steps() then returns after a Start, and None where the page offered none |
| Home and Reset arms | live.register_callback(fn, home=True, reset=True): fn also gets EventChange.home and EventChange.reset |
| A new task while running, apart from Stop | live.register_callback(fn, prompt=True): a new task is EventChange.prompt, not EventChange.end |
| The viewer picks the model | dream.LiveViewClient(robot_id, model_fixed=False): the pickers open, and live.get_model() returns (checkpoint, action_space) after a Start |
A callback that does real work, such as homing the arms, returns it as an awaitable, for example asyncio.run_coroutine_threadsafe(home(), loop): the client waits up to 10 s for it and tells the page whether it worked (return the state after it, or {"state": ..., "error": "..."} when it failed), and never cancels a Start, Stop, Home or Reset halfway. The frames are blurred where a face is found before they leave your computer; face_blur=False turns that off.
The robot id and your key
Section titled “The robot id and your key”dream.LiveViewClient(robot_id) takes the robot’s id on the platform, rbt_ followed by 16 hex digits. A robot gets its id when it is registered, one of two ways. The setup wizard (dreamcli setup, from the platform’s Robot Setup, where the Live View page’s Add robot also leads) registers it on Save and writes the id into the station file, ~/.dreamlabs/station.yaml, as live: {robot_id: rbt_...}; copy it from there. Or register one yourself, with your API key, by one call to the platform; name is the label the Live View page shows, and embodiment is yam for a YAM, or the embodiment of your own that the robot runs:
source ~/.dreamlabs/credentials curl -s -X POST "$DREAM_API_URL/v1/robots" \ -H "Authorization: Bearer $DREAM_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "lab-robot", "embodiment": "yam"}'
It answers with the robot as the platform holds it, {"id": "rbt_...", "name": "lab-robot", "embodiment": "yam", "status": "online", ...}: pass that id. The Live View page lists robots by name, not by id. A loop that passes the id of a robot the key does not own is refused (Troubleshooting).
Your API key comes from the same place as for dream.DreamClient: the api_key= argument, else DREAM_API_KEY, else ~/.dreamlabs/credentials (Getting started). Which platform it connects to is set by Dream Labs in that file, never by your code. Without a key the constructor raises DreamConfigError. The platform must be https://: the key travels on the connection, and the client refuses to send it in the clear to any host but your own computer.
What is sent
Section titled “What is sent”The client keeps one outbound connection to the platform, so it works behind NAT with nothing to open at your end. Everything the client does, encoding included, runs on its own low-priority thread, never on your loop’s. If that thread cannot keep up, because the computer has no CPU to spare, the client pauses the video for 30 seconds rather than compete with your loop, and the page says so. Your loop’s own pace, a slow model call or the arms holding while it waits, never pauses it. A camera is encoded as video only while a viewer watches it, and only the newest observation is ever sent; hand the client a new image for each new camera frame and the same one while the camera has nothing new, and each frame is encoded once: on a slow uplink frames are dropped, never queued, and your loop is never held up. The connection is redialed on its own after a network fault; a status or a frame sent meanwhile is simply the newest one when the link is back.
Troubleshooting
Section titled “Troubleshooting”- The robot never shows up on the page. The platform refused the connection; the library’s log file,
~/.dream/logs/dream.log, says why, with a code (nothing is printed to the terminal;tail -f ~/.dream/logs/dream.login another terminal shows it as it happens).4001is a key the platform does not know.4004is a robot id it does not know, or one that belongs to another account than the key’s: check the id against~/.dreamlabs/station.yaml.4005is a key that was revoked. The client retries every 30 s, so a fixed key or id is picked up without a restart. - The page shows no task and no Stop button after Start. Your loop still reports
idle: switchstatustorunningwhen your callback getsEventChange.start, as both examples do. - The page shows “Dream-1 is getting ready” for the whole run. The page waits for the model’s round trips, and the client reports them only when it is built with
dream_client=client, your loop’sDreamClient. - The video looks blurred. You are streaming the model’s small frames; give
stream()its own frames at 640 pixels wide, as the example does. - The page says the robot is offline. Nothing has called
stream()yet, or the loop stopped calling it; the connection opens on the first call. Check that your loop reachesstream()on every tick. - The model menu is greyed out. That is by design: the model is the
checkpointyour code passes toclient.policy(), and the page shows it. To run another model, change it in your code. - Home and Reset arms fail on the page. They are answered “not supported”: the client has no arms to move. Start and Stop reach your callback.
- The video lags or skips. Only the newest frame is sent, so a lagging picture is the uplink from the robot’s computer, not a queue in your loop. Frames are resized to 640 pixels wide before encoding; sending larger frames costs decoding time and gains nothing.
stream()raisesDreamObservationError.obshas novideo.<role>frame, its cameras differ from the first call’s, orstatusis empty.- The constructor raises
DreamConfigError. No key is set anywhere,robot_idis empty, the platform URL ishttp://on a host other than this computer, or PyAV, OpenCV or websockets is missing: the message names the three, and all of them come with the dream library (Getting started).