server_mqtt.cpp 16 KB

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