Skip to main content

Web (JavaScript/TypeScript)

A minimal reconnecting client. Handles origin implicitly (the browser sets it), re-sends watches on reconnect, and ignores unknown message types instead of throwing.

interface RegisterInfo {
address: number;
addressHex?: string;
name: string;
description?: string;
dataType: string;
length: number;
scale: number; // the bit = 0 default when scaleRule is present
// Present when the device selects the scale at run time — see the
// `scaleRule` row under "What each register carries".
scaleRule?: { register: number; bit: number; scaleIfClear: number; scaleIfSet: number };
unit?: string;
access: 'R' | 'W' | 'RW' | ''; // '' = access not recorded in the vendor spec
functionCode: number;
category?: string;
lowLimit?: string;
highLimit?: string;
min?: number; // raw register units (before scale)
max?: number;
options?: { value: number; label: string; default?: boolean }[];
multiple?: boolean;
value?: number; // only with includeValues; engineering units
// Always present, never empty — see "displayLabel: one label per
// concept, across models" above. Build a settings screen off this, not
// off `name`.
displayLabel: string;
}

// A grouped model's reply nests entries by UI group — see "Grouped replies".
interface RegisterGroup {
group: string;
children: RegisterInfo[];
}

interface TelemetryRecord {
deviceKey: string;
model: string;
receivedAt: string;
cadence: 'default' | 'watched';
registered: boolean;
readings: Record<string, unknown>; // flat: register names, canonical fields, _metadata
}

// Covers the live-view messages; the other reply types are listed in the
// "Server → client" table above.
type ServerMessage =
| { type: 'watch_ack'; deviceKey: string; ok: boolean; model?: string; registersVersion?: string; code?: 'DEVICE_NOT_FOUND' | 'DEVICE_REVOKED'; error?: string }
| { type: 'all_registers'; deviceKey: string; ok: boolean; error?: string; model?: string; access?: string; registersVersion?: string; valuesError?: string; registers?: RegisterInfo[] | RegisterGroup[] }
| { type: 'registers_values'; deviceKey: string; ok: boolean; error?: string; values?: { register: string; ok: boolean; error?: string; value: number; text?: string }[] }
| { type: 'telemetry'; deviceKey: string; record: TelemetryRecord }
| { type: 'presence'; deviceKey: string; lastSeen: string };

class DeviceWatcher {
private ws: WebSocket | null = null;
private readonly watched = new Set<string>();
private reconnectDelayMs = 500;
private closedByUser = false;

constructor(
private readonly url: string, // e.g. "wss://<ws-gateway-host>/ws"
private readonly onMessage: (msg: ServerMessage) => void,
) {}

connect(): void {
this.closedByUser = false;
this.ws = new WebSocket(this.url);

this.ws.onopen = () => {
this.reconnectDelayMs = 500; // reset backoff on a successful connect
// No watch state survives a reconnect server-side — re-send them all.
for (const deviceKey of this.watched) {
this.send({ type: 'watch', deviceKey });
}
};

this.ws.onmessage = (event) => {
let msg: ServerMessage;
try {
msg = JSON.parse(event.data);
} catch {
return; // ignore malformed frames rather than throw
}
this.onMessage(msg);
};

this.ws.onclose = () => {
if (this.closedByUser) return;
setTimeout(() => this.connect(), this.reconnectDelayMs);
this.reconnectDelayMs = Math.min(this.reconnectDelayMs * 2, 15_000); // exponential backoff, capped
};

this.ws.onerror = () => {
// onclose fires right after this; reconnect logic lives there.
};
}

watch(deviceKey: string): void {
this.watched.add(deviceKey);
this.send({ type: 'watch', deviceKey });
}

unwatch(deviceKey: string): void {
this.watched.delete(deviceKey);
this.send({ type: 'unwatch', deviceKey });
}

/**
* Request a device's register catalog. The server resolves which model
* that device is; there is no model form.
*
* Only call this when watch_ack reports a registersVersion you don't
* already hold — the catalog only changes when the backend is
* redeployed, so a cached copy stays valid across sessions and is worth
* persisting (localStorage/IndexedDB), keyed by the model + access +
* registersVersion the reply carries.
*
* One request may be in flight per connection: await the all_registers
* reply before asking for another device's catalog.
*/
getRegisters(deviceKey: string): void {
this.send({ type: 'get_registers', deviceKey });
}

close(): void {
this.closedByUser = true;
this.ws?.close();
}

private send(payload: Record<string, unknown>): void {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(payload));
}
// If not open yet, `onopen` re-sends everything in `watched` anyway.
}
}

// Usage:
const watcher = new DeviceWatcher('wss://<ws-gateway-host>/ws', (msg) => {
if (msg.type === 'watch_ack' && !msg.ok) {
console.warn('watch refused', msg.deviceKey, msg.code, msg.error);
} else if (msg.type === 'telemetry') {
console.log('telemetry', msg.deviceKey, msg.record.readings);
} else if (msg.type === 'presence') {
console.log('presence', msg.deviceKey, msg.lastSeen);
}
});
watcher.connect();
// The device's deviceKey: the UUID from register_result or get_devices.
// A logger id (the QR label) is refused; it changes when the logger is swapped.
watcher.watch('7c9e6679-7425-40de-944b-e07fc1f90ae7');