mqtt_large_message.ino 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. /*
  2. Long message ESP8266 MQTT example
  3. This sketch demonstrates sending arbitrarily large messages in combination
  4. with the ESP8266 board/library.
  5. It connects to an MQTT server then:
  6. - publishes "hello world" to the topic "outTopic"
  7. - subscribes to the topic "greenBottles/#", printing out any messages
  8. it receives. NB - it assumes the received payloads are strings not binary
  9. - If the sub-topic is a number, it publishes a "greenBottles/lyrics" message
  10. with a payload consisting of the lyrics to "10 green bottles", replacing
  11. 10 with the number given in the sub-topic.
  12. It will reconnect to the server if the connection is lost using a blocking
  13. reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
  14. achieve the same result without blocking the main loop.
  15. To install the ESP8266 board, (using Arduino 1.6.4+):
  16. - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
  17. http://arduino.esp8266.com/stable/package_esp8266com_index.json
  18. - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  19. - Select your ESP8266 in "Tools -> Board"
  20. */
  21. #include <ESP8266WiFi.h>
  22. #include <PubSubClient.h>
  23. // Update these with values suitable for your network.
  24. const char* ssid = "........";
  25. const char* password = "........";
  26. const char* mqtt_server = "broker.mqtt-dashboard.com";
  27. WiFiClient espClient;
  28. PubSubClient client(espClient);
  29. long lastMsg = 0;
  30. char msg[50];
  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.begin(ssid, password);
  39. while (WiFi.status() != WL_CONNECTED) {
  40. delay(500);
  41. Serial.print(".");
  42. }
  43. randomSeed(micros());
  44. Serial.println("");
  45. Serial.println("WiFi connected");
  46. Serial.println("IP address: ");
  47. Serial.println(WiFi.localIP());
  48. }
  49. void callback(char* topic, byte* payload, unsigned int length) {
  50. Serial.print("Message arrived [");
  51. Serial.print(topic);
  52. Serial.print("] ");
  53. for (int i = 0; i < length; i++) {
  54. Serial.print((char)payload[i]);
  55. }
  56. Serial.println();
  57. // Find out how many bottles we should generate lyrics for
  58. String topicStr(topic);
  59. int bottleCount = 0; // assume no bottles unless we correctly parse a value from the topic
  60. if (topicStr.indexOf('/') >= 0) {
  61. // The topic includes a '/', we'll try to read the number of bottles from just after that
  62. topicStr.remove(0, topicStr.indexOf('/')+1);
  63. // Now see if there's a number of bottles after the '/'
  64. bottleCount = topicStr.toInt();
  65. }
  66. if (bottleCount > 0) {
  67. // Work out how big our resulting message will be
  68. int msgLen = 0;
  69. for (int i = bottleCount; i > 0; i--) {
  70. String numBottles(i);
  71. msgLen += 2*numBottles.length();
  72. if (i == 1) {
  73. msgLen += 2*String(" green bottle, standing on the wall\n").length();
  74. } else {
  75. msgLen += 2*String(" green bottles, standing on the wall\n").length();
  76. }
  77. msgLen += String("And if one green bottle should accidentally fall\nThere'll be ").length();
  78. switch (i) {
  79. case 1:
  80. msgLen += String("no green bottles, standing on the wall\n\n").length();
  81. break;
  82. case 2:
  83. msgLen += String("1 green bottle, standing on the wall\n\n").length();
  84. break;
  85. default:
  86. numBottles = i-1;
  87. msgLen += numBottles.length();
  88. msgLen += String(" green bottles, standing on the wall\n\n").length();
  89. break;
  90. };
  91. }
  92. // Now we can start to publish the message
  93. client.beginPublish("greenBottles/lyrics", msgLen, false);
  94. for (int i = bottleCount; i > 0; i--) {
  95. for (int j = 0; j < 2; j++) {
  96. client.print(i);
  97. if (i == 1) {
  98. client.print(" green bottle, standing on the wall\n");
  99. } else {
  100. client.print(" green bottles, standing on the wall\n");
  101. }
  102. }
  103. client.print("And if one green bottle should accidentally fall\nThere'll be ");
  104. switch (i) {
  105. case 1:
  106. client.print("no green bottles, standing on the wall\n\n");
  107. break;
  108. case 2:
  109. client.print("1 green bottle, standing on the wall\n\n");
  110. break;
  111. default:
  112. client.print(i-1);
  113. client.print(" green bottles, standing on the wall\n\n");
  114. break;
  115. };
  116. }
  117. // Now we're done!
  118. client.endPublish();
  119. }
  120. }
  121. void reconnect() {
  122. // Loop until we're reconnected
  123. while (!client.connected()) {
  124. Serial.print("Attempting MQTT connection...");
  125. // Create a random client ID
  126. String clientId = "ESP8266Client-";
  127. clientId += String(random(0xffff), HEX);
  128. // Attempt to connect
  129. if (client.connect(clientId.c_str())) {
  130. Serial.println("connected");
  131. // Once connected, publish an announcement...
  132. client.publish("outTopic", "hello world");
  133. // ... and resubscribe
  134. client.subscribe("greenBottles/#");
  135. } else {
  136. Serial.print("failed, rc=");
  137. Serial.print(client.state());
  138. Serial.println(" try again in 5 seconds");
  139. // Wait 5 seconds before retrying
  140. delay(5000);
  141. }
  142. }
  143. }
  144. void setup() {
  145. pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
  146. Serial.begin(115200);
  147. setup_wifi();
  148. client.setServer(mqtt_server, 1883);
  149. client.setCallback(callback);
  150. }
  151. void loop() {
  152. if (!client.connected()) {
  153. reconnect();
  154. }
  155. client.loop();
  156. }