Соединение ESP32 MQTT: методы и примеры кода

Чтобы подключить ESP32 к MQTT (транспорт телеметрии очереди сообщений), вы можете использовать различные методы в зависимости от того, какие библиотеки и платформы вы предпочитаете. Вот несколько популярных методов с примерами кода:

Метод 1: использование библиотеки PubSubClient

#include <WiFi.h>
#include <PubSubClient.h>
// Update these with your network connection details
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Update the MQTT broker details
const char* mqttServer = "your_MQTT_broker_IP";
const int mqttPort = 1883;
const char* mqttUser = "your_MQTT_username";
const char* mqttPassword = "your_MQTT_password";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }
// Connect to MQTT Broker
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);

  while (!client.connected()) {
    if (client.connect("ESP32Client", mqttUser, mqttPassword)) {
      // Subscribe to MQTT topics or perform other actions
      client.subscribe("topic/example");
    } else {
      delay(5000);
    }
  }
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}
void callback(char* topic, byte* payload, unsigned int length) {
  // Handle MQTT message received
}
void reconnect() {
  while (!client.connected()) {
    if (client.connect("ESP32Client", mqttUser, mqttPassword)) {
      // Subscribe to MQTT topics or perform other actions
      client.subscribe("topic/example");
    } else {
      delay(5000);
    }
  }
}

Метод 2: использование библиотеки AsyncMqttClient

#include <WiFi.h>
#include <AsyncMqttClient.h>
// Update these with your network connection details
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Update the MQTT broker details
const char* mqttServer = "your_MQTT_broker_IP";
const int mqttPort = 1883;
const char* mqttUser = "your_MQTT_username";
const char* mqttPassword = "your_MQTT_password";
WiFiClient espClient;
AsyncMqttClient mqttClient;
void setup() {
  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }
// Connect to MQTT Broker
  mqttClient.setServer(mqttServer, mqttPort);
  mqttClient.setCredentials(mqttUser, mqttPassword);
  mqttClient.connect();
}
void loop() {
  // Handle MQTT connection and events
}
void onMqttConnect(bool sessionPresent) {
  // Subscribe to MQTT topics or perform other actions
  mqttClient.subscribe("topic/example");
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  // Handle MQTT disconnection
}
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  // Handle MQTT message received
}

В этих примерах демонстрируются две популярные библиотеки MQTT для ESP32: PubSubClient и AsyncMqttClient. Вам необходимо заменить значения-заполнители (например, SSID, пароль, сведения о брокере MQTT) фактической информацией о вашей сети и брокере MQTT.