Advertisement
rousveiga

MQTT reconnect fail MWE

Jun 25th, 2021
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #include "M5StickCPlus.h"
  2. #include <WiFi.h>
  3. #include "AsyncMqttClient.h"
  4.  
  5. #define SSID "mywifi"
  6. #define WIFI_PASS "mypass"
  7. #define HOST "192.168.0.166"
  8. #define CLIENT_ID "test"
  9. #define PORT 1883
  10. #define USER "mosquitto"
  11. #define MQTT_PASS "mosquitto"
  12.  
  13. bool mqtt_connect_retry = true;
  14. unsigned int counter = 0;
  15. AsyncMqttClient mqtt_client;
  16.  
  17. void mqtt_disconnect_callback(AsyncMqttClientDisconnectReason reason) {
  18.   Serial.printf("%s: disconnected, reason = %hu\r\n", __func__, (uint8_t) reason);
  19.   mqtt_connect_retry = true;
  20. }
  21.  
  22. void setup() {
  23.     M5.begin(false, true, true);
  24.     Serial.begin(115200);
  25.     WiFi.begin(SSID, WIFI_PASS);
  26.     delay(10000);
  27.  
  28.     IPAddress host_ip;
  29.     host_ip.fromString(HOST);
  30.  
  31.     mqtt_client.setServer(host_ip, PORT);
  32.     mqtt_client.setClientId(CLIENT_ID);
  33.     mqtt_client.setCredentials(USER, MQTT_PASS);
  34.  
  35.     mqtt_client.setCleanSession(false);
  36.  
  37.     mqtt_client.onDisconnect(mqtt_disconnect_callback);
  38.     mqtt_client.setKeepAlive(900);
  39. }
  40.  
  41. void loop() {
  42.  
  43.     int status = WiFi.status();
  44.     if (status == WL_CONNECTED) {
  45.         Serial.printf("%s: wifi connected\r\n", __func__);
  46.  
  47.         if (mqtt_client.connected()) {
  48.             Serial.printf("%s: mqtt connected\r\n", __func__);
  49.  
  50.             mqtt_client.publish("test/testA", 0, true, "test 1");
  51.             mqtt_client.publish("test/testB", 0, true, "test 2");
  52.             mqtt_client.publish("test/testC", 0, true, "test 3");
  53.  
  54.         } else if (mqtt_connect_retry) {
  55.             Serial.printf("%s: mqtt disconnected, reconnecting\r\n", __func__);
  56.             mqtt_client.connect();
  57.             mqtt_connect_retry = false;
  58.         } else {
  59.             Serial.printf("%s: reconnecting mqtt\r\n", __func__);
  60.         }
  61.  
  62.     } else if (status == WL_DISCONNECTED || status == WL_CONNECT_FAILED || status == WL_CONNECTION_LOST ) {
  63.         Serial.printf("%s: wifi disconnected, reconnecting\r\n", __func__);
  64.         WiFi.reconnect();
  65.  
  66.     } else {
  67.         Serial.printf("%s: stalling\r\n", __func__);
  68.     }
  69.  
  70.     delay(1000);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement