Skip to main content

resilient_mqtt 0.0.1 copy "resilient_mqtt: ^0.0.1" to clipboard
resilient_mqtt: ^0.0.1 copied to clipboard

A resilience layer for mqtt_client: exponential backoff with jitter, connection state as a Stream, automatic re-subscribe and typed decoders. Pure Dart.

example/main.dart

// Minimal CLI demo.
//
//   docker run --rm -p 1883:1883 \
//     -v "$PWD/tool/mosquitto:/mosquitto/config" eclipse-mosquitto:2
//   dart run example/main.dart [host] [port]
//
// Then stop/start the broker and watch the client back off and recover.
import 'dart:async';
import 'dart:io';

import 'package:resilient_mqtt/resilient_mqtt.dart';

Future<void> main(List<String> args) async {
  final host = args.isNotEmpty ? args[0] : 'localhost';
  final port = args.length > 1 ? int.parse(args[1]) : 1883;

  final client = ResilientMqttClient(
    config: MqttConfig(
      host: host,
      port: port,
      clientId: 'resilient-mqtt-example-$pid',
      keepAlive: const Duration(seconds: 10),
    ),
    reconnectPolicy: ExponentialBackoff(
      base: const Duration(seconds: 1),
      max: const Duration(seconds: 30),
    ),
  );

  client.connectionState.listen(
    (state) => stdout.writeln(switch (state) {
      Connecting() => '… connecting to $host:$port',
      Connected() => '✓ connected',
      Reconnecting(:final attempt, :final nextDelay) =>
        '↻ retry #$attempt in ${nextDelay.inMilliseconds} ms',
      Disconnected(:final reason) => '✗ disconnected (${reason.name})',
    }),
  );

  client
      .subscribeDecoded('resilient_mqtt/demo/#', const StringMqttDecoder())
      .listen((text) => stdout.writeln('← $text'));
  client.decodeErrors.listen((e) => stderr.writeln('decode error: $e'));

  // Does not throw if the broker is down: it keeps retrying in background.
  await client.connect();

  var counter = 0;
  final timer = Timer.periodic(const Duration(seconds: 2), (_) {
    if (!client.isConnected) return; // v0.2 will queue instead.
    client.publishString('resilient_mqtt/demo/tick', 'tick ${++counter}');
  });

  await ProcessSignal.sigint.watch().first;
  timer.cancel();
  await client.dispose();
  exit(0);
}
0
likes
160
points
38
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A resilience layer for mqtt_client: exponential backoff with jitter, connection state as a Stream, automatic re-subscribe and typed decoders. Pure Dart.

Repository (GitHub)
View/report issues

Topics

#mqtt #iot #reconnect #networking

License

MIT (license)

Dependencies

mqtt_client

More

Packages that depend on resilient_mqtt