server_mqtt.cpp 19 KB

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