mqtt_client 1.8.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 89

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.

An example of usage can be found in the examples directory, this example is runnable. 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 for subscription and publishing.

The client supports both normal and secure TCP connections and server side websocket connections.

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

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 'package:mqtt_client/mqtt_client.dart';
import 'package:observable/observable.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.
Future<int> main() async {
  /// 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 TCPO see below.
  final MqttClient client = new MqttClient("test.mosquitto.org", "");

  /// A websocket URL must start with ws:// 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)

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

  /// 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 = 30;

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

  /// 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 = new MqttConnectMessage()
      .withClientIdentifier("Mqtt_clientUniqueId")
      .keepAliveFor(30) // Must agree with the keep alive set above
      .withWillTopic("willtopic")
      .withWillQos(MqttQos.atLeastOnce);
  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();
  } catch (Exception) {
    /// Error handling.....
    client.disconnect();
  }

  /// Check we are connected
  if (client.connectionState == ConnectionState.connected) {
    print("EXAMPLE::Mosquitto client connected");
  } else {
    print(
        "EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, state is ${client
            .connectionState}");
    client.disconnect();
  }

  /// Ok, lets try a subscription
  final String topic = "test/hw";
  final ChangeNotifier<MqttReceivedMessage> cn =
  client.listenTo(topic, MqttQos.exactlyOnce);

  /// We get a change notifier object(see the Observable class) which we then listen to to get
  /// notifications of published updates to each subscribed topic, one for each topic, these are
  /// basically standard Dart streams and can be managed as you wish.
  cn.changes.listen((List<MqttReceivedMessage> c) {
    final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage;
    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:: payload is <$pt> for topic <$topic>");
  });

  /// Sleep to read the log.....
  await MqttUtilities.asyncSleep(5);

  /// Lets publish to a topic, use a high QOS
  // Publish a known topic
  final String pubTopic = "Dart/Mqtt_client/testtopic";
  // Use the payload builder rather than a raw buffer
  final MqttClientPayloadBuilder builder = new MqttClientPayloadBuilder();
  builder.addString("Hello");
  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 unsolicited disconnect callback
void onDisconnected() {
  print("Client unsolicited disconnection");
}

Use this package as a library

1. Depend on it

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


dependencies:
  mqtt_client: "^1.8.0"

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages 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';
  
Version Uploaded Documentation Archive
1.8.0 Jun 20, 2018 Go to the documentation of mqtt_client 1.8.0 Download mqtt_client 1.8.0 archive
1.7.2 May 27, 2018 Go to the documentation of mqtt_client 1.7.2 Download mqtt_client 1.7.2 archive
1.7.1 Apr 30, 2018 Go to the documentation of mqtt_client 1.7.1 Download mqtt_client 1.7.1 archive
1.7.0 Apr 20, 2018 Go to the documentation of mqtt_client 1.7.0 Download mqtt_client 1.7.0 archive
1.6.1 Apr 18, 2018 Go to the documentation of mqtt_client 1.6.1 Download mqtt_client 1.6.1 archive
1.6.0 Mar 22, 2018 Go to the documentation of mqtt_client 1.6.0 Download mqtt_client 1.6.0 archive
1.5.0 Feb 15, 2018 Go to the documentation of mqtt_client 1.5.0 Download mqtt_client 1.5.0 archive
1.4.0 Nov 21, 2017 Go to the documentation of mqtt_client 1.4.0 Download mqtt_client 1.4.0 archive
1.3.0 Nov 13, 2017 Go to the documentation of mqtt_client 1.3.0 Download mqtt_client 1.3.0 archive
1.2.0 Oct 9, 2017 Go to the documentation of mqtt_client 1.2.0 Download mqtt_client 1.2.0 archive

All 12 versions...

Analysis

We analyzed this package on Jun 20, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0-dev.63.0
  • pana: 0.11.3

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
82 / 100
Health:
Code health derived from static analysis. [more]
98 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
95 / 100
Overall score:
Weighted score of the above. [more]
89
Learn more about scoring.

Platforms

Detected platforms: Flutter, other

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

Suggestions

  • Use constrained dependencies.

    The pubspec.yaml contains 1 dependency without version constraints. Specify version ranges for the following dependencies: observable.

  • Fix analysis and formatting issues.

    Analysis or formatting checks reported 48 hints.

    Run dartfmt to format lib/mqtt_client.dart.

    Run dartfmt to format lib/src/connectionhandling/mqtt_client_connection_state.dart.

    Similar analysis of the following files failed:

    • lib/src/connectionhandling/mqtt_client_imqtt_connection_handler.dart (hint)
    • lib/src/connectionhandling/mqtt_client_mqtt_connection.dart (hint)
    • lib/src/connectionhandling/mqtt_client_mqtt_connection_handler.dart (hint)
    • lib/src/connectionhandling/mqtt_client_mqtt_connection_keep_alive.dart (hint)
    • lib/src/connectionhandling/mqtt_client_mqtt_normal_connection.dart (hint)
    • lib/src/connectionhandling/mqtt_client_synchronous_mqtt_connection_handler.dart (hint)
    • lib/src/encoding/mqtt_client_mqtt_encoding.dart (hint)
    • lib/src/exception/mqtt_client_client_identifier_exception.dart (hint)
    • lib/src/exception/mqtt_client_connection_exception.dart (hint)
    • lib/src/exception/mqtt_client_invalid_header_exception.dart (hint)
    • lib/src/exception/mqtt_client_invalid_message_exception.dart (hint)
    • lib/src/exception/mqtt_client_invalid_payload_size_exception.dart (hint)
    • lib/src/exception/mqtt_client_invalid_topic_exception.dart (hint)
    • lib/src/exception/mqtt_client_noconnection_exception.dart (hint)
    • lib/src/messages/connect/mqtt_client_mqtt_connect_flags.dart (hint)
    • lib/src/messages/connect/mqtt_client_mqtt_connect_message.dart (hint)
    • lib/src/messages/connect/mqtt_client_mqtt_connect_payload.dart (hint)
    • lib/src/messages/connectack/mqtt_client_mqtt_connect_ack_message.dart (hint)
    • lib/src/messages/mqtt_client_mqtt_header.dart (hint)
    • lib/src/messages/mqtt_client_mqtt_message.dart (hint)
    • lib/src/messages/mqtt_client_mqtt_message_factory.dart (hint)
    • lib/src/messages/publish/mqtt_client_mqtt_publish_message.dart (hint)
    • lib/src/messages/publish/mqtt_client_mqtt_publish_variable_header.dart (hint)
    • lib/src/messages/publishack/mqtt_client_mqtt_publish_ack_message.dart (hint)
    • lib/src/messages/publishcomplete/mqtt_client_mqtt_publish_complete_message.dart (hint)
    • lib/src/messages/publishreceived/mqtt_client_mqtt_publish_received_message.dart (hint)
    • lib/src/messages/publishrelease/mqtt_client_mqtt_publish_release_message.dart (hint)
    • lib/src/messages/subscribe/mqtt_client_mqtt_subscribe_message.dart (hint)
    • lib/src/messages/subscribe/mqtt_client_mqtt_subscribe_payload.dart (hint)
    • lib/src/messages/subscribeack/mqtt_client_mqtt_subscribe_ack_message.dart (hint)
    • lib/src/messages/subscribeack/mqtt_client_mqtt_subscribe_ack_payload.dart (hint)
    • lib/src/messages/unsubscribe/mqtt_client_mqtt_unsubscribe_message.dart (hint)
    • lib/src/messages/unsubscribe/mqtt_client_mqtt_unsubscribe_payload.dart (hint)
    • lib/src/messages/unsubscribeack/mqtt_client_mqtt_unsubscribe_ack_message.dart (hint)
    • lib/src/mqtt_client.dart (hint)
    • lib/src/mqtt_client_constants.dart (hint)
    • lib/src/mqtt_client_events.dart (hint)
    • lib/src/mqtt_client_ipublishing_manager.dart (hint)
    • lib/src/mqtt_client_message_identifier_dispenser.dart (hint)
    • lib/src/mqtt_client_protocol.dart (hint)
    • lib/src/mqtt_client_publication_topic.dart (hint)
    • lib/src/mqtt_client_publishing_manager.dart (hint)
    • lib/src/mqtt_client_subscription_topic.dart (hint)
    • lib/src/mqtt_client_subscriptions_manager.dart (hint)
    • lib/src/mqtt_client_topic.dart (hint)
    • lib/src/utility/mqtt_client_byte_buffer.dart (hint)

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.8.0 <2.0.0
event_bus >=0.4.0 <=1.0.0 0.4.1
observable any 0.22.1+3
path >=1.4.1 <=2.0.0 1.6.1
typed_data >=1.1.3 <=1.2.0 1.1.5
Transitive dependencies
collection 1.14.10
dart_internal 0.1.1
matcher 0.12.3
meta 1.1.5
quiver 0.29.0+1
stack_trace 1.9.2
Dev dependencies
coverage ^0.7.3
dart_dev ^1.0.0
dart_style >=0.2.0 <0.3.0
dartdoc >=0.8.0 <=0.10.0
mockito ^2.0.2
route ^0.4.6
test ^0.12.0