ClassFlowMQTT.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. #include "defines.h"
  2. #include "ClassFlowMQTT.h"
  3. #include <sstream>
  4. #include <iomanip>
  5. #include <time.h>
  6. #include "Helper.h"
  7. #include "connect_wifi_sta.h"
  8. #include "read_network_config.h"
  9. #include "ClassLogFile.h"
  10. #include "time_sntp.h"
  11. #include "interface_mqtt.h"
  12. #include "ClassFlowPostProcessing.h"
  13. #include "ClassFlowControll.h"
  14. #include "server_mqtt.h"
  15. static const char *TAG = "MQTT";
  16. mqtt_controll_config_t mqtt_controll_config;
  17. extern const char *libfive_git_version(void);
  18. extern const char *libfive_git_revision(void);
  19. extern const char *libfive_git_branch(void);
  20. void ClassFlowMQTT::SetInitialParameter(void)
  21. {
  22. mqtt_controll_config.mqtt_enabled = false;
  23. mqtt_controll_config.mqtt_configOK = false;
  24. mqtt_controll_config.mqtt_initialized = false;
  25. mqtt_controll_config.mqtt_connected = false;
  26. mqtt_controll_config.HomeAssistantDiscovery = false;
  27. mqtt_controll_config.esp_mqtt_ID = MQTT_EVENT_ANY;
  28. mqtt_controll_config.uri = "";
  29. mqtt_controll_config.topic = "";
  30. mqtt_controll_config.topicError = "";
  31. mqtt_controll_config.topicRate = "";
  32. mqtt_controll_config.topicTimeStamp = "";
  33. mqtt_controll_config.maintopic = network_config.hostname;
  34. mqtt_controll_config.discoveryprefix = "homeassistant";
  35. mqtt_controll_config.topicUptime = "";
  36. mqtt_controll_config.topicFreeMem = "";
  37. mqtt_controll_config.caCertFilename = "";
  38. mqtt_controll_config.clientCertFilename = "";
  39. mqtt_controll_config.clientKeyFilename = "";
  40. mqtt_controll_config.validateServerCert = true;
  41. mqtt_controll_config.clientname = network_config.hostname;
  42. mqtt_controll_config.oldValue = "";
  43. mqtt_controll_config.user = "";
  44. mqtt_controll_config.password = "";
  45. mqtt_controll_config.lwt_topic = mqtt_controll_config.maintopic + "/" + LWT_TOPIC;
  46. mqtt_controll_config.lwt_connected = LWT_CONNECTED;
  47. mqtt_controll_config.lwt_disconnected = LWT_DISCONNECTED;
  48. mqtt_controll_config.meterType = "";
  49. mqtt_controll_config.valueUnit = "";
  50. mqtt_controll_config.timeUnit = "";
  51. mqtt_controll_config.rateUnit = "Unit/Minute";
  52. mqtt_controll_config.retainFlag = false;
  53. mqtt_controll_config.keepAlive = 25 * 60;
  54. mqtt_controll_config.domoticzintopic = "";
  55. flowpostprocessing = NULL;
  56. previousElement = NULL;
  57. ListFlowControll = NULL;
  58. disabled = false;
  59. }
  60. ClassFlowMQTT::ClassFlowMQTT(void)
  61. {
  62. SetInitialParameter();
  63. }
  64. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow *> *lfc)
  65. {
  66. SetInitialParameter();
  67. ListFlowControll = lfc;
  68. for (int i = 0; i < ListFlowControll->size(); ++i)
  69. {
  70. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  71. {
  72. flowpostprocessing = (ClassFlowPostProcessing *)(*ListFlowControll)[i];
  73. }
  74. }
  75. }
  76. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow *> *lfc, ClassFlow *_prev)
  77. {
  78. SetInitialParameter();
  79. previousElement = _prev;
  80. ListFlowControll = lfc;
  81. for (int i = 0; i < ListFlowControll->size(); ++i)
  82. {
  83. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  84. {
  85. flowpostprocessing = (ClassFlowPostProcessing *)(*ListFlowControll)[i];
  86. }
  87. }
  88. }
  89. bool ClassFlowMQTT::ReadParameter(FILE *pFile, std::string &aktparamgraph)
  90. {
  91. aktparamgraph = trim_string_left_right(aktparamgraph);
  92. if (aktparamgraph.size() == 0)
  93. {
  94. if (!GetNextParagraph(pFile, aktparamgraph))
  95. {
  96. return false;
  97. }
  98. }
  99. if ((to_upper(aktparamgraph).compare("[MQTT]") != 0) && (to_upper(aktparamgraph).compare(";[MQTT]") != 0))
  100. {
  101. // Paragraph does not fit MQTT
  102. return false;
  103. }
  104. if (aktparamgraph[0] == ';')
  105. {
  106. mqtt_controll_config.mqtt_enabled = false;
  107. while (getNextLine(pFile, &aktparamgraph) && !isNewParagraph(aktparamgraph));
  108. ESP_LOGD(TAG, "mqtt is disabled!");
  109. return true;
  110. }
  111. std::vector<std::string> splitted;
  112. while (getNextLine(pFile, &aktparamgraph) && !isNewParagraph(aktparamgraph))
  113. {
  114. splitted = split_line(aktparamgraph);
  115. if (splitted.size() > 1)
  116. {
  117. std::string _param = to_upper(GetParameterName(splitted[0]));
  118. if (_param == "CACERT")
  119. {
  120. mqtt_controll_config.caCertFilename = "/sdcard" + splitted[1];
  121. }
  122. else if (_param == "VALIDATESERVERCERT")
  123. {
  124. mqtt_controll_config.validateServerCert = alphanumeric_to_boolean(splitted[1]);
  125. }
  126. else if (_param == "CLIENTCERT")
  127. {
  128. mqtt_controll_config.clientCertFilename = "/sdcard" + splitted[1];
  129. }
  130. else if (_param == "CLIENTKEY")
  131. {
  132. mqtt_controll_config.clientKeyFilename = "/sdcard" + splitted[1];
  133. }
  134. else if (_param == "USER")
  135. {
  136. mqtt_controll_config.user = splitted[1];
  137. }
  138. else if (_param == "PASSWORD")
  139. {
  140. mqtt_controll_config.password = splitted[1];
  141. }
  142. else if (_param == "URI")
  143. {
  144. mqtt_controll_config.uri = splitted[1];
  145. }
  146. else if (_param == "RETAINMESSAGES")
  147. {
  148. mqtt_controll_config.retainFlag = alphanumeric_to_boolean(splitted[1]);
  149. }
  150. else if (_param == "HOMEASSISTANTDISCOVERY")
  151. {
  152. if (to_upper(splitted[1]) == "TRUE")
  153. {
  154. mqtt_controll_config.HomeAssistantDiscovery = true;
  155. }
  156. }
  157. else if (_param == "METERTYPE")
  158. {
  159. std::string _value = to_upper(splitted[1]);
  160. /* Use meter type for the device class
  161. Make sure it is a listed one on https://developers.home-assistant.io/docs/core/entity/sensor/#available-device-classes */
  162. if (_value == "WATER_M3")
  163. {
  164. SetMeterType("water", "m³", "h", "m³/h");
  165. }
  166. else if (_value == "WATER_L")
  167. {
  168. SetMeterType("water", "L", "h", "L/h");
  169. }
  170. else if (_value == "WATER_FT3")
  171. {
  172. SetMeterType("water", "ft³", "min", "ft³/min"); // min = Minutes
  173. }
  174. else if (_value == "WATER_GAL")
  175. {
  176. SetMeterType("water", "gal", "h", "gal/h");
  177. }
  178. else if (_value == "WATER_GAL_MIN")
  179. {
  180. SetMeterType("water", "gal", "min", "gal/min"); // min = Minutes
  181. }
  182. else if (_value == "GAS_M3")
  183. {
  184. SetMeterType("gas", "m³", "h", "m³/h");
  185. }
  186. else if (_value == "GAS_FT3")
  187. {
  188. SetMeterType("gas", "ft³", "min", "ft³/min"); // min = Minutes
  189. }
  190. else if (_value == "ENERGY_WH")
  191. {
  192. SetMeterType("energy", "Wh", "h", "W");
  193. }
  194. else if (_value == "ENERGY_KWH")
  195. {
  196. SetMeterType("energy", "kWh", "h", "kW");
  197. }
  198. else if (_value == "ENERGY_MWH")
  199. {
  200. SetMeterType("energy", "MWh", "h", "MW");
  201. }
  202. else if (_value == "ENERGY_GJ")
  203. {
  204. SetMeterType("energy", "GJ", "h", "GJ/h");
  205. }
  206. else if (_value == "TEMPERATURE_C")
  207. {
  208. SetMeterType("temperature", "°C", "min", "°C/min"); // min = Minutes
  209. }
  210. else if (_value == "TEMPERATURE_F")
  211. {
  212. SetMeterType("temperature", "°F", "min", "°F/min"); // min = Minutes
  213. }
  214. else if (_value == "TEMPERATURE_K")
  215. {
  216. SetMeterType("temperature", "K", "min", "K/m"); // min = Minutes
  217. }
  218. }
  219. else if (_param == "CLIENTID")
  220. {
  221. mqtt_controll_config.clientname = splitted[1];
  222. }
  223. else if ((_param == "TOPIC") || (_param == "MAINTOPIC"))
  224. {
  225. mqtt_controll_config.maintopic = splitted[1];
  226. }
  227. else if (_param == "DISCOVERYPREFIX")
  228. {
  229. mqtt_controll_config.discoveryprefix = splitted[1];
  230. }
  231. else if (_param == "DOMOTICZTOPICIN")
  232. {
  233. mqtt_controll_config.domoticzintopic = splitted[1];
  234. }
  235. else if (_param == "DOMOTICZIDX")
  236. {
  237. handleIdx(splitted[0], splitted[1]);
  238. }
  239. }
  240. }
  241. if ((mqtt_controll_config.uri.length() > 0) && (mqtt_controll_config.user.length() > 0))
  242. {
  243. /* Note:
  244. * Originally, we started the MQTT client here.
  245. * How ever we need the interval parameter from the ClassFlowControl, but that only gets started later.
  246. * To work around this, we delay the start and trigger it from ClassFlowControl::ReadParameter() */
  247. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init MQTT with uri: " + mqtt_controll_config.uri + ", user: " + mqtt_controll_config.user);
  248. if (mqtt_controll_config.domoticzintopic.length() > 0)
  249. {
  250. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init MQTT with domoticzintopic: " + mqtt_controll_config.domoticzintopic);
  251. }
  252. mqtt_controll_config.mqtt_enabled = true;
  253. }
  254. else
  255. {
  256. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "MQTT init skipped as we are missing some parameters");
  257. }
  258. return true;
  259. }
  260. void ClassFlowMQTT::SetMeterType(std::string _meterType, std::string _valueUnit, std::string _timeUnit, std::string _rateUnit)
  261. {
  262. mqtt_controll_config.meterType = _meterType;
  263. mqtt_controll_config.valueUnit = _valueUnit;
  264. mqtt_controll_config.timeUnit = _timeUnit;
  265. mqtt_controll_config.rateUnit = _rateUnit;
  266. }
  267. bool ClassFlowMQTT::Start(float AutoInterval)
  268. {
  269. mqtt_controll_config.roundInterval = AutoInterval; // Minutes
  270. mqtt_controll_config.keepAlive = mqtt_controll_config.roundInterval * 60 * 2.5; // Seconds, make sure it is greater thatn 2 rounds!
  271. mqttServer_setParameter(flowpostprocessing->GetNumbers());
  272. if (!MQTT_Configure((void *)&GotConnected))
  273. {
  274. return false;
  275. }
  276. return (MQTT_Init() == 1);
  277. }
  278. bool ClassFlowMQTT::doFlow(std::string time)
  279. {
  280. int qos = 1;
  281. std::string value_temp = "";
  282. std::string error_message_text_temp = "";
  283. std::string raw_value_temp = "";
  284. // std::string pre_value_temp = "";
  285. std::string rate_value_temp = ""; // Always Unit / Minute
  286. std::string time_stamp_temp = "";
  287. std::string change_absolute_temp = "";
  288. /* Send the the Homeassistant Discovery and the Static Topics in case they where scheduled */
  289. sendDiscovery_and_static_Topics();
  290. bool success = publishSystemData(qos);
  291. if (flowpostprocessing && getMQTTisConnected())
  292. {
  293. std::vector<NumberPost *> *NUMBERS = flowpostprocessing->GetNumbers();
  294. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing MQTT topics...");
  295. for (int i = 0; i < (*NUMBERS).size(); ++i)
  296. {
  297. value_temp = (*NUMBERS)[i]->ReturnValue;
  298. raw_value_temp = (*NUMBERS)[i]->ReturnRawValue;
  299. // pre_value_temp = (*NUMBERS)[i]->ReturnPreValue;
  300. error_message_text_temp = (*NUMBERS)[i]->ErrorMessageText;
  301. rate_value_temp = (*NUMBERS)[i]->ReturnRateValue; // Unit per minutes
  302. change_absolute_temp = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
  303. time_stamp_temp = (*NUMBERS)[i]->timeStamp;
  304. std::string DomoticzIdx = (*NUMBERS)[i]->DomoticzIdx;
  305. std::string domoticzpayload = "{\"command\":\"udevice\",\"idx\":" + DomoticzIdx + ",\"svalue\":\"" + value_temp + "\"}";
  306. std::string name_temp = (*NUMBERS)[i]->name;
  307. if (name_temp == "default")
  308. {
  309. // e.g. watermeter/default/
  310. name_temp = mqtt_controll_config.maintopic + "/";
  311. }
  312. else
  313. {
  314. // e.g. watermeter/main/
  315. name_temp = mqtt_controll_config.maintopic + "/" + name_temp + "/";
  316. }
  317. if ((mqtt_controll_config.domoticzintopic.length() > 0) && (value_temp.length() > 0))
  318. {
  319. success |= MQTTPublish(mqtt_controll_config.domoticzintopic, domoticzpayload, qos, mqtt_controll_config.retainFlag);
  320. }
  321. if (value_temp.length() > 0)
  322. {
  323. success |= MQTTPublish(name_temp + "value", value_temp, qos, mqtt_controll_config.retainFlag);
  324. }
  325. if (error_message_text_temp.length() > 0)
  326. {
  327. success |= MQTTPublish(name_temp + "error", error_message_text_temp, qos, mqtt_controll_config.retainFlag);
  328. }
  329. if (rate_value_temp.length() > 0)
  330. {
  331. success |= MQTTPublish(name_temp + "rate", rate_value_temp, qos, mqtt_controll_config.retainFlag);
  332. std::string resultRatePerTimeUnit;
  333. if (mqtt_controll_config.timeUnit == "h")
  334. {
  335. // Need conversion to be per hour
  336. resultRatePerTimeUnit = resultRatePerTimeUnit = to_string((*NUMBERS)[i]->FlowRateAct * 60); // per minutes => per hour
  337. }
  338. else
  339. {
  340. // Keep per minute
  341. resultRatePerTimeUnit = rate_value_temp;
  342. }
  343. success |= MQTTPublish(name_temp + "rate_per_time_unit", resultRatePerTimeUnit, qos, mqtt_controll_config.retainFlag);
  344. }
  345. if (change_absolute_temp.length() > 0)
  346. {
  347. // e.g. _key = watermeter/main/changeabsolut, _content = change_absolute_temp, _qos = 1, retained_flag = mqtt_controll_config.retainFlag
  348. success |= MQTTPublish(name_temp + "changeabsolut", change_absolute_temp, qos, mqtt_controll_config.retainFlag); // Legacy API
  349. success |= MQTTPublish(name_temp + "rate_per_digitization_round", change_absolute_temp, qos, mqtt_controll_config.retainFlag);
  350. }
  351. if (raw_value_temp.length() > 0)
  352. {
  353. success |= MQTTPublish(name_temp + "raw", raw_value_temp, qos, mqtt_controll_config.retainFlag);
  354. }
  355. if (time_stamp_temp.length() > 0)
  356. {
  357. success |= MQTTPublish(name_temp + "timestamp", time_stamp_temp, qos, mqtt_controll_config.retainFlag);
  358. }
  359. std::string json = flowpostprocessing->getJsonFromNumber(i, "\n");
  360. success |= MQTTPublish(name_temp + "json", json, qos, mqtt_controll_config.retainFlag);
  361. }
  362. }
  363. mqtt_controll_config.oldValue = value_temp;
  364. if (!success)
  365. {
  366. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "One or more MQTT topics failed to be published!");
  367. }
  368. return true;
  369. }
  370. void ClassFlowMQTT::handleIdx(std::string _decsep, std::string _value)
  371. {
  372. std::string _digit;
  373. int _pospunkt = _decsep.find_first_of(".");
  374. if (_pospunkt > -1)
  375. {
  376. _digit = _decsep.substr(0, _pospunkt);
  377. }
  378. else
  379. {
  380. _digit = "default";
  381. }
  382. for (int j = 0; j < flowpostprocessing->NUMBERS.size(); ++j)
  383. {
  384. // Set to default first (if nothing else is set)
  385. if ((_digit == "default") || (flowpostprocessing->NUMBERS[j]->name == _digit))
  386. {
  387. flowpostprocessing->NUMBERS[j]->DomoticzIdx = _value;
  388. }
  389. }
  390. }