ClassFlowMQTT.cpp 14 KB

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