Skip to content

Websockets

Overview

The WebSocket API provides real-time, continuous data streaming from the robot to the client. This is ideal for applications that require up-to-the-second updates, such as telemetry and live monitoring.

WebSocket URL: wss://<ROBOT_IP>/wss

Connecting to the WebSocket

To connect to the WebSocket, use the WebSocket URL and include the JWT token in the initial request as a query parameter.

Example using websockets in Python

import asyncio
import websockets

async def connect_to_websocket():
    jwt_token = "your_jwt_token_here"
    ws_url = f"wss://<ROBOT_IP>/wss?token={jwt_token}"
    async with websockets.connect(ws_url) as websocket:
        print("Connected to WebSocket")
        # Subscribe to a topic
        await websocket.send(json.dumps({"action": "subscribe", "topic": "server_logs"}))
        # Receive messages
        async for message in websocket:
            print(f"Received message: {message}")

asyncio.run(connect_to_websocket())

Example using JavaScript

const token = "your_jwt_token_here";
const ws = new WebSocket(`wss://<ROBOT_IP>/wss?token=${token}`);

ws.onopen = function(event) {
    console.log("WebSocket connection established");
    // Subscribe to a topic
    ws.send(JSON.stringify({ action: "subscribe", topic: "server_logs" }));
};

ws.onmessage = function(event) {
    console.log("Message from server", event.data);
};

ws.onerror = function(error) {
    console.log("WebSocket error", error);
};

ws.onclose = function(event) {
    console.log("WebSocket connection closed", event);
};

Token Expiration and Reconnection

The WebSocket token is checked when the connection is opened. If the JWT expires while the socket is idle, the server can close the connection and the client must reconnect with a fresh token.

Recommended client behavior:

  1. Decode the JWT payload locally and read the exp claim.
  2. Refresh before that time with GET /api/v2/auth/refresh/ and Authorization: Bearer <token>.
  3. Store the refreshed token from the Authorization response header.
  4. Reconnect the WebSocket with ?token=<new-token>.
  5. Re-send subscriptions after reconnecting.

The bundled Wizard frontend and pymirokai client handle this automatically.

Messages

To subscribe to a topic:

{
  "action": "subscribe",
  "topic": "some_topic"
}

To unsubscribe from a topic:

{
  "action": "unsubscribe",
  "topic": "some_topic"
}

To publish data to a topic:

{
  "action": "publish",
  "topic": "some_topic",
  "data": {"name": "name_of_data", "type": "type_of_data", "data": "your_data_here"}
}

System logs

Some system logs are published by the WebSocket server on the "server_logs" topic. Subscribe to this topic to get the server messages.