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.
await studio.SubscribeAsync(TopicType.Audio, TopicType.Stream);
studio.State.StreamChanged += (_, s) => Console.WriteLine($"Stream: {s.State} for {s.Seconds} s");await studio.subscribe("audio", "stream");
studio.onState("stream", (s) => console.log(`Stream: ${s.state} for ${s.seconds} s`));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.
metersis pushed ten times a second; follow it while you draw levels and unfollow it after. - Count timers locally.
streamandrecordcarryseconds. 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.
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);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");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,onHandlerErrororon_handler_error. - Events newer than your SDK arrive through
UnknownNotification,onUnknownoron_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 aschat.deletedwith theeids to remove; a card that changes in place (a poll's votes) arrives asactivity.updatedwith the sameeid.
Reconnecting
Reconnecting is on by default in every SDK. When Studio restarts, or the connection drops, the client:
- raises a disconnect with the reason, and whether it's reconnecting;
- reads the discovery file again before each try, because the port and the token may have changed;
- waits a moment, doubling the wait after each failed try up to a limit;
- reconnects, and follows the same topics again, so the state comes back on its own;
- raises a reconnect with the new hello.
studio.Disconnected += (_, e) => Console.WriteLine($"Disconnected ({e.Reason}){(e.Reconnecting ? "; reconnecting…" : "")}");
studio.Reconnected += (_, h) => Console.WriteLine($"Reconnected to {h.InstanceName}.");studio.onDisconnected((d) => console.log(`Disconnected (${d.reason})${d.reconnecting ? "; reconnecting…" : ""}`));
studio.onReconnected((h) => console.log(`Reconnected to ${h.instance_name}.`));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.jsonbefore every connection attempt. A401means 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
pingevery 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,
subscribeto the same topics again (and pass"typed_events": trueagain if you use it), then redraw from thestatenotifications.

