server_mqtt.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. #include <string>
  2. #include <sstream>
  3. #include <iomanip>
  4. #include <vector>
  5. #include "esp_log.h"
  6. #include "ClassLogFile.h"
  7. #include "connect_wlan.h"
  8. #include "server_mqtt.h"
  9. #include "interface_mqtt.h"
  10. #include "time_sntp.h"
  11. static const char *TAG = "MQTT SERVER";
  12. extern const char* libfive_git_version(void);
  13. extern const char* libfive_git_revision(void);
  14. extern const char* libfive_git_branch(void);
  15. std::vector<NumberPost*>* NUMBERS;
  16. bool HomeassistantDiscovery = false;
  17. std::string meterType = "";
  18. std::string valueUnit = "";
  19. std::string timeUnit = "";
  20. std::string rateUnit = "Unit/Minute";
  21. float roundInterval; // Minutes
  22. int keepAlive = 0; // Seconds
  23. int retainFlag;
  24. static std::string maintopic;
  25. void mqttServer_setParameter(std::vector<NumberPost*>* _NUMBERS, int _keepAlive, float _roundInterval) {
  26. NUMBERS = _NUMBERS;
  27. keepAlive = _keepAlive;
  28. roundInterval = _roundInterval;
  29. }
  30. void mqttServer_setMeterType(std::string _meterType, std::string _valueUnit, std::string _timeUnit,std::string _rateUnit) {
  31. meterType = _meterType;
  32. valueUnit = _valueUnit;
  33. timeUnit = _timeUnit;
  34. rateUnit = _rateUnit;
  35. }
  36. void sendHomeAssistantDiscoveryTopic(std::string group, std::string field,
  37. std::string name, std::string icon, std::string unit, std::string deviceClass, std::string stateClass, std::string entityCategory) {
  38. std::string version = std::string(libfive_git_version());
  39. if (version == "") {
  40. version = std::string(libfive_git_branch()) + " (" + std::string(libfive_git_revision()) + ")";
  41. }
  42. std::string topicFull;
  43. std::string configTopic;
  44. std::string payload;
  45. std::string nl = "\n";
  46. configTopic = field;
  47. if (group != "" && (*NUMBERS).size() > 1) { // There is more than one meter, prepend the group so we can differentiate them
  48. configTopic = group + "_" + field;
  49. name = group + " " + name;
  50. }
  51. if (field == "problem") { // Special binary sensor which is based on error topic
  52. topicFull = "homeassistant/binary_sensor/" + maintopic + "/" + configTopic + "/config";
  53. }
  54. else {
  55. topicFull = "homeassistant/sensor/" + maintopic + "/" + configTopic + "/config";
  56. }
  57. /* See https://www.home-assistant.io/docs/mqtt/discovery/ */
  58. payload = "{" + nl +
  59. "\"~\": \"" + maintopic + "\"," + nl +
  60. "\"unique_id\": \"" + maintopic + "-" + configTopic + "\"," + nl +
  61. "\"object_id\": \"" + maintopic + "_" + configTopic + "\"," + nl + // This used to generate the Entity ID
  62. "\"name\": \"" + name + "\"," + nl +
  63. "\"icon\": \"mdi:" + icon + "\"," + nl;
  64. if (group != "") {
  65. if (field == "problem") { // Special binary sensor which is based on error topic
  66. payload += "\"state_topic\": \"~/" + group + "/error\"," + nl;
  67. payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\"," + nl;
  68. }
  69. else {
  70. payload += "\"state_topic\": \"~/" + group + "/" + field + "\"," + nl;
  71. }
  72. }
  73. else {
  74. payload += "\"state_topic\": \"~/" + field + "\"," + nl;
  75. }
  76. if (unit != "") {
  77. payload += "\"unit_of_meas\": \"" + unit + "\"," + nl;
  78. }
  79. if (deviceClass != "") {
  80. payload += "\"device_class\": \"" + deviceClass + "\"," + nl;
  81. }
  82. if (stateClass != "") {
  83. payload += "\"state_class\": \"" + stateClass + "\"," + nl;
  84. }
  85. if (entityCategory != "") {
  86. payload += "\"entity_category\": \"" + entityCategory + "\"," + nl;
  87. }
  88. payload +=
  89. "\"availability_topic\": \"~/" + std::string(LWT_TOPIC) + "\"," + nl +
  90. "\"payload_available\": \"" + LWT_CONNECTED + "\"," + nl +
  91. "\"payload_not_available\": \"" + LWT_DISCONNECTED + "\"," + nl;
  92. payload +=
  93. "\"device\": {" + nl +
  94. "\"identifiers\": [\"" + maintopic + "\"]," + nl +
  95. "\"name\": \"" + maintopic + "\"," + nl +
  96. "\"model\": \"Meter Digitizer\"," + nl +
  97. "\"manufacturer\": \"AI on the Edge Device\"," + nl +
  98. "\"sw_version\": \"" + version + "\"," + nl +
  99. "\"configuration_url\": \"http://" + *getIPAddress() + "\"" + nl +
  100. "}" + nl +
  101. "}" + nl;
  102. MQTTPublish(topicFull, payload, true);
  103. }
  104. void MQTThomeassistantDiscovery() {
  105. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "MQTT - Sending Homeassistant Discovery Topics (Meter Type: " + meterType + ", Value Unit: " + valueUnit + " , Rate Unit: " + rateUnit + ")...");
  106. // Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
  107. sendHomeAssistantDiscoveryTopic("", "uptime", "Uptime", "clock-time-eight-outline", "s", "", "", "diagnostic");
  108. sendHomeAssistantDiscoveryTopic("", "MAC", "MAC Address", "network-outline", "", "", "", "diagnostic");
  109. sendHomeAssistantDiscoveryTopic("", "hostname", "Hostname", "network-outline", "", "", "", "diagnostic");
  110. sendHomeAssistantDiscoveryTopic("", "freeMem", "Free Memory", "memory", "B", "", "measurement", "diagnostic");
  111. sendHomeAssistantDiscoveryTopic("", "wifiRSSI", "Wi-Fi RSSI", "wifi", "dBm", "signal_strength", "", "diagnostic");
  112. sendHomeAssistantDiscoveryTopic("", "CPUtemp", "CPU Temperature", "thermometer", "°C", "temperature", "measurement", "diagnostic");
  113. sendHomeAssistantDiscoveryTopic("", "interval", "Interval", "clock-time-eight-outline", "min", "" , "measurement", "diagnostic");
  114. sendHomeAssistantDiscoveryTopic("", "IP", "IP", "network-outline", "", "", "", "diagnostic");
  115. sendHomeAssistantDiscoveryTopic("", "status", "Status", "list-status", "", "", "", "diagnostic");
  116. for (int i = 0; i < (*NUMBERS).size(); ++i) {
  117. std::string group = (*NUMBERS)[i]->name;
  118. // Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
  119. sendHomeAssistantDiscoveryTopic(group, "value", "Value", "gauge", valueUnit, meterType, "total_increasing", "");
  120. sendHomeAssistantDiscoveryTopic(group, "raw", "Raw Value", "raw", valueUnit, "", "total_increasing", "diagnostic");
  121. sendHomeAssistantDiscoveryTopic(group, "error", "Error", "alert-circle-outline", "", "", "", "diagnostic");
  122. /* Not announcing "rate" as it is better to use rate_per_time_unit resp. rate_per_digitalization_round */
  123. // sendHomeAssistantDiscoveryTopic(group, "rate", "Rate (Unit/Minute)", "swap-vertical", "", "", "", ""); // Legacy, always Unit per Minute
  124. sendHomeAssistantDiscoveryTopic(group, "rate_per_time_unit", "Rate (" + rateUnit + ")", "swap-vertical", rateUnit, "", "", "");
  125. sendHomeAssistantDiscoveryTopic(group, "rate_per_digitalization_round", "Change since last digitalization round", "arrow-expand-vertical", valueUnit, "", "measurement", ""); // correctly the Unit is Uint/Interval!
  126. sendHomeAssistantDiscoveryTopic(group, "timestamp", "Timestamp", "clock-time-eight-outline", "", "timestamp", "", "diagnostic");
  127. sendHomeAssistantDiscoveryTopic(group, "json", "JSON", "code-json", "", "", "", "diagnostic");
  128. sendHomeAssistantDiscoveryTopic(group, "problem", "Problem", "alert-outline", "", "", "", ""); // Special binary sensor which is based on error topic
  129. }
  130. }
  131. void publishSystemData() {
  132. char tmp_char[50];
  133. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Publishing system MQTT topics...");
  134. sprintf(tmp_char, "%ld", (long)getUpTime());
  135. MQTTPublish(maintopic + "/" + "uptime", std::string(tmp_char), retainFlag);
  136. sprintf(tmp_char, "%zu", esp_get_free_heap_size());
  137. MQTTPublish(maintopic + "/" + "freeMem", std::string(tmp_char), retainFlag);
  138. sprintf(tmp_char, "%d", get_WIFI_RSSI());
  139. MQTTPublish(maintopic + "/" + "wifiRSSI", std::string(tmp_char), retainFlag);
  140. sprintf(tmp_char, "%d", (int)temperatureRead());
  141. MQTTPublish(maintopic + "/" + "CPUtemp", std::string(tmp_char), retainFlag);
  142. }
  143. void publishStaticData() {
  144. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Publishing static MQTT topics...");
  145. MQTTPublish(maintopic + "/" + "MAC", getMac(), retainFlag);
  146. MQTTPublish(maintopic + "/" + "IP", *getIPAddress(), retainFlag);
  147. MQTTPublish(maintopic + "/" + "hostname", hostname, retainFlag);
  148. std::stringstream stream;
  149. stream << std::fixed << std::setprecision(1) << roundInterval; // minutes
  150. MQTTPublish(maintopic + "/" + "interval", stream.str(), retainFlag);
  151. }
  152. esp_err_t sendDiscovery_and_static_Topics(httpd_req_t *req) {
  153. if (HomeassistantDiscovery) {
  154. MQTThomeassistantDiscovery();
  155. }
  156. publishStaticData();
  157. const char* resp_str = (const char*) req->user_ctx;
  158. httpd_resp_send(req, resp_str, strlen(resp_str));
  159. return ESP_OK;
  160. }
  161. void GotConnected(std::string maintopic, int retainFlag) {
  162. if (HomeassistantDiscovery) {
  163. MQTThomeassistantDiscovery();
  164. }
  165. publishStaticData();
  166. publishSystemData();
  167. }
  168. void register_server_mqtt_uri(httpd_handle_t server) {
  169. httpd_uri_t uri = { };
  170. uri.method = HTTP_GET;
  171. uri.uri = "/mqtt_publish_discovery";
  172. uri.handler = sendDiscovery_and_static_Topics;
  173. uri.user_ctx = (void*) "MQTT Discovery and Static Topics sent";
  174. httpd_register_uri_handler(server, &uri);
  175. }
  176. std::string getTimeUnit(void) {
  177. return timeUnit;
  178. }
  179. void SetHomeassistantDiscoveryEnabled(bool enabled) {
  180. HomeassistantDiscovery = enabled;
  181. }
  182. void setMqtt_Server_Retain(int _retainFlag) {
  183. retainFlag = _retainFlag;
  184. }
  185. void mqttServer_setMainTopic( std::string _maintopic) {
  186. maintopic = _maintopic;
  187. }
  188. std::string mqttServer_getMainTopic() {
  189. return maintopic;
  190. }