Blame | Last modification | View Log | RSS feed
/*Basic MQTT exampleThis sketch demonstrates the basic capabilities of the library.It connects to an MQTT server then:- publishes "hello world" to the topic "outTopic"- subscribes to the topic "inTopic", printing out any messagesit receives. NB - it assumes the received payloads are strings not binaryIt will reconnect to the server if the connection is lost using a blockingreconnect function. See the 'mqtt_reconnect_nonblocking' example for how toachieve 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 };IPAddress ip(172, 16, 0, 100);IPAddress server(172, 16, 0, 2);void callback(char* topic, byte* payload, unsigned int length) {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;PubSubClient client(ethClient);void reconnect() {// Loop until we're reconnectedwhile (!client.connected()) {Serial.print("Attempting MQTT connection...");// Attempt to connectif (client.connect("arduinoClient")) {Serial.println("connected");// Once connected, publish an announcement...client.publish("outTopic","hello world");// ... and resubscribeclient.subscribe("inTopic");} else {Serial.print("failed, rc=");Serial.print(client.state());Serial.println(" try again in 5 seconds");// Wait 5 seconds before retryingdelay(5000);}}}void setup(){Serial.begin(57600);client.setServer(server, 1883);client.setCallback(callback);Ethernet.begin(mac, ip);// Allow the hardware to sort itself outdelay(1500);}void loop(){if (!client.connected()) {reconnect();}client.loop();}