78 lines
1.9 KiB
Arduino
Raw Permalink Normal View History

/*
2015-08-27 14:18:16 +01:00
Basic MQTT example
2015-08-28 11:21:52 +01:00
This sketch demonstrates the basic capabilities of the library.
It connects to an MQTT server then:
- publishes "hello world" to the topic "outTopic"
2015-08-28 11:21:52 +01:00
- subscribes to the topic "inTopic", printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop.
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
2015-08-27 14:18:16 +01:00
IPAddress ip(172, 16, 0, 100);
IPAddress server(172, 16, 0, 2);
2012-03-13 18:29:43 +00:00
void callback(char* topic, byte* payload, unsigned int length) {
2015-08-28 11:21:52 +01:00
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
EthernetClient ethClient;
2015-08-28 11:21:52 +01:00
PubSubClient client(ethClient);
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic","hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
2015-08-28 11:21:52 +01:00
Serial.begin(57600);
client.setServer(server, 1883);
client.setCallback(callback);
Ethernet.begin(mac, ip);
2015-08-28 11:21:52 +01:00
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
2015-08-28 11:21:52 +01:00
if (!client.connected()) {
reconnect();
}
client.loop();
}