ClassFlowMQTT.cpp 13 KB

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