能源管控程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

74 lines
1.9 KiB

  1. #include <Arduino.h>
  2. using std::string;
  3. // Queue.
  4. #include <freertos/queue.h>
  5. QueueHandle_t mqttQueue;
  6. typedef struct {
  7. string name;
  8. string metric;
  9. } mqttMessage;
  10. // Ds18b20.
  11. #include <DallasTemperature.h>
  12. #include <OneWire.h>
  13. #define ONE_WIRE_BUS1 GPIO_NUM_18
  14. OneWire oneWire1(ONE_WIRE_BUS1);
  15. DallasTemperature ds18(&oneWire1);
  16. TaskHandle_t ds18b20;
  17. void ds18b20Task(void *pvParam) {
  18. ds18.begin();
  19. while (true) {
  20. float temperature = ds18.getTempCByIndex(0);
  21. if (temperature != DEVICE_DISCONNECTED_C) {
  22. char data[10];
  23. sprintf(data, "%.2f", temperature);
  24. string metric = std::string(data);
  25. mqttMessage msg = {"temperature", metric};
  26. xQueueSend(mqttQueue, &msg, portMAX_DELAY);
  27. // printf("Tin = %.2f C\n", temperature);
  28. } // else: printf("Error: Could not read temperature data\n");
  29. vTaskDelay(10356 / portTICK_PERIOD_MS);
  30. }
  31. }
  32. // EspMqtt.
  33. #include "EspMQTT.h"
  34. EspMQTT mqtt;
  35. void mqtt_callback(std::string param, std::string value);
  36. void mqttSetup() {
  37. uint16_t debugLevel = 0;
  38. if (debugLevel) {
  39. mqtt.debugLevel = debugLevel;
  40. mqtt.setAvailabilityInterval(5);
  41. }
  42. // MqTT:
  43. mqtt.setWiFi("wifi-name", "wifi-pass", "hostname");
  44. mqtt.setMqtt("mqtt-server", "mqtt-user", "mqtt-pass");
  45. mqtt.setCommonTopics("my/root/topic/dir", "ds18b20");
  46. // mqtt.setCallback(mqtt_callback);
  47. mqtt.start(true);
  48. }
  49. // Main.cpp Setup.
  50. void setup() {
  51. mqttSetup();
  52. mqttQueue = xQueueCreate(10, sizeof(mqttMessage));
  53. xTaskCreate(ds18b20Task, "ds18b20", 1024, NULL, 1, &ds18b20);
  54. }
  55. // Main.cpp Loop.
  56. mqttMessage message;
  57. QueueHandle_t mqttQueue;
  58. void loop() {
  59. if (xQueueReceive(mqttQueue, &message, 100 / portTICK_PERIOD_MS) == pdTRUE) {
  60. mqtt.publishMetric(message.name, message.metric);
  61. // printf("mqtt [%s] push = %s\n", msg.name.c_str(), msg.metric.c_str());
  62. }
  63. // vTaskDelay(10 / portTICK_PERIOD_MS);
  64. }