ClassFlowMQTT.cpp 12 KB

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