2022/04/23

Android #34 用一塊ESP32來學IOT - Android手機也能通 (Learn IOT with an ESP32 / remote control w/ MQTTDash)

Android #34 用一塊ESP32來學IOT - Android手機也能通 Learn IOT with an ESP32 / remote control w/ MQTTDash

** ENGLISH closed captions is now available for this video ** Learn IOT with an ESP32 / remote control w/ MQTTDash APP

Video timeline:

00:58 Download MQTTDash App 01:29 Create an MQTT connection 03:20 Dashboard Design 04:17 Review subscriptions on MQTTLens 05:15 Enter subscription topics in MQTTDash 10:30 See the Demo on the phone 12:39 Modify ESP32 code accordingly 大家好, 歡迎收看本週的Weekend project with Stonez56。 本周是Android 第34集,"用一塊ESP32來學IOT - Android 手機也能通”。這個是一個專門為初學者來開發的一個系列。 繼上集之後, 有網友反應無法在手機上用 MQTTlens. 所以我們今天要把只能在電腦上使用的 MQTTLens 改成 MQTTDash 這支Android APP. 這樣子, 只要帶著手機, 我們就可真正隨時隨地的遠端控制IOT設備了~ 那我們就一起來學習吧。 Android MQTTDash App: https://play.google.com/store/apps/details?id=net.routix.mqttdash&hl=zh_TW&gl=US&showAllReviews=true 尚未看過這系列的朋友, 建議從這裡依序學習: * 用一塊ESP32來學 IOT https://youtu.be/rjPU4YZG338 * 溫溼度篇 https://youtu.be/x3k_dZXua1I * Android App 也能通 https://youtu.be/0IjQOxD2j48 如果時間不夠的朋友, 也可以從以下的時間軸挑選想看的部份即可! 影片時間軸: 00:00 開始 00:58 下載 MQTTDash APP 01:29 建立 EMQX MQTT 連線 03:20 儀表板設計 04:17 查看之前 MQTTLens 上的訂閱/發佈主題 05:15 在 MQTTDash 中加入訂閱/發佈主題 10:30 看實際手機+ESP32 展示 12:39 如何修改 ESP32 相應代碼

Source code:

  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.  
  21. #include <WiFi.h>
  22. #include <PubSubClient.h>
  23. #include <EasyButton.h>
  24. #define LED 2 //built-in LED on ESP32
  25.  
  26. #include "DHT.h"
  27. #define DHTPIN 23 // Digital pin connected to the DHT sensor
  28. #define DHTTYPE DHT11 // DHT11
  29. DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.
  30. // Set up the temp / humidity update cycle
  31. const int updateCycle = 5000;
  32.  
  33. // Update these with values suitable for your network.
  34. const char *ssid = "Wi-Fi SSID";
  35. const char *password = "Wi-Fi Password";
  36.  
  37. // Define your client ID on EMQX
  38. String mqtt_ClientID = "stonez56_IOT_Station_";
  39.  
  40. // Define your topics to subscribe / publish
  41. const char* sub_topic = "stonez56/esp32s";
  42. const char* pub_led_topic = "stonez56/esp32s_led_state";
  43. const char* pub_init_topic = "stonez56/esp32s_is_back";
  44. const char* pub_temp_topic = "stonez56/esp32s_temp";
  45. const char* pub_humd_topic = "stonez56/esp32s_humd";
  46.  
  47. // EMQX broker parameters
  48. const char *mqtt_server = "broker.emqx.io";
  49. const char *mqtt_userName = "emqx";
  50. const char *mqtt_password = "public";
  51.  
  52. WiFiClient espClient;
  53. PubSubClient client(espClient);
  54. unsigned long lastMsg = 0;
  55. #define MSG_BUFFER_SIZE (50)
  56. char msg[MSG_BUFFER_SIZE];
  57. char msg1[MSG_BUFFER_SIZE];
  58.  
  59. int value = 0;
  60.  
  61. void setup_wifi()
  62. {
  63. delay(10);
  64. // We start by connecting to a WiFi network
  65. Serial.println();
  66. Serial.print("Connecting to ");
  67. Serial.println(ssid);
  68.  
  69. WiFi.mode(WIFI_STA);
  70. WiFi.begin(ssid, password);
  71.  
  72. while (WiFi.status() != WL_CONNECTED)
  73. {
  74. delay(500);
  75. Serial.print(".");
  76. }
  77.  
  78. randomSeed(micros());
  79.  
  80. Serial.println("");
  81. Serial.println("WiFi connected");
  82. Serial.println("IP address: ");
  83. Serial.println(WiFi.localIP());
  84. }
  85.  
  86. void callback(char *topic, byte *payload, unsigned int length)
  87. {
  88. Serial.print("Message arrived [");
  89. Serial.print(topic);
  90. Serial.print("] ");
  91. for (int i = 0; i < length; i++)
  92. {
  93. Serial.print((char)payload[i]);
  94. }
  95. Serial.println();
  96.  
  97. payload[length] = '\0';
  98. String message = (char *)payload;
  99. if (strcmp(topic, sub_topic) == 0)
  100. {
  101. if (message == "off")
  102. {
  103. digitalWrite(LED, LOW); //Turn off
  104. client.publish(pub_led_topic, "off");
  105. }
  106. if (message == "on")
  107. {
  108. digitalWrite(LED, HIGH); //Turn on
  109. client.publish(pub_led_topic, "on");
  110. }
  111. }
  112.  
  113. /* Switch on the LED if an 1 was received as first character
  114. // if ((char)payload[0] == '1')
  115. // {
  116. // digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
  117. // // but actually the LED is on; this is because
  118. // // it is active low on the ESP-01)
  119. // }
  120. // else
  121. // {
  122. // digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
  123. // } */
  124. }
  125.  
  126. void reconnect()
  127. {
  128. // Loop until we're reconnected
  129. while (!client.connected())
  130. {
  131.  
  132. Serial.println("Attempting EMQX MQTT connection...");
  133. // Create a random client ID
  134. mqtt_ClientID += String(random(0xffff), HEX);
  135. // Attempt to connect
  136. if (client.connect((mqtt_ClientID, mqtt_userName, mqtt_password)))
  137. {
  138. Serial.print(" connected with Client ID: ");
  139. Serial.println(mqtt_ClientID);
  140. // Once connected, publish an announcement...
  141. client.publish(pub_init_topic, "Hi, I'm online!");
  142. // ... and resubscribe
  143. client.subscribe(sub_topic);
  144. }
  145. else
  146. {
  147. Serial.print("failed, rc=");
  148. Serial.print(client.state());
  149. Serial.println(" try again in 5 seconds");
  150. // Wait 5 seconds before retrying
  151. delay(5000);
  152. }
  153. }
  154. }
  155.  
  156. void setup()
  157. {
  158. //Start DH11 sensor
  159. dht.begin();
  160.  
  161. pinMode(LED, OUTPUT); // Initialize the _LED pin as an output
  162. digitalWrite(LED, LOW); //default ESP32 LOW is turn off
  163.  
  164. Serial.begin(115200);
  165. setup_wifi();
  166. client.setServer(mqtt_server, 1883);
  167. client.setCallback(callback);
  168. }
  169.  
  170. void loop()
  171. {
  172.  
  173. if (!client.connected())
  174. {
  175. reconnect();
  176. }
  177. client.loop();
  178.  
  179. unsigned long now = millis();
  180. if (now - lastMsg > updateCycle)
  181. {
  182. lastMsg = now;
  183. float humidity = dht.readHumidity();
  184. float temperature = dht.readTemperature();
  185. // Check if any reads failed and exit early (to try again).
  186. if (isnan(humidity) || isnan(temperature))
  187. {
  188. Serial.println(F("Failed to read from DHT sensor!"));
  189. return;
  190. }else{ // publish the message
  191. snprintf(msg, MSG_BUFFER_SIZE, "%.1lf°", temperature);
  192. snprintf(msg1, MSG_BUFFER_SIZE,"%.0lf%%", humidity);
  193. Serial.print("Publish message: ");
  194. Serial.println(msg);
  195. client.publish(pub_temp_topic, msg);
  196. client.publish(pub_humd_topic, msg1);
  197. }
  198.  
  199. }
  200. }
  201.  
;

No comments:

Post a Comment