ClassFlowMQTT.cpp 12 KB

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