server_mqtt.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 binary sensor which is based on error topic
  72. topicFull = "homeassistant/binary_sensor/" + node_id + "/" + configTopic + "/config";
  73. }
  74. else {
  75. topicFull = "homeassistant/sensor/" + node_id + "/" + configTopic + "/config";
  76. }
  77. /* See https://www.home-assistant.io/docs/mqtt/discovery/ */
  78. payload = string("{") +
  79. "\"~\": \"" + maintopic + "\"," +
  80. "\"unique_id\": \"" + maintopic + "-" + configTopic + "\"," +
  81. "\"object_id\": \"" + maintopic + "_" + configTopic + "\"," + // This used to generate the Entity ID
  82. "\"name\": \"" + name + "\"," +
  83. "\"icon\": \"mdi:" + icon + "\",";
  84. if (group != "") {
  85. if (field == "problem") { // Special binary sensor which is based on error topic
  86. payload += "\"state_topic\": \"~/" + group + "/error\",";
  87. payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\",";
  88. }
  89. else {
  90. payload += "\"state_topic\": \"~/" + group + "/" + field + "\",";
  91. }
  92. }
  93. else {
  94. if (field == "problem") { // Special binary sensor which is based on error topic
  95. payload += "\"state_topic\": \"~/error\",";
  96. payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\",";
  97. }
  98. else {
  99. payload += "\"state_topic\": \"~/" + field + "\",";
  100. }
  101. }
  102. if (unit != "") {
  103. payload += "\"unit_of_meas\": \"" + unit + "\",";
  104. }
  105. if (deviceClass != "") {
  106. payload += "\"device_class\": \"" + deviceClass + "\",";
  107. }
  108. if (stateClass != "") {
  109. payload += "\"state_class\": \"" + stateClass + "\",";
  110. }
  111. if (entityCategory != "") {
  112. payload += "\"entity_category\": \"" + entityCategory + "\",";
  113. }
  114. payload +=
  115. "\"availability_topic\": \"~/" + std::string(LWT_TOPIC) + "\"," +
  116. "\"payload_available\": \"" + LWT_CONNECTED + "\"," +
  117. "\"payload_not_available\": \"" + LWT_DISCONNECTED + "\",";
  118. payload += string("\"device\": {") +
  119. "\"identifiers\": [\"" + maintopic + "\"]," +
  120. "\"name\": \"" + maintopic + "\"," +
  121. "\"model\": \"Meter Digitizer\"," +
  122. "\"manufacturer\": \"AI on the Edge Device\"," +
  123. "\"sw_version\": \"" + version + "\"," +
  124. "\"configuration_url\": \"http://" + *getIPAddress() + "\"" +
  125. "}" +
  126. "}";
  127. return MQTTPublish(topicFull, payload, qos, true);
  128. }
  129. bool MQTThomeassistantDiscovery(int qos) {
  130. bool allSendsSuccessed = false;
  131. if (!getMQTTisConnected()) {
  132. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to send Homeassistant Discovery Topics, we are not connected to the MQTT broker!");
  133. return false;
  134. }
  135. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing Homeassistant Discovery topics (Meter Type: '" + meterType + "', Value Unit: '" + valueUnit + "' , Rate Unit: '" + rateUnit + "') ...");
  136. int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  137. // Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
  138. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "uptime", "Uptime", "clock-time-eight-outline", "s", "", "", "diagnostic", qos);
  139. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "MAC", "MAC Address", "network-outline", "", "", "", "diagnostic", qos);
  140. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "fwVersion", "Firmware Version", "application-outline", "", "", "", "diagnostic", qos);
  141. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "hostname", "Hostname", "network-outline", "", "", "", "diagnostic", qos);
  142. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "freeMem", "Free Memory", "memory", "B", "", "measurement", "diagnostic", qos);
  143. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "wifiRSSI", "Wi-Fi RSSI", "wifi", "dBm", "signal_strength", "", "diagnostic", qos);
  144. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "CPUtemp", "CPU Temperature", "thermometer", "°C", "temperature", "measurement", "diagnostic", qos);
  145. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "interval", "Interval", "clock-time-eight-outline", "min", "" , "measurement", "diagnostic", qos);
  146. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "IP", "IP", "network-outline", "", "", "", "diagnostic", qos);
  147. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "status", "Status", "list-status", "", "", "", "diagnostic", qos);
  148. for (int i = 0; i < (*NUMBERS).size(); ++i) {
  149. std::string group = (*NUMBERS)[i]->name;
  150. if (group == "default") {
  151. group = "";
  152. }
  153. /* 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 */
  154. std::string value_state_class = "total_increasing";
  155. if ((*NUMBERS)[i]->AllowNegativeRates) {
  156. value_state_class = "measurement";
  157. }
  158. /* Energy meters need a different Device Class, see https://github.com/jomjol/AI-on-the-edge-device/issues/3333 */
  159. std::string rate_device_class = "volume_flow_rate";
  160. if (meterType == "energy") {
  161. rate_device_class = "power";
  162. }
  163. // Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
  164. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "value", "Value", "gauge", valueUnit, meterType, value_state_class, "", qos); // State Class = "total_increasing" if <NUMBERS>.AllowNegativeRates = false, else use "measurement"
  165. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "raw", "Raw Value", "raw", valueUnit, meterType, "measurement", "diagnostic", qos);
  166. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "error", "Error", "alert-circle-outline", "", "", "", "diagnostic", qos);
  167. /* Not announcing "rate" as it is better to use rate_per_time_unit resp. rate_per_digitization_round */
  168. // allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate", "Rate (Unit/Minute)", "swap-vertical", "", "", "", ""); // Legacy, always Unit per Minute
  169. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_time_unit", "Rate (" + rateUnit + ")", "swap-vertical", rateUnit, rate_device_class, "measurement", "", qos);
  170. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_digitization_round", "Change since last Digitization round", "arrow-expand-vertical", valueUnit, "", "measurement", "", qos); // correctly the Unit is Unit/Interval!
  171. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "timestamp", "Timestamp", "clock-time-eight-outline", "", "timestamp", "", "diagnostic", qos);
  172. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "json", "JSON", "code-json", "", "", "", "diagnostic", qos);
  173. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "problem", "Problem", "alert-outline", "", "problem", "", "", qos); // Special binary sensor which is based on error topic
  174. }
  175. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Successfully published all Homeassistant Discovery MQTT topics");
  176. int aFreeInternalHeapSizeAfter = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  177. int aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  178. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Int. Heap Usage before Publishing Homeassistand Discovery Topics: " +
  179. to_string(aFreeInternalHeapSizeBefore) + ", after: " + to_string(aFreeInternalHeapSizeAfter) + ", delta: " +
  180. to_string(aFreeInternalHeapSizeBefore - aFreeInternalHeapSizeAfter) + ", lowest free: " + to_string(aMinFreeInternalHeapSize));
  181. return allSendsSuccessed;
  182. }
  183. bool publishSystemData(int qos) {
  184. bool allSendsSuccessed = false;
  185. if (!getMQTTisConnected()) {
  186. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to send System Topics, we are not connected to the MQTT broker!");
  187. return false;
  188. }
  189. char tmp_char[50];
  190. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing System MQTT topics...");
  191. int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  192. allSendsSuccessed |= MQTTPublish(maintopic + "/" + std::string(LWT_TOPIC), LWT_CONNECTED, qos, retainFlag); // Publish "connected" to maintopic/connection
  193. sprintf(tmp_char, "%ld", (long)getUpTime());
  194. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "uptime", std::string(tmp_char), qos, retainFlag);
  195. sprintf(tmp_char, "%lu", (long) getESPHeapSize());
  196. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "freeMem", std::string(tmp_char), qos, retainFlag);
  197. sprintf(tmp_char, "%d", get_WIFI_RSSI());
  198. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "wifiRSSI", std::string(tmp_char), qos, retainFlag);
  199. sprintf(tmp_char, "%d", (int)temperatureRead());
  200. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "CPUtemp", std::string(tmp_char), qos, retainFlag);
  201. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Successfully published all System MQTT topics");
  202. int aFreeInternalHeapSizeAfter = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  203. int aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  204. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Int. Heap Usage before publishing System Topics: " +
  205. to_string(aFreeInternalHeapSizeBefore) + ", after: " + to_string(aFreeInternalHeapSizeAfter) + ", delta: " +
  206. to_string(aFreeInternalHeapSizeBefore - aFreeInternalHeapSizeAfter) + ", lowest free: " + to_string(aMinFreeInternalHeapSize));
  207. return allSendsSuccessed;
  208. }
  209. bool publishStaticData(int qos) {
  210. bool allSendsSuccessed = false;
  211. if (!getMQTTisConnected()) {
  212. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to send Static Topics, we are not connected to the MQTT broker!");
  213. return false;
  214. }
  215. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing static MQTT topics...");
  216. int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  217. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "fwVersion", getFwVersion().c_str(), qos, retainFlag);
  218. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "MAC", getMac(), qos, retainFlag);
  219. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "IP", *getIPAddress(), qos, retainFlag);
  220. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "hostname", wlan_config.hostname, qos, retainFlag);
  221. std::stringstream stream;
  222. stream << std::fixed << std::setprecision(1) << roundInterval; // minutes
  223. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "interval", stream.str(), qos, retainFlag);
  224. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Successfully published all Static MQTT topics");
  225. int aFreeInternalHeapSizeAfter = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  226. int aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  227. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Int. Heap Usage before Publishing Static Topics: " +
  228. to_string(aFreeInternalHeapSizeBefore) + ", after: " + to_string(aFreeInternalHeapSizeAfter) + ", delta: " +
  229. to_string(aFreeInternalHeapSizeBefore - aFreeInternalHeapSizeAfter) + ", lowest free: " + to_string(aMinFreeInternalHeapSize));
  230. return allSendsSuccessed;
  231. }
  232. esp_err_t scheduleSendingDiscovery_and_static_Topics(httpd_req_t *req) {
  233. sendingOf_DiscoveryAndStaticTopics_scheduled = true;
  234. char msg[] = "MQTT Homeassistant Discovery and Static Topics scheduled";
  235. httpd_resp_send(req, msg, strlen(msg));
  236. return ESP_OK;
  237. }
  238. esp_err_t sendDiscovery_and_static_Topics(void) {
  239. bool success = false;
  240. if (!sendingOf_DiscoveryAndStaticTopics_scheduled) {
  241. // Flag not set, nothing to do
  242. return ESP_OK;
  243. }
  244. if (HomeassistantDiscovery) {
  245. success = MQTThomeassistantDiscovery(1);
  246. }
  247. success |= publishStaticData(1);
  248. if (success) { // Success, clear the flag
  249. sendingOf_DiscoveryAndStaticTopics_scheduled = false;
  250. return ESP_OK;
  251. }
  252. else {
  253. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "One or more MQTT topics failed to be published, will try sending them in the next round!");
  254. /* Keep sendingOf_DiscoveryAndStaticTopics_scheduled set so we can retry after the next round */
  255. return ESP_FAIL;
  256. }
  257. }
  258. void GotConnected(std::string maintopic, bool retainFlag) {
  259. // Nothing to do
  260. }
  261. void register_server_mqtt_uri(httpd_handle_t server) {
  262. httpd_uri_t uri = { };
  263. uri.method = HTTP_GET;
  264. uri.uri = "/mqtt_publish_discovery";
  265. uri.handler = scheduleSendingDiscovery_and_static_Topics;
  266. uri.user_ctx = (void*) "";
  267. httpd_register_uri_handler(server, &uri);
  268. }
  269. std::string getTimeUnit(void) {
  270. return timeUnit;
  271. }
  272. void SetHomeassistantDiscoveryEnabled(bool enabled) {
  273. HomeassistantDiscovery = enabled;
  274. }
  275. void setMqtt_Server_Retain(bool _retainFlag) {
  276. retainFlag = _retainFlag;
  277. }
  278. void mqttServer_setMainTopic( std::string _maintopic) {
  279. maintopic = _maintopic;
  280. }
  281. std::string mqttServer_getMainTopic() {
  282. return maintopic;
  283. }
  284. void mqttServer_setDmoticzInTopic( std::string _domoticzintopic) {
  285. domoticzintopic = _domoticzintopic;
  286. }
  287. #endif //ENABLE_MQTT