mqtt_client 5.5.4

  • Readme
  • Changelog
  • Example
  • Installing
  • 96

mqtt_client #

Build Status

A server side MQTT client for Dart.

The client is an MQTT v3(3.1 and 3.1.1) implementation supporting subscription/publishing at all QOS levels, keep alive and synchronous connection. The client is designed to take as much MQTT protocol work off the user as possible, connection protocol is handled automatically as are the message exchanges needed to support the different QOS levels and the keep alive mechanism. This allows the user to concentrate on publishing/subscribing and not the details of MQTT itself.

Examples of usage can be found in the examples directory. An example is also provided showing how to use the client to connect to the mqtt-bridge of Google's IoT-Core suite. This demonstrates how to use secure connections and switch MQTT protocols. The test directory also contains standalone runnable scripts demonstrating subscription, publishing and topic filtering.

The client supports both normal and secure TCP connections and server side secure(wss) and non-secure(ws) websocket connections.

The client has been used successfully with the MQTT brokers from several of the major cloud providers IOT/MQTT platforms, including :-

  • Google IOT Core
  • Amazon AWS
  • Microsoft Azure
  • IBM

It has also been used with a range of both publicly available brokers such as Mosquitto and proprietary ones. An example using the adafruit MQTT broker for flutter can be found here.

The code is a port from the C# nMQTT client library to Dart.

#5.5.4 Fix for dart 2.5 usage (issue 99), remove flutter example and issue 115. Note that from here on in the client is not compatible with Dart 2.4.x, if you want to stay on 2.4.x use client version 5.5.4 or lower.

#5.5.3 Issues 85 and 87

#5.5.2 Fix for dart 2.2 usage

#5.5.1 Issue 81

5.5.0 #

Issues 69, 74 and 79

5.4.0 #

Issues 67 and 68

5.3.0 #

Issues 61, 62 and 63

5.2.0 #

Issues 59 + 60

5.1.0 #

Issues 54, 55 and 56

5.0.0 #

Roll up release for issues 48, 49, 50, 52 and 53, warning - breaking API change for connection state and security context in secure mode hence the major version bump.

4.0.0 #

Issue 45, better connection fail reporting, update linter, note breaking API change for turning logging on/off

3.3.6 #

Formatting

3.3.5 #

Issue 40, disconnected clients

3.3.4 #

Formatting

3.3.3 #

Issue 26, example code for flutter

3.3.2 #

Issue 38 QOS1 + 2 protocol handling bugs, Issue 34 Flutter buffers

3.3.1 #

Issue 38 QOS1 + 2 protocol handling bugs

3.3.0 #

Issue 37 onSubscribed and OnUnsubscribed callbacks

3.2.1 #

Issues 32 bug fix

3.2.0 #

Issues 32 and 35

3.1.0 #

Issues 27 and 29, pull request 30

3.0.0 #

Update to Dart 2, major version bump only to create a clean break from Dart 1

2.0.0 #

Issue 23, all subscriptions are now on one client level observable, not on seperate ones per subscription, this change is NOT backwards compatible

1.9.1 #

Issue 22, don't disconnect if we have no connection established

1.9.0 #

Issue 19, multitopic subscriptions + other more minor updates, API changed on this version.

1.8.0 #

Pull request 14, Making library more compliant to work with VerneMQ - explicit setting of will qos.

1.7.2 #

Issue 10, add library prefix for observable

1.7.1 #

Issue 10, update Observable version to 'any'

1.7.0 #

Add the payload builder utility.

1.6.1 #

Update Observable version

1.6.0 #

Remove eventable and its dependency on mirrors, replace with event_bus, issue 10

1.5.0 #

Fixes for issue 8, pub suggestions fixed.

1.4.0 #

Fixes for issues 5 and 6

1.3.0 #

Fixes for issues 3 and 4

1.2.0 #

Add secure sockets, server side only Add ability to select the MQTT protocol between 3.1 and 3.1.1 A few code and test tidy ups Tested to work with iot-core MQTT bridge

1.1.0 #

Add websockets as an alternative network connection server side only

1.0.1 #

Fix unit tests on Travis

1.0.0 #

Initial release

example/mqtt_client.dart

/*
 * Package : mqtt_client
 * Author : S. Hamblett <steve.hamblett@linux.com>
 * Date   : 31/05/2017
 * Copyright :  S.Hamblett
 */

import 'dart:async';
import 'dart:io';
import 'package:mqtt_client/mqtt_client.dart';

/// An annotated simple subscribe/publish usage example for mqtt_client. Please read in with reference
/// to the MQTT specification. The example is runnable, also refer to test/mqtt_client_broker_test...dart
/// files for separate subscribe/publish tests.

/// First create a client, the client is constructed with a broker name, client identifier
/// and port if needed. The client identifier (short ClientId) is an identifier of each MQTT
/// client connecting to a MQTT broker. As the word identifier already suggests, it should be unique per broker.
/// The broker uses it for identifying the client and the current state of the client. If you don’t need a state
/// to be hold by the broker, in MQTT 3.1.1 you can set an empty ClientId, which results in a connection without any state.
/// A condition is that clean session connect flag is true, otherwise the connection will be rejected.
/// The client identifier can be a maximum length of 23 characters. If a port is not specified the standard port
/// of 1883 is used.
/// If you want to use websockets rather than TCP see below.
final MqttClient client = MqttClient('test.mosquitto.org', '');

Future<int> main() async {
  /// A websocket URL must start with ws:// or wss:// or Dart will throw an exception, consult your websocket MQTT broker
  /// for details.
  /// To use websockets add the following lines -:
  /// client.useWebSocket = true;
  /// client.port = 80;  ( or whatever your WS port is)
  /// There is also an alternate websocket implementation for specialist use, see useAlternateWebSocketImplementation
  /// Note do not set the secure flag if you are using wss, the secure flags is for TCP sockets only.
  /// You can also supply your own websocket protocol list or disable this feature using the websocketProtocols
  /// setter, read the API docs for further details here, the vast majority of brokers will support the client default
  /// list so in most cases you can ignore this.

  /// Set logging on if needed, defaults to off
  client.logging(on: false);

  /// If you intend to use a keep alive value in your connect message that is not the default(60s)
  /// you must set it here
  client.keepAlivePeriod = 20;

  /// Add the unsolicited disconnection callback
  client.onDisconnected = onDisconnected;

  /// Add the successful connection callback
  client.onConnected = onConnected;

  /// Add a subscribed callback, there is also an unsubscribed callback if you need it.
  /// You can add these before connection or change them dynamically after connection if
  /// you wish. There is also an onSubscribeFail callback for failed subscriptions, these
  /// can fail either because you have tried to subscribe to an invalid topic or the broker
  /// rejects the subscribe request.
  client.onSubscribed = onSubscribed;

  /// Set a ping received callback if needed, called whenever a ping response(pong) is received
  /// from the broker.
  client.pongCallback = pong;

  /// Create a connection message to use or use the default one. The default one sets the
  /// client identifier, any supplied username/password, the default keepalive interval(60s)
  /// and clean session, an example of a specific one below.
  final MqttConnectMessage connMess = MqttConnectMessage()
      .withClientIdentifier('Mqtt_MyClientUniqueId')
      .keepAliveFor(20) // Must agree with the keep alive set above or not set
      .withWillTopic('willtopic') // If you set this you must set a will message
      .withWillMessage('My Will message')
      .startClean() // Non persistent session for testing
      .withWillQos(MqttQos.atLeastOnce);
  print('EXAMPLE::Mosquitto client connecting....');
  client.connectionMessage = connMess;

  /// Connect the client, any errors here are communicated by raising of the appropriate exception. Note
  /// in some circumstances the broker will just disconnect us, see the spec about this, we however eill
  /// never send malformed messages.
  try {
    await client.connect();
  } on Exception catch (e) {
    print('EXAMPLE::client exception - $e');
    client.disconnect();
  }

  /// Check we are connected
  if (client.connectionStatus.state == MqttConnectionState.connected) {
    print('EXAMPLE::Mosquitto client connected');
  } else {
    /// Use status here rather than state if you also want the broker return code.
    print(
        'EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, status is ${client.connectionStatus}');
    client.disconnect();
    exit(-1);
  }

  /// Ok, lets try a subscription
  print('EXAMPLE::Subscribing to the test/lol topic');
  const String topic = 'test/lol'; // Not a wildcard topic
  client.subscribe(topic, MqttQos.atMostOnce);

  /// The client has a change notifier object(see the Observable class) which we then listen to to get
  /// notifications of published updates to each subscribed topic.
  client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
    final MqttPublishMessage recMess = c[0].payload;
    final String pt =
        MqttPublishPayload.bytesToStringAsString(recMess.payload.message);

    /// The above may seem a little convoluted for users only interested in the
    /// payload, some users however may be interested in the received publish message,
    /// lets not constrain ourselves yet until the package has been in the wild
    /// for a while.
    /// The payload is a byte buffer, this will be specific to the topic
    print(
        'EXAMPLE::Change notification:: topic is <${c[0].topic}>, payload is <-- $pt -->');
    print('');
  });

  /// If needed you can listen for published messages that have completed the publishing
  /// handshake which is Qos dependant. Any message received on this stream has completed its
  /// publishing handshake with the broker.
  client.published.listen((MqttPublishMessage message) {
    print(
        'EXAMPLE::Published notification:: topic is ${message.variableHeader.topicName}, with Qos ${message.header.qos}');
  });

  /// Lets publish to our topic
  /// Use the payload builder rather than a raw buffer
  /// Our known topic to publish to
  const String pubTopic = 'Dart/Mqtt_client/testtopic';
  final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
  builder.addString('Hello from mqtt_client');

  /// Subscribe to it
  print('EXAMPLE::Subscribing to the Dart/Mqtt_client/testtopic topic');
  client.subscribe(pubTopic, MqttQos.exactlyOnce);

  /// Publish it
  print('EXAMPLE::Publishing our topic');
  client.publishMessage(pubTopic, MqttQos.exactlyOnce, builder.payload);

  /// Ok, we will now sleep a while, in this gap you will see ping request/response
  /// messages being exchanged by the keep alive mechanism.
  print('EXAMPLE::Sleeping....');
  await MqttUtilities.asyncSleep(120);

  /// Finally, unsubscribe and exit gracefully
  print('EXAMPLE::Unsubscribing');
  client.unsubscribe(topic);

  /// Wait for the unsubscribe message from the broker if you wish.
  await MqttUtilities.asyncSleep(2);
  print('EXAMPLE::Disconnecting');
  client.disconnect();
  return 0;
}

/// The subscribed callback
void onSubscribed(String topic) {
  print('EXAMPLE::Subscription confirmed for topic $topic');
}

/// The unsolicited disconnect callback
void onDisconnected() {
  print('EXAMPLE::OnDisconnected client callback - Client disconnection');
  if (client.connectionStatus.returnCode == MqttConnectReturnCode.solicited) {
    print('EXAMPLE::OnDisconnected callback is solicited, this is correct');
  }
  exit(-1);
}

/// The successful connect callback
void onConnected() {
  print(
      'EXAMPLE::OnConnected client callback - Client connection was sucessful');
}

/// Pong callback
void pong() {
  print('EXAMPLE::Ping response client callback invoked');
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  mqtt_client: ^5.5.4

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter pub get

Alternatively, your editor might support pub get or flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:mqtt_client/mqtt_client.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
92
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
96
Learn more about scoring.

We analyzed this package on Oct 17, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.5.1
  • pana: 0.12.21

Platforms

Detected platforms: Flutter, other

Primary library: package:mqtt_client/mqtt_client.dart with components: io.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev <3.0.0
crypto ^2.0.6 2.1.3
event_bus ^1.0.1 1.1.0
meta ^1.0.4 1.1.7
path ^1.6.2 1.6.4
typed_data ^1.1.6 1.1.6
Transitive dependencies
charcode 1.1.2
collection 1.14.12
convert 2.1.1
Dev dependencies
coverage ^0.12.3
dart_dev ^2.0.1
dart_style ^1.1.3
mockito ^3.0.0
test ^1.3.0