server_mqtt.cpp 16 KB

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