server_mqtt.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. extern std::string getFwVersion(void);
  19. std::vector<NumberPost*>* NUMBERS;
  20. bool HomeassistantDiscovery = false;
  21. std::string meterType = "";
  22. std::string valueUnit = "";
  23. std::string timeUnit = "";
  24. std::string rateUnit = "Unit/Minute";
  25. float roundInterval; // Minutes
  26. int keepAlive = 0; // Seconds
  27. bool retainFlag;
  28. static std::string maintopic, domoticzintopic;
  29. bool sendingOf_DiscoveryAndStaticTopics_scheduled = true; // Set it to true to make sure it gets sent at least once after startup
  30. void mqttServer_setParameter(std::vector<NumberPost*>* _NUMBERS, int _keepAlive, float _roundInterval) {
  31. NUMBERS = _NUMBERS;
  32. keepAlive = _keepAlive;
  33. roundInterval = _roundInterval;
  34. }
  35. void mqttServer_setMeterType(std::string _meterType, std::string _valueUnit, std::string _timeUnit,std::string _rateUnit) {
  36. meterType = _meterType;
  37. valueUnit = _valueUnit;
  38. timeUnit = _timeUnit;
  39. rateUnit = _rateUnit;
  40. }
  41. /**
  42. * Takes any multi-level MQTT-topic and returns the last topic level as nodeId
  43. * see https://www.hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices/ for details about MQTT topics
  44. */
  45. std::string createNodeId(std::string &topic) {
  46. auto splitPos = topic.find_last_of('/');
  47. return (splitPos == std::string::npos) ? topic : topic.substr(splitPos + 1);
  48. }
  49. bool sendHomeAssistantDiscoveryTopic(std::string group, std::string field,
  50. std::string name, std::string icon, std::string unit, std::string deviceClass, std::string stateClass, std::string entityCategory,
  51. int qos) {
  52. std::string version = std::string(libfive_git_version());
  53. if (version == "") {
  54. version = std::string(libfive_git_branch()) + " (" + std::string(libfive_git_revision()) + ")";
  55. }
  56. std::string topicFull;
  57. std::string configTopic;
  58. std::string payload;
  59. configTopic = field;
  60. if (group != "" && (*NUMBERS).size() > 1) { // There is more than one meter, prepend the group so we can differentiate them
  61. configTopic = group + "_" + field;
  62. name = group + " " + name;
  63. }
  64. /**
  65. * homeassistant needs the MQTT discovery topic according to the following structure:
  66. * <discovery_prefix>/<component>/[<node_id>/]<object_id>/config
  67. * if the main topic is embedded in a nested structure, we just use the last part as node_id
  68. * This means a maintopic "home/test/watermeter" is transformed to the discovery topic "homeassistant/sensor/watermeter/..."
  69. */
  70. std::string node_id = createNodeId(maintopic);
  71. if (field == "problem") { // Special case: Binary sensor which is based on error topic
  72. topicFull = "homeassistant/binary_sensor/" + node_id + "/" + configTopic + "/config";
  73. }
  74. else if (field == "flowstart") { // Special case: Button
  75. topicFull = "homeassistant/button/" + node_id + "/" + configTopic + "/config";
  76. }
  77. else {
  78. topicFull = "homeassistant/sensor/" + node_id + "/" + configTopic + "/config";
  79. }
  80. /* See https://www.home-assistant.io/docs/mqtt/discovery/ */
  81. payload = string("{") +
  82. "\"~\": \"" + maintopic + "\"," +
  83. "\"unique_id\": \"" + maintopic + "-" + configTopic + "\"," +
  84. "\"object_id\": \"" + maintopic + "_" + configTopic + "\"," + // This used to generate the Entity ID
  85. "\"name\": \"" + name + "\"," +
  86. "\"icon\": \"mdi:" + icon + "\",";
  87. if (group != "") {
  88. if (field == "problem") { // Special case: Binary sensor which is based on error topic
  89. payload += "\"state_topic\": \"~/" + group + "/error\",";
  90. payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\",";
  91. }
  92. else {
  93. payload += "\"state_topic\": \"~/" + group + "/" + field + "\",";
  94. }
  95. }
  96. else {
  97. if (field == "problem") { // Special case: Binary sensor which is based on error topic
  98. payload += "\"state_topic\": \"~/error\",";
  99. payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\",";
  100. }
  101. else if (field == "flowstart") { // Special case: Button
  102. payload += "\"cmd_t\":\"~/ctrl/flow_start\","; // Add command topic
  103. }
  104. else {
  105. payload += "\"state_topic\": \"~/" + field + "\",";
  106. }
  107. }
  108. if (unit != "") {
  109. payload += "\"unit_of_meas\": \"" + unit + "\",";
  110. }
  111. if (deviceClass != "") {
  112. payload += "\"device_class\": \"" + deviceClass + "\",";
  113. }
  114. if (stateClass != "") {
  115. payload += "\"state_class\": \"" + stateClass + "\",";
  116. }
  117. if (entityCategory != "") {
  118. payload += "\"entity_category\": \"" + entityCategory + "\",";
  119. }
  120. payload +=
  121. "\"availability_topic\": \"~/" + std::string(LWT_TOPIC) + "\"," +
  122. "\"payload_available\": \"" + LWT_CONNECTED + "\"," +
  123. "\"payload_not_available\": \"" + LWT_DISCONNECTED + "\",";
  124. payload += string("\"device\": {") +
  125. "\"identifiers\": [\"" + maintopic + "\"]," +
  126. "\"name\": \"" + maintopic + "\"," +
  127. "\"model\": \"Meter Digitizer\"," +
  128. "\"manufacturer\": \"AI on the Edge Device\"," +
  129. "\"sw_version\": \"" + version + "\"," +
  130. "\"configuration_url\": \"http://" + *getIPAddress() + "\"" +
  131. "}" +
  132. "}";
  133. return MQTTPublish(topicFull, payload, qos, true);
  134. }
  135. bool MQTThomeassistantDiscovery(int qos) {
  136. bool allSendsSuccessed = false;
  137. if (!getMQTTisConnected()) {
  138. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to send Homeassistant Discovery Topics, we are not connected to the MQTT broker!");
  139. return false;
  140. }
  141. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing Homeassistant Discovery topics (Meter Type: '" + meterType + "', Value Unit: '" + valueUnit + "' , Rate Unit: '" + rateUnit + "') ...");
  142. int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  143. // Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
  144. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "uptime", "Uptime", "clock-time-eight-outline", "s", "", "", "diagnostic", qos);
  145. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "MAC", "MAC Address", "network-outline", "", "", "", "diagnostic", qos);
  146. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "fwVersion", "Firmware Version", "application-outline", "", "", "", "diagnostic", qos);
  147. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "hostname", "Hostname", "network-outline", "", "", "", "diagnostic", qos);
  148. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "freeMem", "Free Memory", "memory", "B", "", "measurement", "diagnostic", qos);
  149. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "wifiRSSI", "Wi-Fi RSSI", "wifi", "dBm", "signal_strength", "", "diagnostic", qos);
  150. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "CPUtemp", "CPU Temperature", "thermometer", "°C", "temperature", "measurement", "diagnostic", qos);
  151. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "interval", "Interval", "clock-time-eight-outline", "min", "" , "measurement", "diagnostic", qos);
  152. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "IP", "IP", "network-outline", "", "", "", "diagnostic", qos);
  153. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "status", "Status", "list-status", "", "", "", "diagnostic", qos);
  154. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "flowstart", "Manual Flow Start", "timer-play-outline", "", "", "", "", qos);
  155. for (int i = 0; i < (*NUMBERS).size(); ++i) {
  156. std::string group = (*NUMBERS)[i]->name;
  157. if (group == "default") {
  158. group = "";
  159. }
  160. /* If "Allow neg. rate" is true, use "measurement" instead of "total_increasing" for the State Class, see https://github.com/jomjol/AI-on-the-edge-device/issues/3331 */
  161. std::string value_state_class = "total_increasing";
  162. if ((*NUMBERS)[i]->AllowNegativeRates) {
  163. value_state_class = "measurement";
  164. }
  165. /* Energy meters need a different Device Class, see https://github.com/jomjol/AI-on-the-edge-device/issues/3333 */
  166. std::string rate_device_class = "volume_flow_rate";
  167. if (meterType == "energy") {
  168. rate_device_class = "power";
  169. }
  170. // Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
  171. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "value", "Value", "gauge", valueUnit, meterType, value_state_class, "", qos); // State Class = "total_increasing" if <NUMBERS>.AllowNegativeRates = false, else use "measurement"
  172. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "raw", "Raw Value", "raw", valueUnit, meterType, "measurement", "diagnostic", qos);
  173. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "error", "Error", "alert-circle-outline", "", "", "", "diagnostic", qos);
  174. /* Not announcing "rate" as it is better to use rate_per_time_unit resp. rate_per_digitization_round */
  175. // allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate", "Rate (Unit/Minute)", "swap-vertical", "", "", "", ""); // Legacy, always Unit per Minute
  176. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_time_unit", "Rate (" + rateUnit + ")", "swap-vertical", rateUnit, rate_device_class, "measurement", "", qos);
  177. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_digitization_round", "Change since last Digitization round", "arrow-expand-vertical", valueUnit, "", "measurement", "", qos); // correctly the Unit is Unit/Interval!
  178. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "timestamp", "Timestamp", "clock-time-eight-outline", "", "timestamp", "", "diagnostic", qos);
  179. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "json", "JSON", "code-json", "", "", "", "diagnostic", qos);
  180. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "problem", "Problem", "alert-outline", "", "problem", "", "", qos); // Special binary sensor which is based on error topic
  181. }
  182. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Successfully published all Homeassistant Discovery MQTT topics");
  183. int aFreeInternalHeapSizeAfter = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  184. int aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  185. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Int. Heap Usage before Publishing Homeassistand Discovery Topics: " +
  186. to_string(aFreeInternalHeapSizeBefore) + ", after: " + to_string(aFreeInternalHeapSizeAfter) + ", delta: " +
  187. to_string(aFreeInternalHeapSizeBefore - aFreeInternalHeapSizeAfter) + ", lowest free: " + to_string(aMinFreeInternalHeapSize));
  188. return allSendsSuccessed;
  189. }
  190. bool publishSystemData(int qos) {
  191. bool allSendsSuccessed = false;
  192. if (!getMQTTisConnected()) {
  193. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to send System Topics, we are not connected to the MQTT broker!");
  194. return false;
  195. }
  196. char tmp_char[50];
  197. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing System MQTT topics...");
  198. int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  199. allSendsSuccessed |= MQTTPublish(maintopic + "/" + std::string(LWT_TOPIC), LWT_CONNECTED, qos, retainFlag); // Publish "connected" to maintopic/connection
  200. sprintf(tmp_char, "%ld", (long)getUpTime());
  201. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "uptime", std::string(tmp_char), qos, retainFlag);
  202. sprintf(tmp_char, "%lu", (long) getESPHeapSize());
  203. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "freeMem", std::string(tmp_char), qos, retainFlag);
  204. sprintf(tmp_char, "%d", get_WIFI_RSSI());
  205. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "wifiRSSI", std::string(tmp_char), qos, retainFlag);
  206. sprintf(tmp_char, "%d", (int)temperatureRead());
  207. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "CPUtemp", std::string(tmp_char), qos, retainFlag);
  208. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Successfully published all System MQTT topics");
  209. int aFreeInternalHeapSizeAfter = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  210. int aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  211. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Int. Heap Usage before publishing System Topics: " +
  212. to_string(aFreeInternalHeapSizeBefore) + ", after: " + to_string(aFreeInternalHeapSizeAfter) + ", delta: " +
  213. to_string(aFreeInternalHeapSizeBefore - aFreeInternalHeapSizeAfter) + ", lowest free: " + to_string(aMinFreeInternalHeapSize));
  214. return allSendsSuccessed;
  215. }
  216. bool publishStaticData(int qos) {
  217. bool allSendsSuccessed = false;
  218. if (!getMQTTisConnected()) {
  219. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to send Static Topics, we are not connected to the MQTT broker!");
  220. return false;
  221. }
  222. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing static MQTT topics...");
  223. int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  224. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "fwVersion", getFwVersion().c_str(), qos, retainFlag);
  225. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "MAC", getMac(), qos, retainFlag);
  226. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "IP", *getIPAddress(), qos, retainFlag);
  227. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "hostname", wlan_config.hostname, qos, retainFlag);
  228. std::stringstream stream;
  229. stream << std::fixed << std::setprecision(1) << roundInterval; // minutes
  230. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "interval", stream.str(), qos, retainFlag);
  231. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Successfully published all Static MQTT topics");
  232. int aFreeInternalHeapSizeAfter = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  233. int aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  234. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Int. Heap Usage before Publishing Static Topics: " +
  235. to_string(aFreeInternalHeapSizeBefore) + ", after: " + to_string(aFreeInternalHeapSizeAfter) + ", delta: " +
  236. to_string(aFreeInternalHeapSizeBefore - aFreeInternalHeapSizeAfter) + ", lowest free: " + to_string(aMinFreeInternalHeapSize));
  237. return allSendsSuccessed;
  238. }
  239. esp_err_t scheduleSendingDiscovery_and_static_Topics(httpd_req_t *req) {
  240. sendingOf_DiscoveryAndStaticTopics_scheduled = true;
  241. char msg[] = "MQTT Homeassistant Discovery and Static Topics scheduled";
  242. httpd_resp_send(req, msg, strlen(msg));
  243. return ESP_OK;
  244. }
  245. esp_err_t sendDiscovery_and_static_Topics(void) {
  246. bool success = false;
  247. if (!sendingOf_DiscoveryAndStaticTopics_scheduled) {
  248. // Flag not set, nothing to do
  249. return ESP_OK;
  250. }
  251. if (HomeassistantDiscovery) {
  252. success = MQTThomeassistantDiscovery(1);
  253. }
  254. success |= publishStaticData(1);
  255. if (success) { // Success, clear the flag
  256. sendingOf_DiscoveryAndStaticTopics_scheduled = false;
  257. return ESP_OK;
  258. }
  259. else {
  260. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "One or more MQTT topics failed to be published, will try sending them in the next round!");
  261. /* Keep sendingOf_DiscoveryAndStaticTopics_scheduled set so we can retry after the next round */
  262. return ESP_FAIL;
  263. }
  264. }
  265. void GotConnected(std::string maintopic, bool retainFlag) {
  266. // Nothing to do
  267. }
  268. void register_server_mqtt_uri(httpd_handle_t server) {
  269. httpd_uri_t uri = { };
  270. uri.method = HTTP_GET;
  271. uri.uri = "/mqtt_publish_discovery";
  272. uri.handler = scheduleSendingDiscovery_and_static_Topics;
  273. uri.user_ctx = (void*) "";
  274. httpd_register_uri_handler(server, &uri);
  275. }
  276. std::string getTimeUnit(void) {
  277. return timeUnit;
  278. }
  279. void SetHomeassistantDiscoveryEnabled(bool enabled) {
  280. HomeassistantDiscovery = enabled;
  281. }
  282. void setMqtt_Server_Retain(bool _retainFlag) {
  283. retainFlag = _retainFlag;
  284. }
  285. void mqttServer_setMainTopic( std::string _maintopic) {
  286. maintopic = _maintopic;
  287. }
  288. std::string mqttServer_getMainTopic() {
  289. return maintopic;
  290. }
  291. void mqttServer_setDmoticzInTopic( std::string _domoticzintopic) {
  292. domoticzintopic = _domoticzintopic;
  293. }
  294. #endif //ENABLE_MQTT