arduino-libraries / ArduinoMqttClient

ArduinoMqttClient Library for Arduino
GNU Lesser General Public License v2.1
187 stars 73 forks source link

makes some attempts to minimize the delay for reconnection, just a hobby #49

Closed vladi4ko closed 3 years ago

vladi4ko commented 3 years ago
#ifndef MyMqtt_h
#define MyMqtt_h
#include <Arduino.h>

#include <ArduinoMqttClient.h>

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "xxx.xxx.xxx.xxx";
int port = 1883;

char* topics(const char* topic) {
  static char buffer[50];
  snprintf(buffer, sizeof(buffer), "/%s/%s", mqttid, topic);
  return buffer;
}

void topics_subscribe() {
  mqttClient.subscribe(topics("info/command"));
  // topics can be unsubscribed using:
  // mqttClient.unsubscribe(topic);
}

void onMqttMessage(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.print("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");

  // use the Stream interface to print the contents
  while (mqttClient.available()) {
    Serial.print((char)mqttClient.read());
  }
  Serial.println();

  Serial.println();
}

void setup_mqtt() {
  //#if TX_PAYLOAD_BUFFER_SIZE  < 512  // If the max message size is too small, throw an error at compile time. See MqttClient.cpp line 35
  //#error "TX_PAYLOAD_BUFFER_SIZE  is too small in libraries/ArduinoMqttClient/src/MqttClient.cpp at line 35, increase it to 512"
  //#endif

  // You can provide a unique client ID, if not set the library uses Arduino-millis()
  // Each client must have a unique client ID
  // mqttClient.setId("clientId");
  mqttClient.setId(clientid);

  // You can provide a username and password for authentication
  mqttClient.setUsernamePassword("xxxxxxxxxx", "xxxxxxxxx");

  if (WiFi.isConnected()) {
    Serial.print("Attempting to connect to the MQTT broker: ");
    Serial.println(broker);
    if (!mqttClient.connect(broker, port)) {
      Serial.print("MQTT connection failed! Error code = ");
      Serial.println(mqttClient.connectError());
    } else {
      Serial.println("Client connected!");
      topics_subscribe();
    }
    mqttClient.onMessage(onMqttMessage);
  }

}
#include <ESP8266Ping.h>
const IPAddress remote_ip(xxx, xxx, xxx, xxx);
#include <ESP8266HTTPClient.h>
HTTPClient http;
int attemptReconnect() {
  int connected;
  if (Ping.ping(remote_ip, 1)) {
    if (D)Serial.println("Success!!");
    http.setReuse(true);
    WiFiClient client;
    http.begin(client, "xxx.xxx.xxx.xxx", 1883);
    int httpCode = http.GET();
    if (D)Serial.printf("[HTTP] GET... code: %s\n", http.errorToString(httpCode).c_str());
    if (D)Serial.printf("[HTTP] GET... code: %d\n", httpCode);
    if (httpCode ==  -5) {
      connected = -5;
    } else {
      connected = 0;
    }
    http.end();
  } else {
    connected = 0;
    if (D)Serial.println("Error :(");
  }

  if (connected == -5) {
    if (!mqttClient.connect(broker, port)) {
      if (D)Serial.print("MQTT connection failed! Error code = ");
      if (D)Serial.println(mqttClient.connectError());
    }
    return mqttClient.connectError();
  } else {
    return -2;
  }
}
int xxx = 1000;
void loop_mqtt() {
  if (!mqttClient.connected()) { // if the client has been disconnected,
    //Serial.println("Client disconnected, attempting reconnection");
    BWoD(xxx) {
      if (xxx < 600000) {
        xxx = xxx * 1.5;
      } else {
        xxx = 1000;
      }
      Serial.printf("------------- %d -------------\n", xxx);
      if (!attemptReconnect()) { // try reconnecting
        mqttreconnect++;
        xxx = 1000;
        if (D)Serial.print("Client reconnected!");
        if (D)Serial.println();
        topics_subscribe();
      }
    }
  } else {
    mqttClient.poll();
  }

  BWoD(1000) {
    if (mqttClient.connected()) {
      if (D) {
        Serial.print("Sending message to topic: ");
        Serial.println(topics("info"));
        Serial.println(info_topic());
      }
      // send message, the Print interface can be used to set the message contents
      mqttClient.beginMessage(topics("info"));
      mqttClient.print(info_topic());
      mqttClient.endMessage();
      if (D)Serial.println();

      if (D) {
        Serial.print("Sending message to topic: ");
        Serial.println(topics("data"));
        Serial.println(data_topic());
      }
      // send message, the Print interface can be used to set the message contents
      mqttClient.beginMessage(topics("data"));
      mqttClient.print(data_topic());
      mqttClient.endMessage();
      if (D)Serial.println();
    }
  }
}

#endif
aentinger commented 3 years ago

Thank you? Not sure what you want me to do with it though.

vladi4ko commented 3 years ago

Unfortunately I thought the problem was from mqtt and wifi. In a few hours I had a hardware and software watchdog. The problem turned out to be in DHT22. ArduinoMqttClient is working normally. Sorry for the offtopic if possible delete it.

aentinger commented 3 years ago

Roger that :wink: Thank you for the clarification.