Skip to content
Platform

Use the station description for joint order, units and camera names. Feed the model measured positions from session.get_joints() and decode each camera message’s jpeg bytes. Treat each camera frame and joint sample as a separate observation.

Return one dictionary of absolute joint targets per control step. Every dictionary in a chunk must name the same joints. With session.send_chunk(targets, dt, t0=t), target i is scheduled at t + i * dt before the station’s playout delay. Take t from time.monotonic() on the client. Check the station limits before submitting a chunk.

Save fake_api.py beside your script and install httpx==0.28.1 with the client. Run this metadata check without a station:

import httpx
from bsln.sdk import Client
from fake_api import FakeApi, TOKEN, URL
with Client(URL, TOKEN, transport=httpx.MockTransport(FakeApi())) as client:
description = client.session_description("ses_0000000000000001")
print(description["joint_order"])

This fixture handles HTTP reads only. Keep WebSocket calls out of the test. Run adapter_check.py to check your adapter’s joint order and units.

Feed recorded positions to your input adapter and assert the output keys match your controlled joints. Reject nonfinite targets and values outside each joint’s safe_range. Measure inference time against the chunk horizon. Use the recording exercise to read joint values without opening a session.

Confirm SDK access and the approved robot, then save this as my_policy_loop.py. The model sends 12 targets each cycle to the left wrist joint left_joint6. It uses the station’s control_hz to space those targets.

import math
import sys
import time
from bsln.sdk import Client, SessionError
ROBOT_TYPE = "bimanual_arm"
REQUEST_ID = input("Pilot request ID (Enter for standard SDK access): ").strip() or None
RUN_S = 10.0 # the policy drives for 10 s
CYCLE_S = 0.1 # one observation and one chunk every 0.1 s
CHUNK = 12
class MyPolicy:
"""A stand-in for your model. It waves the left wrist by 0.1 rad around its start position."""
def __init__(self, control_hz: float):
self.dt = 1.0 / control_hz
self.center: float | None = None
def act(self, observation: dict) -> list[dict[str, float]]:
"""Return the targets for the next CHUNK control steps, one dict for each step.
observation["joints"]: {joint name: position}, using the units reported by the station.
observation["images"]: {camera name: JPEG bytes}. Decode them for your model, for example with Pillow.
observation["time"]: seconds since the policy started.
"""
if self.center is None:
self.center = observation["joints"]["left_joint6"]
t = observation["time"]
return [{"left_joint6": self.center + 0.1 * math.sin(math.pi * (t + i * self.dt))} for i in range(CHUNK)]
def observe(session, images: dict[str, bytes], t: float) -> dict:
"""The newest joint positions and the newest image of each camera."""
while (message := session.recv(timeout=0)) is not None: # everything that arrived since the last cycle
if message["type"] == "frame":
images[message["camera"]] = message["jpeg"]
return {"joints": session.get_joints(), "images": dict(images), "time": t}
client = Client() # reads BSLN_URL and BSLN_TOKEN, or the values that `bsln login` saved
# The server assigns an idle real station of this robot type. frames=True: the stream also brings the camera images.
with client.start_session(
robot_type=ROBOT_TYPE, frames=True, max_occupied_s=60, request_id=REQUEST_ID
) as session:
print("session:", session.id)
station = session.description
hz = station["control_hz"]
cameras = ", ".join(camera["name"] for camera in station["cameras"])
print(f"{station['robot_type']}: {len(station['joint_order'])} joints, {hz:g} Hz, cameras {cameras}")
policy = MyPolicy(hz)
images: dict[str, bytes] = {}
chunks = 0
begin = time.monotonic()
try:
while (now := time.monotonic()) - begin < RUN_S:
observation = observe(session, images, now - begin)
actions = policy.act(observation)
session.send_chunk(actions, dt=1.0 / hz, t0=now) # target i is for the time now + i / hz
chunks += 1
time.sleep(max(0.0, CYCLE_S - (time.monotonic() - now)))
session.hold() # stop here. The arms keep the last target.
except SessionError as error: # the session ended, or the connection is lost. The station holds the arms.
sys.exit(f"stopped: {error}")
except KeyboardInterrupt:
sys.exit("Interrupted. Check the session outcome before starting another session.")
print(f"sent {chunks} chunks, images from {', '.join(sorted(images)) or 'no camera'}")
print(f"deadman holds: {session.get_state()['deadman_holds']}, dropped messages: {session.stats()['dropped']}")
session.end()

Enter your assigned request ID if you have a one-session grant. It must allow 60 seconds and be unused.

uv run python my_policy_loop.py

If the arm holds between chunks, compare the late-target and dropped-message counters in the session report.