Skip to main content

Connection

Monitor the connection lifecycle between your device and RelayX. Register listeners for status changes like connect, disconnect, and reconnect events.

Overview

The connection module provides visibility into the device's connection state. You don't need to manage reconnection yourself — the SDK handles it automatically — but you can react to status changes.

Access via device.connection.

API

device.connection.listeners(callback: (event) => void) → void
  • callback — Called whenever the connection status changes
  • event — An object with a type property indicating what happened

Status Events

EventDescription
connectedSuccessfully connected to RelayX
disconnectedConnection closed (only on explicit disconnect() calls)
reconnectingConnection lost, SDK is attempting to reconnect
reconnectedSuccessfully reconnected after a drop
auth_failedAuthentication failed — check your API key and secret

Register a Listener

device.connection.listeners((event) => {
console.log("Status:", event.type);
});

Handling Each Event

device.connection.listeners((event) => {
switch (event.type) {
case "connected":
console.log("Connected to RelayX");
break;
case "disconnected":
console.log("Disconnected");
break;
case "reconnecting":
console.log("Connection lost, reconnecting...");
break;
case "reconnected":
console.log("Reconnected — buffered messages flushed");
break;
case "auth_failed":
console.error("Authentication failed — check your API key");
break;
}
});

Multiple Listeners

You can register multiple listeners. Each one is called independently when a status change occurs.

// logging
device.connection.listeners((event) => {
console.log(`[${new Date().toISOString()}] ${event.type}`);
});

// UI updates
device.connection.listeners((event) => {
updateStatusIndicator(event.type);
});

Reconnection Behavior

When the connection drops unexpectedly, the SDK automatically handles reconnection:

  1. A reconnecting event is emitted once
  2. The SDK keeps retrying until a connection is re-established
  3. All active RPC and command listeners are resubscribed
  4. Any telemetry or events buffered while offline are flushed in order
  5. A reconnected event is emitted
info

The disconnected event only fires on explicit disconnect() calls — not on unexpected connection drops. If the connection drops unexpectedly, you'll see reconnecting followed by reconnected.

Connect and Disconnect

Connection is managed at the device level, not through this module:

// connect
await device.connect();

// disconnect
await device.disconnect();

Both methods return true if the state changed, false if already in that state (e.g., calling connect() when already connected).