mqtt_client

repository·master·Indexed 20 days ago

https://github.com/shamblett/mqtt_client

A Dart implementation of the MQTT v3 (3.1 and 3.1.1) protocol for server and browser-based clients. It provides automated connection management, QoS handling, and support for TCP and WebSockets (ws/wss). The library includes features for subscription/publishing at all QoS levels, keep-alive mechanisms, and 'Will' messages, with compatibility for brokers such as Mosquitto, AWS, Azure, and Google IoT Core.

Tokens
5.9K
Snippets
24
Records
32
Agent score
70%

What's inside mqtt_client

  1. Overview of mqtt_client

    master

    The mqtt_client package is a Dart implementation of the MQTT v3 (3.1 and 3.1.1) protocol designed for server and browser environments. It automates complex MQTT protocol tasks such as connection handshakes, keep-alive mechanisms, and message exchanges required for different Quality of Service (QoS) levels, allowing developers to focus on publishing and subscribing.

    Key Features:

    • Protocol Support: MQTT v3 (3.1 and 3.1.1). For MQTT v5, use mqtt5_client instead.
    • Connection Types:
      • Server Client: Supports normal/secure TCP and secure (wss)/non-secure (ws) WebSockets.
      • Browser Client: Supports only secure (wss) and non-secure (ws) WebSockets.
    • Capabilities: Supports subscription/publishing at all QoS levels, keep-alive, and synchronous connections.
    • Compatibility: Successfully used with Google IoT Core, Amazon AWS, Microsoft Azure, IBM, Mosquitto, and others.
  2. Configure iOS permissions for mqtt_client

    master

    When using mqtt_client in a Flutter environment on iOS, you must grant permission to access the local network to discover Bonjour services. Add the following keys to your ios/Runner/Info.plist file:

    <key>NSLocalNetworkUsageDescription</key>
    <string>Looking for local tcp Bonjour service</string>
    <key>NSBonjourServices</key>
    <array>
      <string>mqtt.tcp</string>
    </array>
  3. Configure Android permissions for mqtt_client

    master

    When using mqtt_client in a Flutter environment on Android, you must ensure the application has permission to access the internet and network state. Add the following permissions to your android/app/src/main/AndroidManifest.xml file:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  4. Configure Auto Reconnect and Resubscription

    master

    The MqttClient supports automatic reconnection if autoReconnect is set to true.

    • autoReconnect: If true, the client will attempt to reconnect indefinitely after an unexpected disconnect. This mechanism is only triggered if an initial connection was successfully established.
    • resubscribeOnAutoReconnect: If true (default), the client automatically re-subscribes to all previously confirmed subscriptions during the reconnection process. If set to false, you must manually handle re-subscriptions using the provided callbacks.
    client.autoReconnect = true;
    client.resubscribeOnAutoReconnect = true;
  5. Initialize an MqttClient

    master

    To use the mqtt_client package, you must instantiate either an MqttClientServer or an MqttBrowserClient (do not instantiate MqttClient directly). The client requires a server hostname and a unique client identifier. You can also specify a custom port.

    Use the default constructor for the standard MQTT port (1883) or MqttClient.withPort to specify a different port.

    // Using default port (1883)
    final client = MqttClientServer('your.broker.hostname', 'unique_client_id');
    
    // Using a custom port
    final client = MqttClientServer.withPort('your.broker.hostname', 'unique_client_id', 1883);
  6. Configure Keep Alive and Latency monitoring

    master

    To maintain a connection and monitor health, use the Keep Alive settings:

    • keepAlivePeriod: The interval in seconds for ping requests. Set to a valid value to enable keep alive.
    • disconnectOnNoResponsePeriod: The number of seconds to wait for a ping response (pong) before forcibly disconnecting. Default is 0 (disabled).
    • pingCallback: Callback triggered when a ping request is sent.
    • pongCallback: Callback triggered when a ping response is received.
    • lastCycleLatency: Returns the latency of the last ping/pong cycle in milliseconds.
    • averageCycleLatency: Returns the average latency of all cycles in the current connection period.
  7. Configure connection timeouts

    master

    You can control how long the client waits for network operations:

    • socketTimeout: Specifies the maximum time in milliseconds to wait for a socket connection (TCP only). Setting this disables connectTimeoutPeriod.
    • connectTimeoutPeriod: Specifies the time period in milliseconds between successive connection attempts. Defaults to 5000ms. Minimum value is 1000ms.
  8. Handle MQTT connection callbacks

    master

    You can assign callback functions to handle various lifecycle events:

    • onConnected: Called on successful connection.
    • onDisconnected: Called on unsolicited disconnects (broker termination).
    • onAutoReconnect: Called before the auto-reconnect process begins.
    • onAutoReconnected: Called after the auto-reconnect process completes.
    • onFailedConnectionAttempt: Called on every failed attempt if autoReconnect is NOT set.
    • onSubscribed / onSubscribeFail: Called when subscription requests are acknowledged or fail.
    • onUnsubscribed: Called when an unsubscription is confirmed.
  9. Use MqttVariableHeader for MQTT message headers

    master

    The MqttVariableHeader class serves as the base class for the Variable Header portion of MQTT messages. It manages common fields such as protocol name, protocol version, keep alive timers, and message identifiers.

    Developers can instantiate a header using the default constructor or populate it from an existing byte stream using MqttVariableHeader.fromByteBuffer(MqttByteBuffer headerStream).

    // Initialize a new header with default protocol settings
    var header = MqttVariableHeader();
    
    // Or initialize from a byte stream
    var headerFromStream = MqttVariableHeader.fromByteBuffer(myMqttByteBuffer);
  10. Enable client logging

    master

    You can enable or disable logging for the client using the logging() method. You can also control whether the message payloads are included in the logs.

    // Enable logging with payloads
    client.logging(on: true, logPayloads: true);
    
    // Enable logging without payloads
    client.logging(on: true, logPayloads: false);
  11. Use MqttServerClient for server-side MQTT connections

    master

    The MqttServerClient class is designed for server-side MQTT implementations. It extends MqttClient and provides specialized handling for TCP and WebSocket connections, including support for custom socket options and security contexts.

    Key Configuration Options

    • secure: Set to true to use a secure TCP connection. Note: This does not support secure websockets (wss).
    • useWebSocket: Set to true to use a websocket connection instead of the default TCP one.
    • useAlternateWebSocketImplementation: If useWebSocket is true, this enables an alternate websocket implementation.
    • onBadCertificate: A callback function bool Function(X509Certificate certificate)? used to handle bad certificates. Returning true ignores the error.
    • socketOptions: A list of RawSocketOption objects (from Dart's dart:io) applied to both the initial connection and auto-reconnects. This is only applicable to TCP sockets.
    • websocketHeader: Allows specifying additional HTTP headers for the websocket connection via a Map<String, dynamic>.
    // Basic initialization with default port
    final client = MqttServerClient('your.broker.address', 'client_id');
    
    // Initialization with a specific port
    final clientWithPort = MqttServerClient.withPort('your.broker.address', 'client_id', 1883);
    
    // Connecting with authentication
    await client.connect('username', 'password');
  12. Configure Will messages in MqttConnectMessage

    master

    MQTT 'Will' messages (Last Will and Testament) allow the broker to notify other clients if the connection is unexpectedly lost. You can configure this using the following methods:

    • will(): Sets the willFlag to true.
    • withWillQos(MqttQos qos): Sets the Quality of Service for the Will message.
    • withWillRetain(): Sets the willRetain flag.
    • withWillTopic(String willTopic): Sets the topic for the Will message (automatically calls will()).
    • withWillMessage(String willMessage): Sets the payload for the Will message (automatically calls will()).
    message.withWillTopic('clients/status')
           .withWillMessage('unexpected_disconnect')
           .withWillQos(MqttQos.atLeastOnce)
           .withWillRetain();