ClassFlowMQTT.cpp 14 KB

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