ClassFlowMQTT.cpp 12 KB

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