Developer
Log in

SDKs

Events and reconnecting

A control surface runs for hours while Studio starts, quits and restarts around it. These are the patterns that keep it right the whole time, in all three SDKs.

Follow state, don't poll it

Subscribe once to the topics you show. Studio sends each one's current value straight away, then again whenever it changes. Draw from the latest value; never ask on a timer.

C#
await studio.SubscribeAsync(TopicType.Audio, TopicType.Stream);
studio.State.StreamChanged += (_, s) => Console.WriteLine($"Stream: {s.State} for {s.Seconds} s");
TypeScript
await studio.subscribe("audio", "stream");
studio.onState("stream", (s) => console.log(`Stream: ${s.state} for ${s.seconds} s`));
Python
await studio.subscribe(TopicType.AUDIO, TopicType.STREAM)
studio.on_state(TopicType.STREAM, lambda s: print(f"Stream: {s.state.value} for {s.seconds} s"))
  • Follow only what's on screen. meters is pushed ten times a second; follow it while you draw levels and unfollow it after.
  • Count timers locally. stream and record carry seconds. Add the time since the last push for an uptime clock, instead of asking Studio every second. The Stream Deck plugin and the Companion module both do this.
  • Media positions move with the clock. While a media source plays on air, its position is position_ms + (now − at_ms); the topic is pushed only when something else happens.

Handle events by type

Events say something happened: a scene went on air, a raid arrived, a recording paused. Each has its own type, and you get it while you follow its topic.

C#
studio.SceneChanged += (_, e) => Console.WriteLine($"On air: {e.Name}");
studio.EventReceived += (_, e) =>
{
    switch (e)
    {
        case ActivityRaidEvent r: Console.WriteLine($"Raid: {r.Amount?.Value} viewers"); break;
        case ChatRowEvent row: Console.WriteLine($"{e.Type}: {row.Text}"); break;   // every chat row and activity
    }
};
await studio.SubscribeAsync(TopicType.Scenes, TopicType.Chat, TopicType.Activity);
TypeScript
studio.on("scene.changed", (e) => console.log(`On air: ${e.name}`));
studio.onEvent((e) => {
  switch (e.type) {
    case "activity.raid": console.log(`Raid: ${e.data.amount?.value} viewers`); break;
    case "chat.deleted": console.log(`${e.data.eids.length} messages removed`); break;
  }
});
await studio.subscribe("scenes", "chat", "activity");
Python
studio.on(EventType.SCENE_CHANGED, lambda e: print(f"On air: {e.name}"))

async for event in studio.events():
    match event:
        case ActivityRaidEvent(amount=ChatAmount(value=viewers)):
            print(f"Raid: {viewers:.0f} viewers")
        case ChatRow(text=text):
            print(f"{event.type.value}: {text}")
  • Handlers run in order, on the connection's own path. Keep them quick, and hand long work to your own task or thread.
  • A handler that throws doesn't stop the client. You hear about it through HandlerFailed, onHandlerError or on_handler_error.
  • Events newer than your SDK arrive through UnknownNotification, onUnknown or on_unknown. Ignore them, or handle them by their data.
  • Chat rows are one shape. A message, a follow, a sub, a gift, a raid and a poll card are all a ChatRow, so one renderer shows them all. A deleted message arrives as chat.deleted with the eids to remove; a card that changes in place (a poll's votes) arrives as activity.updated with the same eid.

Reconnecting

Reconnecting is on by default in every SDK. When Studio restarts, or the connection drops, the client:

  1. raises a disconnect with the reason, and whether it's reconnecting;
  2. reads the discovery file again before each try, because the port and the token may have changed;
  3. waits a moment, doubling the wait after each failed try up to a limit;
  4. reconnects, and follows the same topics again, so the state comes back on its own;
  5. raises a reconnect with the new hello.
C#
studio.Disconnected += (_, e) => Console.WriteLine($"Disconnected ({e.Reason}){(e.Reconnecting ? "; reconnecting…" : "")}");
studio.Reconnected += (_, h) => Console.WriteLine($"Reconnected to {h.InstanceName}.");
TypeScript
studio.onDisconnected((d) => console.log(`Disconnected (${d.reason})${d.reconnecting ? "; reconnecting…" : ""}`));
studio.onReconnected((h) => console.log(`Reconnected to ${h.instance_name}.`));
Python
studio.on_disconnected(lambda d: print(f"Disconnected ({d.reason}){'; reconnecting…' if d.reconnecting else ''}"))
studio.on_reconnected(lambda h: print(f"Reconnected to {h.instance_name}."))

The timing is yours to tune:

C# (VelumClientOptions) TypeScript (options) Python (connect(...)) Default
Reconnect at all AutoReconnect autoReconnect auto_reconnect on
First wait ReconnectDelay reconnectDelayMs reconnect_delay 0.25 s
Longest wait MaxReconnectDelay maxReconnectDelayMs max_reconnect_delay 5 s
Connecting may take ConnectTimeout connectTimeoutMs connect_timeout 10 s
An answer may take RequestTimeout requestTimeoutMs request_timeout 60 s (going live can take a while)

A request that's waiting when the connection drops fails with the connection error (VelumConnectionException or VelumConnectionError). Whether to send it again is your call: switching a scene again is harmless, but sending record.toggle twice stops the recording it started. Check the state first.

Never show stale state

While the client is disconnected, what you last saw may no longer be true. Show that plainly:

  • Dim, don't freeze. The Stream Deck plugin dims every key and adds an unplugged badge; the Companion module turns every feedback off and empties its state variables. Neither shows the last value as if it were current.
  • Say why. The disconnect's reason is plain English, ready to show.
  • Come back by itself. After the reconnect, the topics are pushed again; redraw from them.

If you write your own client

The same rules, without an SDK:

  • Re-read control.json before every connection attempt. A 401 means the token changed: read the file again within a second, not after a long backoff.
  • Back off between tries, starting small and doubling to a limit.
  • Send a ping every 15 seconds or so (the Stream Deck plugin does). If it isn't answered, treat the connection as gone, even if the socket hasn't closed.
  • After reconnecting, subscribe to the same topics again (and pass "typed_events": true again if you use it), then redraw from the state notifications.

to open · ↑ ↓ to move · Esc to close