knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.82k stars 1.47k forks source link

Delay in reconnect() blocks execution of other code #936

Closed mqqtpower closed 2 years ago

mqqtpower commented 2 years ago

Hi there. I have switches controlling relays (onebutton library) and when client is connected I can control relays both with MQTT and switches. When there is no connection I cannot do anything as delay in reconnect() blocks execution of other code.

void loop() {
  // keep watching the push buttons:
  button1.tick();
  button2.tick();
  button3.tick();
  button4.tick();
  button5.tick();
  button6.tick();
  button7.tick();
  button8.tick();
  button9.tick();
  button10.tick();
  button11.tick();
  button12.tick();
  button13.tick();
  button14.tick();
  button15.tick();
  button16.tick();
  button17.tick();
  button18.tick();
  button19.tick();
  button20.tick();
  button21.tick();
  button22.tick();
  button23.tick();
  button24.tick();
  button25.tick();
  button26.tick();
  button27.tick();
  button28.tick();
  button29.tick();
  button30.tick();
  button31.tick();
  button32.tick();
  button33.tick();
  button34.tick();
  button35.tick();
  button36.tick();

  // You can implement other code in here or just wait a while 
  delay(10);
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
} // end of loop
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe(sub1);
      client.subscribe(sub2);
      client.subscribe(sub3);
      client.subscribe(sub4);
      client.subscribe(sub5);
      client.subscribe(sub6);
      client.subscribe(sub7);
      client.subscribe(sub8);
      client.subscribe(sub9);
      client.subscribe(sub10);
      client.subscribe(sub11);
      client.subscribe(sub12);
      client.subscribe(sub13);
      client.subscribe(sub14);
      client.subscribe(sub15);
      client.subscribe(sub16);
      client.subscribe(refresh);
      // Publish states
      publishAll();
    } 
    else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

How to allow other code to be executed when trying to reconnect?