Playground key
create a key →

Guide

Hardware & devices.

Devices join a stream with its stream key. A device trades the key for a 15-minute token at POST /v1/streams/token, then connects to the stream's room with a LiveKit client SDK, the same way your end-users do.

Device roles

  • camera publishes video and audio. The stream goes live when the first one connects. A stream takes up to eight, each under its own name, and its hls setting decides which are recorded.
  • robot receives input from the controller and publishes telemetry.
  • operator publishes a person's webcam and mic over WebRTC only. It never makes the stream live and is never recorded.

A robot with its own camera can connect once, as camera: camera tokens also receive input and publish telemetry. Use robot when the camera is a separate device, like a phone.

Connect a robot

Any machine that runs a LiveKit SDK can be the robot: Linux on x64 or arm64 (64-bit Raspberry Pi OS, Jetson), macOS or Windows. This example uses the Node SDK. Python, Go and Rust work the same way.

It follows the full safety contract: it acts only on the controller named in the room's metadata, stops on an e-stop and when input goes quiet, and honours the stream's control timeout and max lag.

robot.mjs
// npm install @livekit/rtc-node
// setMotors, runCommand and readBattery are yours.
import { Room, RoomEvent } from "@livekit/rtc-node";

const API = "https://platform.droidhub.cloud/api";
const streamKey = process.env.DROIDHUB_STREAM_KEY; // dh_sk_…
const encode = (msg) => new TextEncoder().encode(JSON.stringify(msg));

async function robotToken() {
  const res = await fetch(`${API}/v1/streams/token`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ streamKey, role: "robot" }),
  });
  if (!res.ok) throw new Error(`token exchange failed: ${res.status}`);
  return res.json(); // { token, url, room, expiresInSeconds }
}

const room = new Room();
let state = null; // who holds control, the e-stop and the policy
let lastInputAt = 0;
let lastFromController = 0;
let controllerSince = 0;
let rtt = null;
let lastPongAt = 0;
let holding = false;
let reportedFor = null;

// eugene keeps the control state in the room's metadata.
function onState() {
  const prev = state;
  try {
    state = JSON.parse(room.metadata || "{}").droidhub ?? null;
  } catch {
    state = null;
  }
  if (state?.controller?.assignmentId !== prev?.controller?.assignmentId) {
    controllerSince = Date.now();
    lastFromController = 0;
    rtt = null;
  }
  if (!state?.controller || state.estop) setMotors(0, 0);
}
room.on(RoomEvent.RoomMetadataChanged, onState);

room.on(RoomEvent.DataReceived, (payload, participant, _kind, topic) => {
  // Only the controller drives. Cameras and other devices can send data too.
  if (!state?.controller || participant?.identity !== state.controller.identity) return;
  lastFromController = Date.now();
  let msg;
  try {
    msg = JSON.parse(new TextDecoder().decode(payload));
  } catch {
    return;
  }
  if (topic === "dh.hb") {
    if (typeof msg.pong === "number") {
      rtt = Date.now() - msg.pong;
      lastPongAt = Date.now();
    }
    return;
  }
  // Axes: [left, right], each -100..100.
  if (!Array.isArray(msg) || state.estop || holding) return;
  setMotors(msg[0] ?? 0, msg[1] ?? 0);
  lastInputAt = Date.now();
});

// Safety loop.
setInterval(async () => {
  const now = Date.now();
  if (now - lastInputAt > 400) setMotors(0, 0); // input went quiet
  const c = state?.controller;
  if (!c || state.estop) return;

  // Max lag: ping the controller, hold still while the round trip is too long.
  if (state.maxLagMs) {
    room.localParticipant
      .publishData(encode({ ping: now }), {
        reliable: false,
        topic: "dh.hb",
        destination_identities: [c.identity],
      })
      .catch(() => {});
    holding = rtt === null || rtt > state.maxLagMs || now - lastPongAt > state.maxLagMs + 250;
    if (holding) setMotors(0, 0);
  } else {
    holding = false;
  }

  // Control timeout: the controller went quiet. Stop, then report it once.
  const quietFor = now - Math.max(lastFromController, controllerSince);
  if (state.controlTimeoutMs && quietFor > state.controlTimeoutMs && reportedFor !== c.assignmentId) {
    reportedFor = c.assignmentId;
    setMotors(0, 0);
    await fetch(`${API}/v1/streams/control-timeout`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ streamKey, identity: c.identity, assignmentId: c.assignmentId }),
    }).catch(() => {});
  }
}, 100);

const { token, url } = await robotToken();
await room.connect(url, token, { autoSubscribe: false });
onState();

// Discrete commands: RPC calls addressed to this robot's identity.
room.localParticipant.registerRpcMethod("control", async ({ callerIdentity, payload }) => {
  if (callerIdentity !== state?.controller?.identity || state.estop) {
    throw new Error("not the controller");
  }
  const { cmd } = JSON.parse(payload); // e.g. { "cmd": "honk" }
  runCommand(cmd);
  return "ok";
});

// Telemetry: any JSON, to everyone in the room.
setInterval(() => {
  room.localParticipant
    .publishData(encode({ battery: readBattery() }), { reliable: true, topic: "telemetry" })
    .catch(() => {});
}, 5000);

The robot's identity is robot_<streamId> unless you pass your own. A connected robot stays connected past its token's 15 minutes. If the room disconnects, stop, exchange the key again and reconnect.

Identities

Identities that start with camera mark a camera. Give robots and operators identities that don't.

Test with the dashboard

Open the stream in the dashboard, select Connect, then Take control, and drive with WASD or the arrow keys. The drive pad sends the input format the example above reads:

  • A JSON array [left, right] of integers from −100 to 100, tank style.
  • 20 frames a second while a key is held, sent lossy: only the newest frame matters.
  • Five zero frames on release, then nothing until the next key.
  • W and S send ±60 on both sides. A and D turn in place at ±40. Held together they add up, clipped to ±100.

The pad also sends heartbeats and answers pings, so a stream's control timeout and max lag work with it. Your own controller can send anything your robot understands; the control-queue recipe uses this format.

Failsafe

DroidHub decides who may drive and enforces it at the media server. Stopping is the robot's job: when input goes quiet for about 400 ms, when the room state shows an e-stop or no controller, and when the room disconnects. Input stops when the driver lets go, loses their connection, or loses control to someone else.

Cameras

A camera publishes with a camera token from any LiveKit SDK: web, iOS, Android, React Native, or Node, Python, Go and Rust on Linux. If the stream's hls setting covers it, HLS recording starts when its video arrives. Pass orientation: "portrait" for a phone held upright. The test publisher goes live from a webcam.

For more angles, give each extra camera its own name in the token exchange. The one without a name is main: its playlist is the stream's hlsPlaybackUrl.

a second camera
POST /api/v1/streams/token
{ "streamKey": "dh_sk_…", "role": "camera", "camera": "arm" }

Viewers tell the cameras apart by the camera field in each participant's metadata. Set the stream's hls to all to record every camera.

Microcontrollers

An ESP32 or an Arduino can't run WebRTC. Pair it with a small computer, such as a Raspberry Pi, that runs the robot client and talks to the board over serial or USB.