2021/10/31

#6 監測資料寫入InfluxDB資料庫, 長期保存並在NodeRED資訊看板裡顯示

大家好, 今天來和大家分享 “一起來學樹莓派, 寫入InfluxDB 資料庫”. 上集分享的是資料送到 MQTT 顯示到資訊看板後, 時間後後資料就消失了. 本集是把所有的資料收集起來之後, 可以用來以後做為資料分析的依據. 以前你可能要把資料寫到 Thinkspeak server上, 現在自己家裡的樹莓派上就可以做到了! 一起來學樹莓派吧!


這影片內容有:
  • 安裝 InfluxDB 資料庫
  • 比較 InfluxDB 與關聯式資庫的不同
  • 如何把ESP32送到 MQTT 資料寫入InfluxDB 資料庫
  • 讀取InfluxDB 資料庫, 再把這些資料在資訊看板上顯示出來




Format code for writing InfluxDB

  1. // Create the object key to match DB filed name from topic name(studio/temp1)
  2. msg.payload["temp"] = msg.payload["studio/temp1"];
  3. // Delete the unwanted studio/temp1
  4. delete msg.payload["studio/temp1"];
  5. // Update temp from string to float
  6. msg.payload["temp"] = parseFloat(msg.payload["temp"]);
  7.  
  8. msg.payload["humd"] = msg.payload["studio/humd1"];
  9. delete msg.payload["studio/humd1"];
  10. msg.payload["humd"] = parseFloat(msg.payload["humd"]);
  11.  
  12. //remove unused topic
  13. delete msg.topic;
  14.  
  15. //Create a temporary array
  16. var data = [];
  17. data.push(msg.payload);
  18.  
  19.  
  20. //Add object to DB Tag(index field)
  21. data.push({"location":"studio"});
  22. //msg.payload.push({"location":"studio"});
  23.  
  24. //Copy temporary array to msg.payload
  25. msg.payload = data;
  26. return msg;

Format code for reading historical InfluxDB data

  1.  
  2.  
  3. //Source from: https://discourse.nodered.org/t/display-2-extracts-from-influxdb-in-an-ui-chart/29665
  4. var series = ["Temperature °C", "Humdity %"];
  5. var labels = ["temp", "Humdity"];
  6.  
  7. var data0 = "[";
  8. var thetime0;
  9.  
  10. for (var i=0; i < msg.payload.results[0].series[0].values.length; i++) {
  11. thetime0 = (msg.payload.results[0].series[0].values[i][0]); // Some manipulation of the time may be required
  12. thetime0 = Date.parse(thetime0);
  13. data0 += '{ "x":' + thetime0 + ', "y":' + (msg.payload.results[0].series[0].values[i][1]) + '}';
  14. if (i < (msg.payload.results[0].series[0].values.length - 1)) {
  15. data0 += ","
  16. } else {
  17. data0 += "]"
  18. }
  19. }
  20.  
  21.  
  22.  
  23. var data1 = "[";
  24. var thetime1;
  25.  
  26. for (var j=0; j < msg.payload.results[0].series[0].values.length; j++) {
  27. thetime1 = (msg.payload.results[0].series[0].values[j][0]); // Some manipulation of the time may be required
  28. thetime1 = Date.parse(thetime1);
  29. data1 += '{ "x":' + thetime1 + ', "y":' + (msg.payload.results[0].series[0].values[j][2]) + '}';
  30. if (j < (msg.payload.results[0].series[0].values.length - 1)) {
  31. data1 += ","
  32. } else {
  33. data1 += "]"
  34. }
  35. }
  36. var data = [data0, data1];
  37. var jsondata = [JSON.parse(data0), JSON.parse(data1)];
  38. msg.payload = [{"series": series, "data": jsondata, "labels": labels}];
  39. msg.dataPoints = data;
  40.  
  41.  
  42. return msg;
  43.  

請在此下載本篇教學的 NodeRead 程式: #6 監測資料寫入InfluxDB資料庫, 長期保存並在NodeRED資訊看板裡顯示

更新:
影片內容不小心略過這個 InfluxDB Out Node (Write to studioTempDB)的內容:

InfluxDB out node 內容有兩項資料要輸入:
(1) 定義 InfluxDB Server, 按下鉛筆符號(見下圖)
(2) 寫入的 Measurement 資料表名稱,我們的範例裡,Measurement = studioTemp

定義 InfluxDB Server:
(1) InfluxDB - 在 Flow 裡看到的名稱
(2) InfluxDB 版本 - 教學裡案裝的是 v1.64
(3) Host: InfluxDB 的主機: 由於我們裝在本機,所以用 : raspberrypi.local, Port: 8086
(4) 資料庫名稱: 範例裡使用 studioTemp
(5) 資料庫帳號及密碼: 如果未設定可略過


Stonez56 一起來學樹莓派系列影片: 


2021/10/23

#5 2021 一起學 Raspberry Pi 4 - 溫溼度感測器DHT11由 ESP32 經 MQTT 送到 Node-RED

大家好, 今天來和大家分享如何把 DHT11溫溼度感測器上的資料由ESP32 讀取, 並用MQTT Client 發佈到 Mosquitto Server(MQTT), 再送到 Node-RED上, 再把這些資料在資訊看板上顯示出來. 


本篇使用到的程式碼:

  1. //---- Setup update frequency -----//
  2. const long TEMP_updateInterval = 10000; // How long to change temp and update, 10000 = 10 sec
  3. unsigned long TEMP_currentMillis = 0;
  4. unsigned long TEMP_previousMillis = 0; // store last time temp update
  5.  
  6. #include "DHT.h"
  7. #define DHTPIN 23 //ESP32 pin 23
  8. #define DHTTYPE DHT11
  9. DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
  10.  
  11. /*
  12. SimpleMQTTClient.ino
  13. The purpose of this exemple is to illustrate a simple handling of MQTT and Wifi connection.
  14. Once it connects successfully to a Wifi network and a MQTT broker, it subscribe to a topic and send a message to it.
  15. It will also send a message delayed 5 seconds later.
  16. */
  17.  
  18. #include "EspMQTTClient.h"
  19.  
  20. EspMQTTClient client(
  21. "Your_WiFi_AP", // Wi-Fi AP name
  22. "Wi-FI_Password", // Wi-Fi Password
  23. "192.168.0.119", // MQTT Broker server ip
  24. "", // Broker user name; Can be omitted if not needed
  25. "", // Broker password; Can be omitted if not needed
  26. "ESP32_Client", // Client name that uniquely identify your device
  27. 1883 // The MQTT port, default to 1883. this line can be omitted
  28. );
  29.  
  30. void setup()
  31. {
  32. Serial.begin(115200);
  33. //Start DH11 sensor
  34. dht.begin();
  35. // Optionnal functionnalities of EspMQTTClient :
  36. client.enableDebuggingMessages(); // Enable debugging messages sent to serial output
  37. //client.enableHTTPWebUpdater(); // Enable the web updater. User and password default to values of MQTTUsername and MQTTPassword. These can be overrited with enableHTTPWebUpdater("user", "password").
  38. //client.enableLastWillMessage("TestClient/lastwill", "I am going offline"); // You can activate the retain flag by setting the third parameter to true
  39. }
  40.  
  41. // This function is called once everything is connected (Wifi and MQTT)
  42. // WARNING : YOU MUST IMPLEMENT IT IF YOU USE EspMQTTClient
  43. void onConnectionEstablished()
  44. {
  45. // Subscribe to "mytopic/test" and display received message to Serial
  46. client.subscribe("message/hello", [](const String &payload)
  47. { Serial.println(payload); });
  48.  
  49. // Subscribe to "mytopic/wildcardtest/#" and display received message to Serial
  50. //client.subscribe("mytopic/wildcardtest/#", [](const String &topic, const String &payload)
  51. // { Serial.println("(From wildcard) topic: " + topic + ", payload: " + payload); });
  52.  
  53. // Publish a message to "mytopic/test"
  54. client.publish("studio/temp1", "Let's go!"); // You can activate the retain flag by setting the third parameter to true
  55.  
  56. // Execute delayed instructions
  57. //client.executeDelayed(5 * 1000, []()
  58. // { client.publish("mytopic/wildcardtest/test123", "This is a message sent 5 seconds later"); });
  59. }
  60.  
  61.  
  62.  
  63. void loop()
  64. {
  65.  
  66. TEMP_currentMillis = millis();
  67. if(TEMP_currentMillis - TEMP_previousMillis >= TEMP_updateInterval){
  68. TEMP_previousMillis = TEMP_currentMillis;
  69.  
  70. // Reading temperature or humidity takes about 250 milliseconds!
  71. // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  72. float humidity = dht.readHumidity();
  73. float temperature = dht.readTemperature();
  74. // Read temperature as Fahrenheit (isFahrenheit = true)
  75. //float f = dht.readTemperature(true);
  76.  
  77. // Check if any reads failed and exit early (to try again).
  78. if (isnan(humidity) || isnan(temperature))
  79. {
  80. Serial.println(F("Failed to read from DHT sensor!"));
  81. return;
  82. }
  83.  
  84. String tmp = "Current Temperature: ";
  85. String hud = "Current Humidity: ";
  86. Serial.print(tmp);
  87. Serial.println(String(temperature));
  88. Serial.print(hud);
  89. Serial.println(String(humidity));
  90. //Publish
  91. client.publish("studio/temp1", String(temperature));
  92. client.publish("studio/humd1", String(humidity));
  93.  
  94. // Here is how to subscribe
  95. //client.subscribe("message/hello", [](const String &payload) { Serial.println(payload); });
  96. }
  97.  
  98. client.loop();
  99. }
  100.  

*** 影片中忘了說明, 在 VS Code 裡, 按下 F1 到 Arduino Library Manager 裡, 搜尋 EspMQTTClient V.11.1版本, 並按下安裝 , 程式才能正確執行喔~~ ***


如果時間不夠的朋友, 也可以從以下的時間軸挑選想看的部份即可!

影片時間軸:

00:29 課程開始 00:52 如何將 DHT11 連接到 ESP32 (接線圖) 00:59 在 ESP32 利用 EspMQTTClient 來寫程式 01:22 安裝 DHT11 程式庫 02:16 設定 EspMQTTClient 02:45 由 Raspberry Pi Terminal 找出 Mosquitto(MQTT) IP 地址 04:51 不要用 delay() 在程式 Loop 裡! 06:50 上傳並檢查發佈/訂閱的 messages 07:54 安裝 Node-RED 資訊看板(在 Node-RED 中) 08:57 按主題來訂閱消息 09:58 設置 MQTT 服務器的位置 11:34 建立資訊看板選項 Tabs Links & Groups 17:00 建立歷史資料資訊看板 20:32 查看資訊看板 20:50 資訊看板中的選項 Tabs Links & Groups在哪裡

下一集將介紹如何把歷史資料存儲到樹莓派的資料庫(influxDBvor MySQL)中, 以取得長時間的記錄資料. 


Stonez56 一起來學樹莓派系列影片: 


參考資料:

EspMQTTClient: https://github.com/plapointe6/EspMQTTClient