ClassFlowMQTT.cpp 13 KB

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