ClassFlowMQTT.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. #include <sstream>
  2. #include "ClassFlowMQTT.h"
  3. #include "Helper.h"
  4. #include "connect_wlan.h"
  5. #include "ClassLogFile.h"
  6. #include "time_sntp.h"
  7. #include "interface_mqtt.h"
  8. #include "ClassFlowPostProcessing.h"
  9. #include "ClassFlowControll.h"
  10. #include <time.h>
  11. #define __HIDE_PASSWORD
  12. //static const char *TAG = "class_flow_MQTT";
  13. #define LWT_TOPIC "connection"
  14. #define LWT_CONNECTED "connected"
  15. #define LWT_DISCONNECTED "connection lost"
  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 float AutoIntervalShared;
  20. std::vector<NumberPost*>* NUMBERS;
  21. bool HomeassistantDiscovery = false;
  22. void sendHomeAssistantDiscoveryTopic(std::string maintopic, std::string group, std::string field,
  23. std::string name, std::string icon, std::string unit, std::string deviceClass, std::string stateClass) {
  24. std::string version = std::string(libfive_git_version());
  25. if (version == "") {
  26. version = std::string(libfive_git_branch()) + " (" + std::string(libfive_git_revision()) + ")";
  27. }
  28. std::string topic;
  29. std::string topicFull;
  30. std::string topicT;
  31. std::string payload;
  32. std::string nl = "\n";
  33. if (group == "") {
  34. topic = field;
  35. topicT = field;
  36. }
  37. else {
  38. topic = group + "/" + field;
  39. topicT = group + "_" + field;
  40. }
  41. if (group != "") { // Prepend the group to the name
  42. name = group + " " + name;
  43. }
  44. topicFull = "homeassistant/sensor/" + maintopic + "/" + topicT + "/config";
  45. /* See https://www.home-assistant.io/docs/mqtt/discovery/ */
  46. payload = "{" + nl +
  47. "\"~\": \"" + maintopic + "\"," + nl +
  48. "\"unique_id\": \"" + maintopic + "-" + topicT + "\"," + nl +
  49. "\"object_id\": \"" + maintopic + "_" + topicT + "\"," + nl + // This used to generate the Entity ID
  50. "\"name\": \"" + name + "\"," + nl +
  51. "\"icon\": \"mdi:" + icon + "\"," + nl;
  52. if (group != "") {
  53. if (field == "problem") { // Special binary sensor which is based on error topic
  54. payload += "\"state_topic\": \"~/" + group + "/error\"," + nl;
  55. payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\"," + nl;
  56. }
  57. else {
  58. payload += "\"state_topic\": \"~/" + group + "/" + field + "\"," + nl;
  59. }
  60. }
  61. else {
  62. payload += "\"state_topic\": \"~/" + field + "\"," + nl;
  63. }
  64. if (unit != "") {
  65. payload += "\"unit_of_meas\": \"" + unit + "\"," + nl;
  66. }
  67. if (deviceClass != "") {
  68. payload += "\"device_class\": \"" + deviceClass + "\"," + nl;
  69. /* if (deviceClass == "problem") {
  70. payload += "\"value_template\": \"{{ 'OFF' if 'no error' in value else 'ON'}}\"," + nl;
  71. }*/
  72. }
  73. if (stateClass != "") {
  74. payload += "\"state_class\": \"" + stateClass + "\"," + nl;
  75. }
  76. payload +=
  77. "\"availability_topic\": \"~/" + std::string(LWT_TOPIC) + "\"," + nl +
  78. "\"payload_available\": \"" + LWT_CONNECTED + "\"," + nl +
  79. "\"payload_not_available\": \"" + LWT_DISCONNECTED + "\"," + nl;
  80. payload +=
  81. "\"device\": {" + nl +
  82. "\"identifiers\": [\"" + maintopic + "\"]," + nl +
  83. "\"name\": \"" + maintopic + "\"," + nl +
  84. "\"model\": \"Meter Digitizer\"," + nl +
  85. "\"manufacturer\": \"AI on the Edge Device\"," + nl +
  86. "\"sw_version\": \"" + version + "\"," + nl +
  87. "\"configuration_url\": \"http://" + *getIPAddress() + "\"" + nl +
  88. "}" + nl +
  89. "}" + nl;
  90. MQTTPublish(topicFull, payload, true);
  91. }
  92. void MQTThomeassistantDiscovery(std::string maintopic) {
  93. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT - Sending Homeassistant Discovery Topics...");
  94. // maintopic group field User Friendly Name icon unit Device Class State Class
  95. sendHomeAssistantDiscoveryTopic(maintopic, "", "uptime", "Uptime", "clock-time-eight-outline", "s", "", "");
  96. sendHomeAssistantDiscoveryTopic(maintopic, "", "IP", "IP", "network-outline", "", "", "");
  97. sendHomeAssistantDiscoveryTopic(maintopic, "", "MAC", "MAC Address", "network-outline", "", "", "");
  98. sendHomeAssistantDiscoveryTopic(maintopic, "", "hostname", "Hostname", "network-outline", "", "", "");
  99. sendHomeAssistantDiscoveryTopic(maintopic, "", "freeMem", "Free Memory", "memory", "B", "", "measurement");
  100. sendHomeAssistantDiscoveryTopic(maintopic, "", "wifiRSSI", "Wi-Fi RSSI", "wifi", "dBm", "signal_strength", "");
  101. sendHomeAssistantDiscoveryTopic(maintopic, "", "CPUtemp", "CPU Temperature", "thermometer", "°C", "temperature", "measurement");
  102. for (int i = 0; i < (*NUMBERS).size(); ++i) {
  103. // maintopic group field User Friendly Name icon unit Device Class State Class
  104. sendHomeAssistantDiscoveryTopic(maintopic, (*NUMBERS)[i]->name, "value", "Value", "gauge", "", "", "total_increasing");
  105. sendHomeAssistantDiscoveryTopic(maintopic, (*NUMBERS)[i]->name, "error", "Error", "alert-circle-outline", "", "", "");
  106. sendHomeAssistantDiscoveryTopic(maintopic, (*NUMBERS)[i]->name, "rate", "Rate", "swap-vertical", "", "", "");
  107. sendHomeAssistantDiscoveryTopic(maintopic, (*NUMBERS)[i]->name, "changeabsolut", "Absolute Change", "arrow-expand-vertical", "", "", "measurement");
  108. sendHomeAssistantDiscoveryTopic(maintopic, (*NUMBERS)[i]->name, "raw", "Raw Value", "raw", "", "", "total_increasing");
  109. sendHomeAssistantDiscoveryTopic(maintopic, (*NUMBERS)[i]->name, "timestamp", "Timestamp", "clock-time-eight-outline", "", "timestamp", "");
  110. sendHomeAssistantDiscoveryTopic(maintopic, (*NUMBERS)[i]->name, "json", "JSON", "code-json", "", "", "");
  111. sendHomeAssistantDiscoveryTopic(maintopic, (*NUMBERS)[i]->name, "problem", "Problem", "alert-outline", "", "", ""); // Special binary sensor which is based on error topic
  112. }
  113. }
  114. void publishRuntimeData(std::string maintopic, int SetRetainFlag) {
  115. char tmp_char[50];
  116. sprintf(tmp_char, "%ld", (long)getUpTime());
  117. MQTTPublish(maintopic + "/" + "uptime", std::string(tmp_char), SetRetainFlag);
  118. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0))
  119. sprintf(tmp_char, "%lu", esp_get_free_heap_size());
  120. #else
  121. sprintf(tmp_char, "%zu", esp_get_free_heap_size());
  122. #endif
  123. MQTTPublish(maintopic + "/" + "freeMem", std::string(tmp_char), SetRetainFlag);
  124. sprintf(tmp_char, "%d", get_WIFI_RSSI());
  125. MQTTPublish(maintopic + "/" + "wifiRSSI", std::string(tmp_char), SetRetainFlag);
  126. sprintf(tmp_char, "%d", (int)temperatureRead());
  127. MQTTPublish(maintopic + "/" + "CPUtemp", std::string(tmp_char), SetRetainFlag);
  128. }
  129. void GotConnected(std::string maintopic, int SetRetainFlag) {
  130. if (HomeassistantDiscovery) {
  131. MQTThomeassistantDiscovery(maintopic);
  132. }
  133. MQTTPublish(maintopic + "/" + "MAC", getMac(), SetRetainFlag);
  134. MQTTPublish(maintopic + "/" + "IP", *getIPAddress(), SetRetainFlag);
  135. MQTTPublish(maintopic + "/" + "hostname", hostname, SetRetainFlag);
  136. publishRuntimeData(maintopic, SetRetainFlag);
  137. }
  138. void ClassFlowMQTT::SetInitialParameter(void)
  139. {
  140. uri = "";
  141. topic = "";
  142. topicError = "";
  143. topicRate = "";
  144. topicTimeStamp = "";
  145. maintopic = hostname;
  146. topicUptime = "";
  147. topicFreeMem = "";
  148. clientname = "AIOTED-" + getMac();
  149. OldValue = "";
  150. flowpostprocessing = NULL;
  151. user = "";
  152. password = "";
  153. SetRetainFlag = 0;
  154. previousElement = NULL;
  155. ListFlowControll = NULL;
  156. disabled = false;
  157. keepAlive = 25*60;
  158. }
  159. ClassFlowMQTT::ClassFlowMQTT()
  160. {
  161. SetInitialParameter();
  162. }
  163. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow*>* lfc)
  164. {
  165. SetInitialParameter();
  166. ListFlowControll = lfc;
  167. for (int i = 0; i < ListFlowControll->size(); ++i)
  168. {
  169. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  170. {
  171. flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
  172. }
  173. }
  174. NUMBERS = flowpostprocessing->GetNumbers();
  175. keepAlive = AutoIntervalShared * 60 * 2.5; // TODO find better way to access AutoIntervall in ClassFlowControll
  176. LogFile.WriteToFile(ESP_LOG_INFO, "Digitizer interval is " + std::to_string(AutoIntervalShared) +
  177. " minutes => setting MQTT LWT timeout to " + std::to_string(keepAlive/60) + " minutes.");
  178. }
  179. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow*>* lfc, ClassFlow *_prev)
  180. {
  181. SetInitialParameter();
  182. previousElement = _prev;
  183. ListFlowControll = lfc;
  184. for (int i = 0; i < ListFlowControll->size(); ++i)
  185. {
  186. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  187. {
  188. flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
  189. }
  190. }
  191. }
  192. bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
  193. {
  194. std::vector<string> zerlegt;
  195. aktparamgraph = trim(aktparamgraph);
  196. if (aktparamgraph.size() == 0)
  197. if (!this->GetNextParagraph(pfile, aktparamgraph))
  198. return false;
  199. if (toUpper(aktparamgraph).compare("[MQTT]") != 0) // Paragraph passt nich zu MakeImage
  200. return false;
  201. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
  202. {
  203. zerlegt = this->ZerlegeZeile(aktparamgraph);
  204. if ((toUpper(zerlegt[0]) == "USER") && (zerlegt.size() > 1))
  205. {
  206. this->user = zerlegt[1];
  207. }
  208. if ((toUpper(zerlegt[0]) == "PASSWORD") && (zerlegt.size() > 1))
  209. {
  210. this->password = zerlegt[1];
  211. }
  212. if ((toUpper(zerlegt[0]) == "URI") && (zerlegt.size() > 1))
  213. {
  214. this->uri = zerlegt[1];
  215. }
  216. if ((toUpper(zerlegt[0]) == "SETRETAINFLAG") && (zerlegt.size() > 1))
  217. {
  218. if (toUpper(zerlegt[1]) == "TRUE")
  219. SetRetainFlag = 1;
  220. }
  221. if ((toUpper(zerlegt[0]) == "HOMEASSISTANTDISCOVERY") && (zerlegt.size() > 1))
  222. {
  223. if (toUpper(zerlegt[1]) == "TRUE")
  224. HomeassistantDiscovery = true;
  225. }
  226. if ((toUpper(zerlegt[0]) == "CLIENTID") && (zerlegt.size() > 1))
  227. {
  228. this->clientname = zerlegt[1];
  229. }
  230. if (((toUpper(zerlegt[0]) == "TOPIC") || (toUpper(zerlegt[0]) == "MAINTOPIC")) && (zerlegt.size() > 1))
  231. {
  232. maintopic = zerlegt[1];
  233. }
  234. }
  235. MQTT_Configure(uri, clientname, user, password, maintopic, LWT_TOPIC, LWT_CONNECTED, LWT_DISCONNECTED, keepAlive, SetRetainFlag, (void *)&GotConnected);
  236. if (!MQTT_Init()) {
  237. if (!MQTT_Init()) { // Retry
  238. return false;
  239. }
  240. }
  241. return true;
  242. }
  243. string ClassFlowMQTT::GetMQTTMainTopic()
  244. {
  245. return maintopic;
  246. }
  247. bool ClassFlowMQTT::doFlow(string zwtime)
  248. {
  249. std::string result;
  250. std::string resulterror = "";
  251. std::string resultraw = "";
  252. std::string resultrate = "";
  253. std::string resulttimestamp = "";
  254. std::string resultchangabs = "";
  255. string zw = "";
  256. string namenumber = "";
  257. publishRuntimeData(maintopic, SetRetainFlag);
  258. if (flowpostprocessing)
  259. {
  260. std::vector<NumberPost*>* NUMBERS = flowpostprocessing->GetNumbers();
  261. for (int i = 0; i < (*NUMBERS).size(); ++i)
  262. {
  263. result = (*NUMBERS)[i]->ReturnValue;
  264. resultraw = (*NUMBERS)[i]->ReturnRawValue;
  265. resulterror = (*NUMBERS)[i]->ErrorMessageText;
  266. resultrate = (*NUMBERS)[i]->ReturnRateValue;
  267. resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute;
  268. resulttimestamp = (*NUMBERS)[i]->timeStamp;
  269. namenumber = (*NUMBERS)[i]->name;
  270. if (namenumber == "default")
  271. namenumber = maintopic + "/";
  272. else
  273. namenumber = maintopic + "/" + namenumber + "/";
  274. if (result.length() > 0)
  275. MQTTPublish(namenumber + "value", result, SetRetainFlag);
  276. if (resulterror.length() > 0)
  277. MQTTPublish(namenumber + "error", resulterror, SetRetainFlag);
  278. if (resultrate.length() > 0)
  279. MQTTPublish(namenumber + "rate", resultrate, SetRetainFlag);
  280. if (resultchangabs.length() > 0)
  281. MQTTPublish(namenumber + "changeabsolut", resultchangabs, SetRetainFlag);
  282. if (resultraw.length() > 0)
  283. MQTTPublish(namenumber + "raw", resultraw, SetRetainFlag);
  284. if (resulttimestamp.length() > 0)
  285. MQTTPublish(namenumber + "timestamp", resulttimestamp, SetRetainFlag);
  286. std::string json = "";
  287. if (result.length() > 0)
  288. json += "{\"value\":"+result;
  289. else
  290. json += "{\"value\":\"\"";
  291. json += ",\"raw\":\""+resultraw;
  292. json += "\",\"error\":\""+resulterror;
  293. if (resultrate.length() > 0)
  294. json += "\",\"rate\":"+resultrate;
  295. else
  296. json += "\",\"rate\":\"\"";
  297. json += ",\"timestamp\":\""+resulttimestamp+"\"}";
  298. MQTTPublish(namenumber + "json", json, SetRetainFlag);
  299. }
  300. }
  301. else
  302. {
  303. for (int i = 0; i < ListFlowControll->size(); ++i)
  304. {
  305. zw = (*ListFlowControll)[i]->getReadout();
  306. if (zw.length() > 0)
  307. {
  308. if (result.length() == 0)
  309. result = zw;
  310. else
  311. result = result + "\t" + zw;
  312. }
  313. }
  314. MQTTPublish(topic, result, SetRetainFlag);
  315. }
  316. OldValue = result;
  317. return true;
  318. }