mqtt_basic.ino 1.9 KB

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