server_mqtt.cpp 11 KB

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