AsyncMqttClient Documentation

repository·develop·Indexed 21 days ago

https://github.com/marvinroger/async-mqtt-client

An asynchronous MQTT client library optimized for ESP8266 and ESP32 microcontrollers using the Arduino framework. It is fully compliant with MQTT version 3.1.1 and supports QoS 0, 1, and 2, as well as SSL/TLS encrypted communications. Built on top of ESPAsyncTCP (ESP8266) or AsyncTCP (ESP32), it provides a non-blocking execution model for improved performance in embedded environments.

Tokens
3.7K
Snippets
12
Records
18
Agent score
72%

What's inside AsyncMqttClient

  1. Overview of AsyncMqttClient features

    develop

    AsyncMqttClient is an asynchronous MQTT client implementation designed for ESP8266 and ESP32 microcontrollers. It is built on top of ESPAsyncTCP (for ESP8266) or AsyncTCP (for ESP32).

    Key capabilities include:

    • Protocol Compliance: Fully compliant with MQTT version 3.1.1.
    • Asynchronous Operation: Non-blocking execution for better performance in embedded environments.
    • Quality of Service (QoS): Supports QoS 0, 1, and 2 for both subscribe and publish operations.
    • Security: Supports SSL/TLS for encrypted communications.
  2. Handle large incoming messages via onMessage callbacks

    develop

    The library does not buffer incoming data; instead, it passes data directly from the TCP layer to your onMessage callback.

    Because of TCP constraints, large payloads (e.g., OTA updates) are delivered in chunks. A single call to onMessage typically handles about 1460 bytes. To reconstruct a large message, you must use the len, index, and total parameters provided in the callback to track the progress of the incoming data.

    Warning: The library reuses the same topic buffer for subsequent calls. If you modify the topic buffer within your onMessage callback, those changes will persist in the next callback invocation.

  3. Configure and use SSL with limitations

    develop

    To use SSL, you must enable the build flag -DASYNC_TCP_SSL_ENABLED=1.

    Security and Compatibility Requirements:

    • Server Validation: SSL only supports fingerprints for server validation. You must specify one or more acceptable server fingerprints to prevent man-in-the-middle attacks.
    • Supported Signature Algorithms: Only SHA1, SHA224, SHA256, and MD5 are supported. Using SHA384 or SHA512 will cause the device to crash.
    • Protocol Version: TLS 1.2 is not supported.
    -DASYNC_TCP_SSL_ENABLED=1
  4. Handle failed outgoing message publishing

    develop

    When calling the publish method, the library returns a packet ID if the message was successfully queued. If there is insufficient free memory (based on the MQTT_MIN_FREE_MEMORY setting), the method returns 0.

    It is the developer's responsibility to check the return value of publish and retry sending the packet if 0 is returned.

    // Example pattern for handling publish failures
    uint16_t packetId = client.publish(topic, payload, len);
    if (packetId == 0) {
        // Handle failure: retry later or log error
    }
  5. Install AsyncMqttClient in the Arduino IDE

    develop

    To install AsyncMqttClient in the Arduino IDE, download the latest release .zip file from the GitHub releases page and use the following steps in the IDE:

    1. Go to Sketch
    2. Select Include Library
    3. Select Add .ZIP Library...
    4. Choose the downloaded .zip file.

    Required Dependencies

    You must also install one of the following dependencies depending on your hardware:

    • For ESP8266: Install ESPAsyncTCP using the same .zip method.
    • For ESP32: Install AsyncTCP using the same .zip method.
    Sketch → Include Library → Add .ZIP Library
  6. Install AsyncMqttClient via PlatformIO

    develop

    You can install the library directly through the PlatformIO registry. This is the recommended method for managing the dependency in your PlatformIO projects.

    Available in the PlatformIO registry: http://platformio.org/lib/show/346/AsyncMqttClient
  7. Configure minimum free memory for outgoing messages

    develop

    The AsyncMqttClient uses a queue to buffer outgoing messages. To prevent memory exhaustion, the library checks for a minimum amount of free memory before queuing a packet. By default, this threshold is set to 4096 bytes.

    You can adjust this threshold by defining the MQTT_MIN_FREE_MEMORY constant to your desired value in your configuration/build settings.

    // Example: Setting a custom minimum free memory threshold
    #define MQTT_MIN_FREE_MEMORY 2048
  8. Format incoming MQTT message payloads for printing

    develop

    Incoming MQTT message payloads contain raw data and are not null-terminated C-strings. Because Arduino's Serial.print() functions expect a C-string, attempting to print the payload directly will fail or result in unexpected behavior.

    To correctly print the payload, you must iterate through the payload byte by byte using its length.

    for (size_t i = 0; i < len; ++i) {
        Serial.print(payload[i]);
    }
  9. Understand MQTT QoS retransmission limitations

    develop

    The library is spec-compliant with one major exception regarding power loss: it does not persist the state of unconfirmed messages in non-volatile memory.

    In the event of a power failure, the following will not be honored (retransmission will not occur upon restart):

    • All messages in a QoS 1 or 2 flow that have not been confirmed by the broker.
    • All received QoS 2 messages that have not yet been confirmed to the broker.

    This behavior aligns with point 4.1.1 of the MQTT specification v3.1.1.

  10. Handle AsyncMqttClient events

    develop

    Register callback functions to respond to MQTT lifecycle events and network changes using the on<Event> methods. These callbacks allow you to implement asynchronous logic such as subscribing to topics only after a successful connection.

    Available Event Handlers

    • onConnect(callback): Triggered when the client successfully connects to the broker.
    • onDisconnect(callback): Triggered when the client disconnects.
    • onSubscribe(callback): Triggered when a subscription is acknowledged.
    • onUnsubscribe(callback): Triggered when an unsubscription is acknowledged.
    • onPublish(callback): Triggered when a publish request is acknowledged.
    • onMessage(callback): Triggered when a message is received on a subscribed topic.
    client.onConnect([](AsyncMqttClient* client) {
        Serial.println("Connected!");
        client->subscribe("sensors/temp", 1);
    });
    
    client.onMessage([](AsyncMqttClient* client, const char* topic, const char* payload) {
        Serial.printf("Message arrived on %s: %s\n", topic, payload);
    });