mqtt_reconnect_nonblocking.ino 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Reconnecting MQTT example - non-blocking
  3. This sketch demonstrates how to keep the client connected
  4. using a non-blocking reconnect function. If the client loses
  5. its connection, it attempts to reconnect every 5 seconds
  6. without blocking the main loop.
  7. */
  8. #include <SPI.h>
  9. #include <Ethernet.h>
  10. #include <PubSubClient.h>
  11. // Update these with values suitable for your hardware/network.
  12. byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
  13. IPAddress ip(172, 16, 0, 100);
  14. IPAddress server(172, 16, 0, 2);
  15. void callback(char* topic, byte* payload, unsigned int length) {
  16. // handle message arrived
  17. }
  18. EthernetClient ethClient;
  19. PubSubClient client(ethClient);
  20. long lastReconnectAttempt = 0;
  21. boolean reconnect() {
  22. if (client.connect("arduinoClient")) {
  23. // Once connected, publish an announcement...
  24. client.publish("outTopic","hello world");
  25. // ... and resubscribe
  26. client.subscribe("inTopic");
  27. }
  28. return client.connected();
  29. }
  30. void setup()
  31. {
  32. client.setServer(server, 1883);
  33. client.setCallback(callback);
  34. Ethernet.begin(mac, ip);
  35. delay(1500);
  36. lastReconnectAttempt = 0;
  37. }
  38. void loop()
  39. {
  40. if (!client.connected()) {
  41. long now = millis();
  42. if (now - lastReconnectAttempt > 5000) {
  43. lastReconnectAttempt = now;
  44. // Attempt to reconnect
  45. if (reconnect()) {
  46. lastReconnectAttempt = 0;
  47. }
  48. }
  49. } else {
  50. // Client connected
  51. client.loop();
  52. }
  53. }