server_mqtt.cpp 11 KB

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