programowanie:esp32:mqtt

MQTT na ESP32



#include "Arduino.h"
#include <WiFi.h>
#include <PubSubClient.h>
 
const String Device_ID = "11";  // ID urządzenia [String]
const String myHostname = "ssh_device_" + Device_ID;
 
String Mqtt_Server = "adres_serwera";  // MQTT broker address
int Mqtt_Port = numer_portu;  // MQTT broker port
String Mqtt_User = "nazwa_uzytkownika";  // MQTT broker username
String Mqtt_Password = "haslo";  // MQTT broker user password
// const int Mqtt_Buffer_Size = 512;  // powiększenie rozmiaru bufora publikowania
 
PubSubClient mqttClient(wifiClient);
 
void callback(char*, byte*, unsigned int);
void connectMqtt();



void setup()
{
  connectWiFi();
  connectMqtt();
}



void loop()
{
  if (WiFi.status() != WL_CONNECTED) { connectWiFi(); }
  if (!mqttClient.connected()) { connectMqtt(); }
  mqttClient.loop();
  vTaskDelay(pdMS_TO_TICKS(10));
}



void connectMqtt()
{
  digitalWrite(BUILT_LED, LOW);
  int hostnameLenght = myHostname.length() + 1;
  char myMqttName[hostnameLenght];
  myHostname.toCharArray(myMqttName, hostnameLenght);
 
  mqttClient.setServer(Mqtt_Server.c_str(), Mqtt_Port);
  mqttClient.setCallback(callback);
  // mqttClient.setBufferSize(Mqtt_Buffer_Size);  // powiększenie rozmiaru bufora publikowania
 
  while (!mqttClient.connected() and apiGetSuccess) {
    vTaskDelay(pdMS_TO_TICKS(500));
    digitalWrite(BUILT_LED, HIGH);
    Serial.println("Connecting to MQTT...");
 
    //willMessage:
    String json = "{\"device\":{\"id\":" + Device_ID 
    + ",\"name\":\"" + myHostname 
    + "\",\"type\":\"" + ESP.getChipModel() 
    + "\",\"online\":false}}";
 
    if (mqttClient.connect(myMqttName, Mqtt_User.c_str(), Mqtt_Password.c_str(), "will_message_topic", 1, true, json.c_str()))
    {
      Serial.println("Connected to MQTT");
      mqttClient.subscribe("adres_kanalu");  // subskrypcja
    } 
    else 
    {
      Serial.print("MQTT Client Failed with state ");
      Serial.println(mqttClient.state());
 
      if (WiFi.status() != WL_CONNECTED) 
      {
        Serial.println("WiFi disconnected!");
        break;
      }
      vTaskDelay(pdMS_TO_TICKS(500));
      digitalWrite(BUILT_LED, LOW);
    }
  }
  digitalWrite(BUILT_LED, HIGH);
}



void callback(char* topic, byte* payload, unsigned int length)
{
  char *token;
  const char *delimiter ="/";
  String splitTopic[4] = {};
  token = strtok(topic, delimiter);
 
  int i = 0;
  while (token != NULL) 
  {
    splitTopic[i] = token;
    i++;
    token=strtok(NULL, delimiter);
  }
 
  if (splitTopic[0] == "lvl_1" and splitTopic[1] == "lvl_2" and splitTopic[2] == "lvl_3")  // kanał odebranej wiadomości
  {
    ...    
  }
}



Proste
mqttClient.publish("topic", "message");
Sprawdzające rozmiar wiadomości
String topic = "topic");
int pub = mqttClient.publish(topic.c_str(), "message", true);
if (!pub)
{
  Serial.println("MQTT publish fail!");
  Serial.println("json size: " + String("message".length()) + " bajts");
  Serial.println("message buffor: " + String(Mqtt_Buffer_Size));
}



-4 MQTT_CONNECTION_TIMEOUT the server didn't respond within the keepalive time
-3 MQTT_CONNECTION_LOST the network connection was broken
-2 MQTT_CONNECT_FAILED the network connection failed
-1 MQTT_DISCONNECTED the client is disconnected cleanly
0 MQTT_CONNECTED the client is connected
1 MQTT_CONNECT_BAD_PROTOCOL the server doesn't support the requested version of MQTT
2 MQTT_CONNECT_BAD_CLIENT_ID the server rejected the client identifier
3 MQTT_CONNECT_UNAVAILABLE the server was unable to accept the connection
4 MQTT_CONNECT_BAD_CREDENTIALS the username/password were rejected
5 MQTT_CONNECT_UNAUTHORIZED the client was not authorized to connect
  • programowanie/esp32/mqtt.txt
  • ostatnio zmienione: 2024/09/08 18:10
  • przez sases