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