server_mqtt.cpp 11 KB

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