mqtt_esp8266.ino 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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. long lastMsg = 0;
  29. char msg[50];
  30. int value = 0;
  31. void setup_wifi() {
  32. delay(10);
  33. // We start by connecting to a WiFi network
  34. Serial.println();
  35. Serial.print("Connecting to ");
  36. Serial.println(ssid);
  37. WiFi.begin(ssid, password);
  38. while (WiFi.status() != WL_CONNECTED) {
  39. delay(500);
  40. Serial.print(".");
  41. }
  42. randomSeed(micros());
  43. Serial.println("");
  44. Serial.println("WiFi connected");
  45. Serial.println("IP address: ");
  46. Serial.println(WiFi.localIP());
  47. }
  48. void callback(char* topic, byte* payload, unsigned int length) {
  49. Serial.print("Message arrived [");
  50. Serial.print(topic);
  51. Serial.print("] ");
  52. for (int i = 0; i < length; i++) {
  53. Serial.print((char)payload[i]);
  54. }
  55. Serial.println();
  56. // Switch on the LED if an 1 was received as first character
  57. if ((char)payload[0] == '1') {
  58. digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
  59. // but actually the LED is on; this is because
  60. // it is active low on the ESP-01)
  61. } else {
  62. digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
  63. }
  64. }
  65. void reconnect() {
  66. // Loop until we're reconnected
  67. while (!client.connected()) {
  68. Serial.print("Attempting MQTT connection...");
  69. // Create a random client ID
  70. String clientId = "ESP8266Client-";
  71. clientId += String(random(0xffff), HEX);
  72. // Attempt to connect
  73. if (client.connect(clientId.c_str())) {
  74. Serial.println("connected");
  75. // Once connected, publish an announcement...
  76. client.publish("outTopic", "hello world");
  77. // ... and resubscribe
  78. client.subscribe("inTopic");
  79. } else {
  80. Serial.print("failed, rc=");
  81. Serial.print(client.state());
  82. Serial.println(" try again in 5 seconds");
  83. // Wait 5 seconds before retrying
  84. delay(5000);
  85. }
  86. }
  87. }
  88. void setup() {
  89. pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
  90. Serial.begin(115200);
  91. setup_wifi();
  92. client.setServer(mqtt_server, 1883);
  93. client.setCallback(callback);
  94. }
  95. void loop() {
  96. if (!client.connected()) {
  97. reconnect();
  98. }
  99. client.loop();
  100. long now = millis();
  101. if (now - lastMsg > 2000) {
  102. lastMsg = now;
  103. ++value;
  104. snprintf (msg, 50, "hello world #%ld", value);
  105. Serial.print("Publish message: ");
  106. Serial.println(msg);
  107. client.publish("outTopic", msg);
  108. }
  109. }