| 2 |
raymond |
1 |
/*
|
|
|
2 |
Basic MQTT example
|
|
|
3 |
|
|
|
4 |
This sketch demonstrates the basic capabilities of the library.
|
|
|
5 |
It connects to an MQTT server then:
|
|
|
6 |
- publishes "hello world" to the topic "outTopic"
|
|
|
7 |
- subscribes to the topic "inTopic", printing out any messages
|
|
|
8 |
it receives. NB - it assumes the received payloads are strings not binary
|
|
|
9 |
|
|
|
10 |
It will reconnect to the server if the connection is lost using a blocking
|
|
|
11 |
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
|
|
|
12 |
achieve the same result without blocking the main loop.
|
|
|
13 |
|
|
|
14 |
*/
|
|
|
15 |
|
|
|
16 |
#include <SPI.h>
|
|
|
17 |
#include <Ethernet.h>
|
|
|
18 |
#include <PubSubClient.h>
|
|
|
19 |
|
|
|
20 |
// Update these with values suitable for your network.
|
|
|
21 |
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
|
|
|
22 |
IPAddress ip(172, 16, 0, 100);
|
|
|
23 |
IPAddress server(172, 16, 0, 2);
|
|
|
24 |
|
|
|
25 |
void callback(char* topic, byte* payload, unsigned int length) {
|
|
|
26 |
Serial.print("Message arrived [");
|
|
|
27 |
Serial.print(topic);
|
|
|
28 |
Serial.print("] ");
|
|
|
29 |
for (int i=0;i<length;i++) {
|
|
|
30 |
Serial.print((char)payload[i]);
|
|
|
31 |
}
|
|
|
32 |
Serial.println();
|
|
|
33 |
}
|
|
|
34 |
|
|
|
35 |
EthernetClient ethClient;
|
|
|
36 |
PubSubClient client(ethClient);
|
|
|
37 |
|
|
|
38 |
void reconnect() {
|
|
|
39 |
// Loop until we're reconnected
|
|
|
40 |
while (!client.connected()) {
|
|
|
41 |
Serial.print("Attempting MQTT connection...");
|
|
|
42 |
// Attempt to connect
|
|
|
43 |
if (client.connect("arduinoClient")) {
|
|
|
44 |
Serial.println("connected");
|
|
|
45 |
// Once connected, publish an announcement...
|
|
|
46 |
client.publish("outTopic","hello world");
|
|
|
47 |
// ... and resubscribe
|
|
|
48 |
client.subscribe("inTopic");
|
|
|
49 |
} else {
|
|
|
50 |
Serial.print("failed, rc=");
|
|
|
51 |
Serial.print(client.state());
|
|
|
52 |
Serial.println(" try again in 5 seconds");
|
|
|
53 |
// Wait 5 seconds before retrying
|
|
|
54 |
delay(5000);
|
|
|
55 |
}
|
|
|
56 |
}
|
|
|
57 |
}
|
|
|
58 |
|
|
|
59 |
void setup()
|
|
|
60 |
{
|
|
|
61 |
Serial.begin(57600);
|
|
|
62 |
|
|
|
63 |
client.setServer(server, 1883);
|
|
|
64 |
client.setCallback(callback);
|
|
|
65 |
|
|
|
66 |
Ethernet.begin(mac, ip);
|
|
|
67 |
// Allow the hardware to sort itself out
|
|
|
68 |
delay(1500);
|
|
|
69 |
}
|
|
|
70 |
|
|
|
71 |
void loop()
|
|
|
72 |
{
|
|
|
73 |
if (!client.connected()) {
|
|
|
74 |
reconnect();
|
|
|
75 |
}
|
|
|
76 |
client.loop();
|
|
|
77 |
}
|