server_mqtt.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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("", "hostname", "Hostname", "network-outline", "", "", "", "diagnostic", qos);
  125. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "freeMem", "Free Memory", "memory", "B", "", "measurement", "diagnostic", qos);
  126. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "wifiRSSI", "Wi-Fi RSSI", "wifi", "dBm", "signal_strength", "", "diagnostic", qos);
  127. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "CPUtemp", "CPU Temperature", "thermometer", "°C", "temperature", "measurement", "diagnostic", qos);
  128. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "interval", "Interval", "clock-time-eight-outline", "min", "" , "measurement", "diagnostic", qos);
  129. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "IP", "IP", "network-outline", "", "", "", "diagnostic", qos);
  130. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic("", "status", "Status", "list-status", "", "", "", "diagnostic", qos);
  131. for (int i = 0; i < (*NUMBERS).size(); ++i) {
  132. std::string group = (*NUMBERS)[i]->name;
  133. if (group == "default") {
  134. group = "";
  135. }
  136. // Group | Field | User Friendly Name | Icon | Unit | Device Class | State Class | Entity Category
  137. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "value", "Value", "gauge", valueUnit, meterType, "total_increasing", "", qos);
  138. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "raw", "Raw Value", "raw", "", "", "", "diagnostic", qos);
  139. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "error", "Error", "alert-circle-outline", "", "", "", "diagnostic", qos);
  140. /* Not announcing "rate" as it is better to use rate_per_time_unit resp. rate_per_digitalization_round */
  141. // allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate", "Rate (Unit/Minute)", "swap-vertical", "", "", "", ""); // Legacy, always Unit per Minute
  142. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_time_unit", "Rate (" + rateUnit + ")", "swap-vertical", rateUnit, "", "measurement", "", qos);
  143. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "rate_per_digitalization_round", "Change since last digitalization round", "arrow-expand-vertical", valueUnit, "", "measurement", "", qos); // correctly the Unit is Unit/Interval!
  144. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "timestamp", "Timestamp", "clock-time-eight-outline", "", "timestamp", "", "diagnostic", qos);
  145. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "json", "JSON", "code-json", "", "", "", "diagnostic", qos);
  146. allSendsSuccessed |= sendHomeAssistantDiscoveryTopic(group, "problem", "Problem", "alert-outline", "", "problem", "", "", qos); // Special binary sensor which is based on error topic
  147. }
  148. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Successfully published all Homeassistant Discovery MQTT topics");
  149. int aFreeInternalHeapSizeAfter = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  150. int aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  151. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Int. Heap Usage before Publishing Homeassistand Discovery Topics: " +
  152. to_string(aFreeInternalHeapSizeBefore) + ", after: " + to_string(aFreeInternalHeapSizeAfter) + ", delta: " +
  153. to_string(aFreeInternalHeapSizeBefore - aFreeInternalHeapSizeAfter) + ", lowest free: " + to_string(aMinFreeInternalHeapSize));
  154. return allSendsSuccessed;
  155. }
  156. bool publishSystemData(int qos) {
  157. bool allSendsSuccessed = false;
  158. if (!getMQTTisConnected()) {
  159. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to send System Topics, we are not connected to the MQTT broker!");
  160. return false;
  161. }
  162. char tmp_char[50];
  163. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing System MQTT topics...");
  164. int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  165. allSendsSuccessed |= MQTTPublish(maintopic + "/" + std::string(LWT_TOPIC), LWT_CONNECTED, qos, retainFlag); // Publish "connected" to maintopic/connection
  166. sprintf(tmp_char, "%ld", (long)getUpTime());
  167. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "uptime", std::string(tmp_char), qos, retainFlag);
  168. sprintf(tmp_char, "%lu", (long) getESPHeapSize());
  169. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "freeMem", std::string(tmp_char), qos, retainFlag);
  170. sprintf(tmp_char, "%d", get_WIFI_RSSI());
  171. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "wifiRSSI", std::string(tmp_char), qos, retainFlag);
  172. sprintf(tmp_char, "%d", (int)temperatureRead());
  173. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "CPUtemp", std::string(tmp_char), qos, retainFlag);
  174. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Successfully published all System MQTT topics");
  175. int aFreeInternalHeapSizeAfter = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  176. int aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  177. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Int. Heap Usage before publishing System Topics: " +
  178. to_string(aFreeInternalHeapSizeBefore) + ", after: " + to_string(aFreeInternalHeapSizeAfter) + ", delta: " +
  179. to_string(aFreeInternalHeapSizeBefore - aFreeInternalHeapSizeAfter) + ", lowest free: " + to_string(aMinFreeInternalHeapSize));
  180. return allSendsSuccessed;
  181. }
  182. bool publishStaticData(int qos) {
  183. bool allSendsSuccessed = false;
  184. if (!getMQTTisConnected()) {
  185. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Unable to send Static Topics, we are not connected to the MQTT broker!");
  186. return false;
  187. }
  188. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing static MQTT topics...");
  189. int aFreeInternalHeapSizeBefore = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  190. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "MAC", getMac(), qos, retainFlag);
  191. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "IP", *getIPAddress(), qos, retainFlag);
  192. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "hostname", wlan_config.hostname, qos, retainFlag);
  193. std::stringstream stream;
  194. stream << std::fixed << std::setprecision(1) << roundInterval; // minutes
  195. allSendsSuccessed |= MQTTPublish(maintopic + "/" + "interval", stream.str(), qos, retainFlag);
  196. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Successfully published all Static MQTT topics");
  197. int aFreeInternalHeapSizeAfter = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  198. int aMinFreeInternalHeapSize = heap_caps_get_minimum_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  199. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Int. Heap Usage before Publishing Static Topics: " +
  200. to_string(aFreeInternalHeapSizeBefore) + ", after: " + to_string(aFreeInternalHeapSizeAfter) + ", delta: " +
  201. to_string(aFreeInternalHeapSizeBefore - aFreeInternalHeapSizeAfter) + ", lowest free: " + to_string(aMinFreeInternalHeapSize));
  202. return allSendsSuccessed;
  203. }
  204. esp_err_t scheduleSendingDiscovery_and_static_Topics(httpd_req_t *req) {
  205. sendingOf_DiscoveryAndStaticTopics_scheduled = true;
  206. char msg[] = "MQTT Homeassistant Discovery and Static Topics scheduled";
  207. httpd_resp_send(req, msg, strlen(msg));
  208. return ESP_OK;
  209. }
  210. esp_err_t sendDiscovery_and_static_Topics(void) {
  211. bool success = false;
  212. if (!sendingOf_DiscoveryAndStaticTopics_scheduled) {
  213. // Flag not set, nothing to do
  214. return ESP_OK;
  215. }
  216. if (HomeassistantDiscovery) {
  217. success = MQTThomeassistantDiscovery(1);
  218. }
  219. success |= publishStaticData(1);
  220. if (success) { // Success, clear the flag
  221. sendingOf_DiscoveryAndStaticTopics_scheduled = false;
  222. return ESP_OK;
  223. }
  224. else {
  225. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "One or more MQTT topics failed to be published, will try sending them in the next round!");
  226. /* Keep sendingOf_DiscoveryAndStaticTopics_scheduled set so we can retry after the next round */
  227. return ESP_FAIL;
  228. }
  229. }
  230. void GotConnected(std::string maintopic, bool retainFlag) {
  231. // Nothing to do
  232. }
  233. void register_server_mqtt_uri(httpd_handle_t server) {
  234. httpd_uri_t uri = { };
  235. uri.method = HTTP_GET;
  236. uri.uri = "/mqtt_publish_discovery";
  237. uri.handler = scheduleSendingDiscovery_and_static_Topics;
  238. uri.user_ctx = (void*) "";
  239. httpd_register_uri_handler(server, &uri);
  240. }
  241. std::string getTimeUnit(void) {
  242. return timeUnit;
  243. }
  244. void SetHomeassistantDiscoveryEnabled(bool enabled) {
  245. HomeassistantDiscovery = enabled;
  246. }
  247. void setMqtt_Server_Retain(bool _retainFlag) {
  248. retainFlag = _retainFlag;
  249. }
  250. void mqttServer_setMainTopic( std::string _maintopic) {
  251. maintopic = _maintopic;
  252. }
  253. std::string mqttServer_getMainTopic() {
  254. return maintopic;
  255. }
  256. #endif //ENABLE_MQTT