ClassFlowMQTT.cpp 14 KB

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