Flutter (Dart)
Using web_socket_channel
(the standard Flutter WebSocket package — add it via
flutter pub add web_socket_channel). Same reconnect + re-watch shape as
the web client above.
import 'dart:async';
import 'dart:convert';
import 'package:web_socket_channel/web_socket_channel.dart';
class DeviceWatcher {
final String url; // e.g. "wss://<ws-gateway-host>/ws"
final void Function(Map<String, dynamic> message) onMessage;
WebSocketChannel? _channel;
final Set<String> _watched = {};
Duration _reconnectDelay = const Duration(milliseconds: 500);
bool _closedByUser = false;
DeviceWatcher(this.url, this.onMessage);
void connect() {
_closedByUser = false;
final channel = WebSocketChannel.connect(Uri.parse(url));
_channel = channel;
// No watch state survives a reconnect server-side — re-send them all.
for (final deviceKey in _watched) {
_send(channel, {'type': 'watch', 'deviceKey': deviceKey});
}
_reconnectDelay = const Duration(milliseconds: 500); // reset backoff
channel.stream.listen(
(raw) {
try {
final msg = jsonDecode(raw as String) as Map<String, dynamic>;
onMessage(msg);
} catch (_) {
// ignore malformed frames rather than throw
}
},
onDone: () => _scheduleReconnect(),
onError: (_) => _scheduleReconnect(),
cancelOnError: true,
);
}
void _scheduleReconnect() {
if (_closedByUser) return;
Future.delayed(_reconnectDelay, connect);
final nextMs = (_reconnectDelay.inMilliseconds * 2).clamp(500, 15000);
_reconnectDelay = Duration(milliseconds: nextMs);
}
void watch(String deviceKey) {
_watched.add(deviceKey);
final channel = _channel;
if (channel != null) _send(channel, {'type': 'watch', 'deviceKey': deviceKey});
}
void unwatch(String deviceKey) {
_watched.remove(deviceKey);
final channel = _channel;
if (channel != null) _send(channel, {'type': 'unwatch', 'deviceKey': 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 cache it on disk (keyed by the model + access +
/// registersVersion the reply carries) and reuse it across sessions.
/// One request may be in flight per connection: await the all_registers
/// reply before asking for another device's catalog.
void getRegisters(String deviceKey) {
final channel = _channel;
if (channel != null) _send(channel, {'type': 'get_registers', 'deviceKey': deviceKey});
}
void close() {
_closedByUser = true;
_channel?.sink.close();
}
void _send(WebSocketChannel channel, Map<String, dynamic> payload) {
channel.sink.add(jsonEncode(payload));
}
}
// Usage:
final watcher = DeviceWatcher('wss://<ws-gateway-host>/ws', (msg) {
switch (msg['type']) {
case 'watch_ack':
if (msg['ok'] != true) print('watch refused ${msg['deviceKey']} ${msg['code']}');
break;
case 'telemetry':
print('telemetry ${msg['deviceKey']} ${msg['record']['readings']}');
break;
case 'presence':
print('presence ${msg['deviceKey']} ${msg['lastSeen']}');
break;
}
});
watcher.connect();
watcher.watch('i30000252761006466'); // the loggerID from the QR label, lowercase