User Tools

Site Tools


asyncmqtt

When using platformio, add this in lib_deps:

heman/AsyncMqttClient-esphome @ ^2.1.0

Create asyncmqtt.h and include it in the main source code, define the MQTT_HOST, MQTT_PORT and MQTT_TOPIC as well:

#define MQTT_HOST IPAddress(192, 168, 1, 6)
#define MQTT_PORT 1883
#define MQTT_TOPIC "iot_tank"
#include "asyncmqtt.h"

// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST "example.com"
#include <Ticker.h>
#include <AsyncMqttClient.h>

bool mqttconnected = false;
struct mqttdatastruct { 
    String message; 
    bool cleared; 
    unsigned long millis;
};

mqttdatastruct mqttdata;

AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;

void connectToMqtt() {
  mqttClient.disconnect();
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}

void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);
  mqttconnected = true;
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");
  mqttconnected = false;
  if (nodemcuwificonnected) {
    mqttReconnectTimer.once(2, connectToMqtt);
  }
}

void onMqttPublish(uint16_t packetId) {
  Serial.print("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
  Serial.print("  qos: ");
  Serial.println(qos);
}

void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  Serial.println("Publish received.");
  Serial.print("  topic: ");
  Serial.println(topic);
  Serial.print("  qos: ");
  Serial.println(properties.qos);
  Serial.print("  dup: ");
  Serial.println(properties.dup);
  Serial.print("  retain: ");
  Serial.println(properties.retain);
  Serial.print("  len: ");
  Serial.println(len);
  Serial.print("  index: ");
  Serial.println(index);
  Serial.print("  total: ");
  Serial.println(total);
  Serial.print("  payload: ");
  Serial.println(payload);
  Serial.print("  message: ");
  String strpayload;
  strpayload = String(payload);
  mqttdata.message = strpayload.substring(0,len);
  mqttdata.cleared = false;
  mqttdata.millis  = millis();
  Serial.println(mqttdata.message);
}

void initializemqtt() {
   mqttClient.onConnect(onMqttConnect);
   mqttClient.onDisconnect(onMqttDisconnect);
   mqttClient.onSubscribe(onMqttSubscribe);
   mqttClient.onUnsubscribe(onMqttUnsubscribe);
   mqttClient.onPublish(onMqttPublish);
   mqttClient.setServer(MQTT_HOST, MQTT_PORT);
   // If your broker requires authentication (username and password), set them below
   // mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
   mqttClient.onMessage(onMqttMessage);
   connectToMqtt();
}

Basically, use the publish() method on the mqttClient object to publish data on a topic. The publish() method accepts the following arguments, in order:

    MQTT topic (const char*)
    QoS (uint8_t): quality of service – it can be 0, 1 or 2
    retain flag (bool): retain flag
    payload (const char*) – in this case, the payload corresponds to the sensor reading

    sample: 
       uint16_t packetIdPub = mqttClient.publish(MQTT_TOPIC, 1, true, String(millis()).c_str());
       Serial.printf("Publishing on topic %s at QoS 1, packetId %i: ", MQTT_TOPIC, packetIdPub);

The QoS (quality of service) is a way to guarantee that the message is delivered. It can be one of the following levels:

    0: the message will be delivered once or not at all. The message is not acknowledged. There is no possibility of duplicated messages;
    1: the message will be delivered at least once, but may be delivered more than once;
    2: the message is always delivered exactly once;

Subscribing can be done:

mqttClient.subscribe(MQTT_TOPIC,1);
asyncmqtt.txt · Last modified: by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki