256dpi / arduino-mqtt

MQTT library for Arduino
MIT License
1.01k stars 232 forks source link

ESP32 connect issue? #174

Closed rokrodic closed 3 years ago

rokrodic commented 4 years ago

Hi. I use the code below and have one problem. At random time I get stuck at the point of connecting to MQTT server. Hard reset starts the ESP32 with functional mqtt. Serial output:

incoming: /Camabptoled - 1
1005 MQTT wifi OK -> .................................................................. with indefinite dots...

Code:

char MQTTinPIR2LED[] = "/Cam00ptoled";
char* MQTTName = "Camab";
WiFiClient espClient;
MQTTClient Mclient(256);
IPAddress MQTTserver(192, 168, 2, 44);

void MQTTcallback(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);
}
void MQTTconnect() {
  //Mclient.disconnect(); // <--- If we get here, we are already disconnected.
  Serial.print(millis()/1000);
  Serial.print(" MQTT wifi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(200);
  }
  Serial.print(" OK -> ");
  while (!Mclient.connect(MQTTName)) {
    Serial.print(".");
    delay(10);
  }
  Serial.println("OK!");
  Mclient.subscribe(MQTTinPIR2LED);
}
void setup() {
  String str = MQTTserver.toString();
  Mclient.begin(str.c_str(), 1883, espClient);
  Mclient.onMessage(MQTTcallback); //Mclient.onMessageAdvanced(MQTTcallback);
  Mclient.setOptions(10, true, 1000);
  MQTTpublishS(MQTTinReset, "0");
  MQTTconnect();
  MQTTPublishSlow();
...
}
void loop() {
  ul_now = millis();
  Mclient.loop();
  //delay(50);
  server.handleClient();
  if (!Mclient.connected()) {
    MQTTconnect();
  }
  MQTTsend();
}

Any idea? I have checked the net for solution but no luck.

rokrodic commented 4 years ago

I have tested the code below. It makes a software reset and mqtt works afterwards. It is not a solution, but more a test. I suppose there is not a stack problem as errors happen at random time. The only variable is the mqtt server serves other clients as well. Timing? Changing timeout makes no difference.

  unsigned long qwe = 0;
  while (!Mclient.connect(MQTTName)) {
    Serial.print(".");
    qwe++;
    delay(50);
    if (qwe > 50) resetModule();
  }
256dpi commented 3 years ago

Closing as outdated. Please reopen if problem persists.