ClassFlowMQTT.cpp 12 KB

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