|
| 1 | +/* |
| 2 | + MQTT "will" message example |
| 3 | +
|
| 4 | + - connects to an MQTT server with a will message |
| 5 | + - publishes a message |
| 6 | + - waits a little bit |
| 7 | + - disconnects the socket *without* sending a disconnect packet |
| 8 | +
|
| 9 | + You should see the will message published when we disconnect |
| 10 | +*/ |
| 11 | + |
| 12 | +#include <ESP8266WiFi.h> |
| 13 | +#include <PubSubClient.h> |
| 14 | + |
| 15 | +const char *ssid = "xxxxxxxx"; // cannot be longer than 32 characters! |
| 16 | +const char *pass = "yyyyyyyy"; // |
| 17 | + |
| 18 | +// Update these with values suitable for your network. |
| 19 | +IPAddress server(172, 16, 0, 2); |
| 20 | + |
| 21 | +WiFiClient wclient; |
| 22 | +PubSubClient client(wclient, server); |
| 23 | + |
| 24 | +void setup() { |
| 25 | + // Setup console |
| 26 | + Serial.begin(115200); |
| 27 | + delay(10); |
| 28 | + Serial.println(); |
| 29 | + Serial.println(); |
| 30 | +} |
| 31 | + |
| 32 | +void loop() { |
| 33 | + delay(1000); |
| 34 | + |
| 35 | + if (WiFi.status() != WL_CONNECTED) { |
| 36 | + Serial.print("Connecting to "); |
| 37 | + Serial.print(ssid); |
| 38 | + Serial.println("..."); |
| 39 | + WiFi.begin(ssid, pass); |
| 40 | + |
| 41 | + if (WiFi.waitForConnectResult() != WL_CONNECTED) |
| 42 | + return; |
| 43 | + Serial.println("WiFi connected"); |
| 44 | + } |
| 45 | + |
| 46 | + if (WiFi.status() == WL_CONNECTED) { |
| 47 | + MQTT::Connect con("arduinoClient"); |
| 48 | + con.set_will("test", "I am down."); |
| 49 | + // Or to set a binary message: |
| 50 | + // char msg[4] = { 0xde, 0xad, 0xbe, 0xef }; |
| 51 | + // con.set_will("test", msg, 4); |
| 52 | + if (client.connect(con)) { |
| 53 | + client.publish("test", "I am up!"); |
| 54 | + delay(1000); |
| 55 | + wclient.stop(); |
| 56 | + } else |
| 57 | + Serial.println("MQTT connection failed."); |
| 58 | + |
| 59 | + delay(10000); |
| 60 | + } |
| 61 | +} |
| 62 | + |
0 commit comments