server_mqtt.cpp 11 KB

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