mqtt_esp8266.ino 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. /*
  2. Basic ESP8266 MQTT example
  3. This sketch demonstrates the capabilities of the pubsub library in combination
  4. with the ESP8266 board/library.
  5. It connects to an MQTT server then:
  6. - publishes "hello world" to the topic "outTopic" every two seconds
  7. - subscribes to the topic "inTopic", printing out any messages
  8. it receives. NB - it assumes the received payloads are strings not binary
  9. - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
  10. else switch it off
  11. It will reconnect to the server if the connection is lost using a blocking
  12. reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
  13. achieve the same result without blocking the main loop.
  14. To install the ESP8266 board, (using Arduino 1.6.4+):
  15. - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
  16. http://arduino.esp8266.com/stable/package_esp8266com_index.json
  17. - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  18. - Select your ESP8266 in "Tools -> Board"
  19. */
  20. #include <ESP8266WiFi.h>
  21. #include <PubSubClient.h>
  22. // Update these with values suitable for your network.
  23. const char* ssid = "........";
  24. const char* password = "........";
  25. const char* mqtt_server = "broker.mqtt-dashboard.com";
  26. WiFiClient espClient;
  27. PubSubClient client(espClient);
  28. unsigned long lastMsg = 0;
  29. #define MSG_BUFFER_SIZE (50)
  30. char msg[MSG_BUFFER_SIZE];
  31. int value = 0;
  32. void setup_wifi() {
  33. delay(10);
  34. // We start by connecting to a WiFi network
  35. Serial.println();
  36. Serial.print("Connecting to ");
  37. Serial.println(ssid);
  38. WiFi.mode(WIFI_STA);
  39. WiFi.begin(ssid, password);
  40. while (WiFi.status() != WL_CONNECTED) {
  41. delay(500);
  42. Serial.print(".");
  43. }
  44. randomSeed(micros());
  45. Serial.println("");
  46. Serial.println("WiFi connected");
  47. Serial.println("IP address: ");
  48. Serial.println(WiFi.localIP());
  49. }
  50. void callback(char* topic, byte* payload, unsigned int length) {
  51. Serial.print("Message arrived [");
  52. Serial.print(topic);
  53. Serial.print("] ");
  54. for (int i = 0; i < length; i++) {
  55. Serial.print((char)payload[i]);
  56. }
  57. Serial.println();
  58. // Switch on the LED if an 1 was received as first character
  59. if ((char)payload[0] == '1') {
  60. digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
  61. // but actually the LED is on; this is because
  62. // it is active low on the ESP-01)
  63. } else {
  64. digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
  65. }
  66. }
  67. void reconnect() {
  68. // Loop until we're reconnected
  69. while (!client.connected()) {
  70. Serial.print("Attempting MQTT connection...");
  71. // Create a random client ID
  72. String clientId = "ESP8266Client-";
  73. clientId += String(random(0xffff), HEX);
  74. // Attempt to connect
  75. if (client.connect(clientId.c_str())) {
  76. Serial.println("connected");
  77. // Once connected, publish an announcement...
  78. client.publish("outTopic", "hello world");
  79. // ... and resubscribe
  80. client.subscribe("inTopic");
  81. } else {
  82. Serial.print("failed, rc=");
  83. Serial.print(client.state());
  84. Serial.println(" try again in 5 seconds");
  85. // Wait 5 seconds before retrying
  86. delay(5000);
  87. }
  88. }
  89. }
  90. void setup() {
  91. pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
  92. Serial.begin(115200);
  93. setup_wifi();
  94. client.setServer(mqtt_server, 1883);
  95. client.setCallback(callback);
  96. }
  97. void loop() {
  98. if (!client.connected()) {
  99. reconnect();
  100. }
  101. client.loop();
  102. unsigned long now = millis();
  103. if (now - lastMsg > 2000) {
  104. lastMsg = now;
  105. ++value;
  106. snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
  107. Serial.print("Publish message: ");
  108. Serial.println(msg);
  109. client.publish("outTopic", msg);
  110. }
  111. }