server_mqtt.cpp 11 KB

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