ClassFlowMQTT.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. #ifdef ENABLE_MQTT
  2. #include <sstream>
  3. #include <iomanip>
  4. #include "ClassFlowMQTT.h"
  5. #include "Helper.h"
  6. #include "connect_wlan.h"
  7. #include "read_wlanini.h"
  8. #include "ClassLogFile.h"
  9. #include "time_sntp.h"
  10. #include "interface_mqtt.h"
  11. #include "ClassFlowPostProcessing.h"
  12. #include "ClassFlowControll.h"
  13. #include "server_mqtt.h"
  14. #include <time.h>
  15. #include "../../include/defines.h"
  16. static const char *TAG = "MQTT";
  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. uri = "";
  23. topic = "";
  24. topicError = "";
  25. topicRate = "";
  26. topicTimeStamp = "";
  27. maintopic = wlan_config.hostname;
  28. topicUptime = "";
  29. topicFreeMem = "";
  30. caCertFilename = "";
  31. clientCertFilename = "";
  32. clientKeyFilename = "";
  33. validateServerCert = true;
  34. clientname = wlan_config.hostname;
  35. OldValue = "";
  36. flowpostprocessing = NULL;
  37. user = "";
  38. password = "";
  39. SetRetainFlag = false;
  40. previousElement = NULL;
  41. ListFlowControll = NULL;
  42. disabled = false;
  43. keepAlive = 25*60;
  44. domoticzintopic = "";
  45. }
  46. ClassFlowMQTT::ClassFlowMQTT()
  47. {
  48. SetInitialParameter();
  49. }
  50. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow*>* lfc)
  51. {
  52. SetInitialParameter();
  53. ListFlowControll = lfc;
  54. for (int i = 0; i < ListFlowControll->size(); ++i)
  55. {
  56. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  57. {
  58. flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
  59. }
  60. }
  61. }
  62. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow*>* lfc, ClassFlow *_prev)
  63. {
  64. SetInitialParameter();
  65. previousElement = _prev;
  66. ListFlowControll = lfc;
  67. for (int i = 0; i < ListFlowControll->size(); ++i)
  68. {
  69. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  70. {
  71. flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
  72. }
  73. }
  74. }
  75. bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
  76. {
  77. std::vector<string> splitted;
  78. aktparamgraph = trim(aktparamgraph);
  79. if (aktparamgraph.size() == 0)
  80. if (!this->GetNextParagraph(pfile, aktparamgraph))
  81. return false;
  82. if (toUpper(aktparamgraph).compare("[MQTT]") != 0) // Paragraph does not fit MQTT
  83. return false;
  84. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
  85. {
  86. splitted = ZerlegeZeile(aktparamgraph);
  87. std::string _param = GetParameterName(splitted[0]);
  88. if ((toUpper(_param) == "CACERT") && (splitted.size() > 1))
  89. {
  90. this->caCertFilename = "/sdcard" + splitted[1];
  91. }
  92. if ((toUpper(_param) == "VALIDATESERVERCERT") && (splitted.size() > 1))
  93. {
  94. validateServerCert = alphanumericToBoolean(splitted[1]);
  95. }
  96. if ((toUpper(_param) == "CLIENTCERT") && (splitted.size() > 1))
  97. {
  98. this->clientCertFilename = "/sdcard" + splitted[1];
  99. }
  100. if ((toUpper(_param) == "CLIENTKEY") && (splitted.size() > 1))
  101. {
  102. this->clientKeyFilename = "/sdcard" + splitted[1];
  103. }
  104. if ((toUpper(_param) == "USER") && (splitted.size() > 1))
  105. {
  106. this->user = splitted[1];
  107. }
  108. if ((toUpper(_param) == "PASSWORD") && (splitted.size() > 1))
  109. {
  110. this->password = splitted[1];
  111. }
  112. if ((toUpper(_param) == "URI") && (splitted.size() > 1))
  113. {
  114. this->uri = splitted[1];
  115. }
  116. if ((toUpper(_param) == "RETAINMESSAGES") && (splitted.size() > 1))
  117. {
  118. SetRetainFlag = alphanumericToBoolean(splitted[1]);
  119. setMqtt_Server_Retain(SetRetainFlag);
  120. }
  121. if ((toUpper(_param) == "HOMEASSISTANTDISCOVERY") && (splitted.size() > 1))
  122. {
  123. if (toUpper(splitted[1]) == "TRUE")
  124. SetHomeassistantDiscoveryEnabled(true);
  125. }
  126. if ((toUpper(_param) == "METERTYPE") && (splitted.size() > 1)) {
  127. /* Use meter type for the device class
  128. Make sure it is a listed one on https://developers.home-assistant.io/docs/core/entity/sensor/#available-device-classes */
  129. if (toUpper(splitted[1]) == "WATER_M3") {
  130. mqttServer_setMeterType("water", "m³", "h", "m³/h");
  131. }
  132. else if (toUpper(splitted[1]) == "WATER_L") {
  133. mqttServer_setMeterType("water", "L", "h", "L/h");
  134. }
  135. else if (toUpper(splitted[1]) == "WATER_FT3") {
  136. mqttServer_setMeterType("water", "ft³", "m", "ft³/m"); // m = Minutes
  137. }
  138. else if (toUpper(splitted[1]) == "WATER_GAL") {
  139. mqttServer_setMeterType("water", "gal", "h", "gal/h");
  140. }
  141. else if (toUpper(splitted[1]) == "GAS_M3") {
  142. mqttServer_setMeterType("gas", "m³", "h", "m³/h");
  143. }
  144. else if (toUpper(splitted[1]) == "GAS_FT3") {
  145. mqttServer_setMeterType("gas", "ft³", "m", "ft³/m"); // m = Minutes
  146. }
  147. else if (toUpper(splitted[1]) == "ENERGY_WH") {
  148. mqttServer_setMeterType("energy", "Wh", "h", "W");
  149. }
  150. else if (toUpper(splitted[1]) == "ENERGY_KWH") {
  151. mqttServer_setMeterType("energy", "kWh", "h", "kW");
  152. }
  153. else if (toUpper(splitted[1]) == "ENERGY_MWH") {
  154. mqttServer_setMeterType("energy", "MWh", "h", "MW");
  155. }
  156. else if (toUpper(splitted[1]) == "ENERGY_GJ") {
  157. mqttServer_setMeterType("energy", "GJ", "h", "GJ/h");
  158. }
  159. else if (toUpper(splitted[1]) == "TEMPERATURE_C") {
  160. mqttServer_setMeterType("temperature", "°C", "m", "°C/m"); // m = Minutes
  161. }
  162. else if (toUpper(splitted[1]) == "TEMPERATURE_F") {
  163. mqttServer_setMeterType("temperature", "°F", "m", "°F/m"); // m = Minutes
  164. }
  165. else if (toUpper(splitted[1]) == "TEMPERATURE_K") {
  166. mqttServer_setMeterType("temperature", "K", "m", "K/m"); // m = Minutes
  167. }
  168. }
  169. if ((toUpper(_param) == "CLIENTID") && (splitted.size() > 1))
  170. {
  171. this->clientname = splitted[1];
  172. }
  173. if (((toUpper(_param) == "TOPIC") || (toUpper(splitted[0]) == "MAINTOPIC")) && (splitted.size() > 1))
  174. {
  175. maintopic = splitted[1];
  176. }
  177. if (((toUpper(_param) == "DOMOTICZTOPICIN")) && (splitted.size() > 1))
  178. {
  179. this->domoticzintopic = splitted[1];
  180. }
  181. if (((toUpper(_param) == "DOMOTICZIDX")) && (splitted.size() > 1))
  182. {
  183. handleIdx(splitted[0], splitted[1]);
  184. }
  185. }
  186. /* Note:
  187. * Originally, we started the MQTT client here.
  188. * How ever we need the interval parameter from the ClassFlowControll, but that only gets started later.
  189. * To work around this, we delay the start and trigger it from ClassFlowControll::ReadParameter() */
  190. mqttServer_setMainTopic(maintopic);
  191. mqttServer_setDmoticzInTopic(domoticzintopic);
  192. return true;
  193. }
  194. bool ClassFlowMQTT::Start(float AutoInterval)
  195. {
  196. roundInterval = AutoInterval; // Minutes
  197. keepAlive = roundInterval * 60 * 2.5; // Seconds, make sure it is greater thatn 2 rounds!
  198. std::stringstream stream;
  199. stream << std::fixed << std::setprecision(1) << "Digitizer interval is " << roundInterval <<
  200. " minutes => setting MQTT LWT timeout to " << ((float)keepAlive/60) << " minutes.";
  201. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, stream.str());
  202. mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval);
  203. bool MQTTConfigCheck = MQTT_Configure(uri, clientname, user, password, maintopic, domoticzintopic, LWT_TOPIC, LWT_CONNECTED,
  204. LWT_DISCONNECTED, caCertFilename, validateServerCert, clientCertFilename, clientKeyFilename,
  205. keepAlive, SetRetainFlag, (void *)&GotConnected);
  206. if (!MQTTConfigCheck) {
  207. return false;
  208. }
  209. return (MQTT_Init() == 1);
  210. }
  211. bool ClassFlowMQTT::doFlow(string zwtime)
  212. {
  213. bool success;
  214. std::string result;
  215. std::string resulterror = "";
  216. std::string resultraw = "";
  217. std::string resultpre = "";
  218. std::string resultrate = ""; // Always Unit / Minute
  219. std::string resultRatePerTimeUnit = ""; // According to selection
  220. std::string resulttimestamp = "";
  221. std::string resultchangabs = "";
  222. string zw = "";
  223. string namenumber = "";
  224. string domoticzpayload = "";
  225. string DomoticzIdx = "";
  226. int qos = 1;
  227. /* Send the the Homeassistant Discovery and the Static Topics in case they where scheduled */
  228. sendDiscovery_and_static_Topics();
  229. success = publishSystemData(qos);
  230. if (flowpostprocessing && getMQTTisConnected())
  231. {
  232. std::vector<NumberPost*>* NUMBERS = flowpostprocessing->GetNumbers();
  233. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing MQTT topics...");
  234. for (int i = 0; i < (*NUMBERS).size(); ++i)
  235. {
  236. result = (*NUMBERS)[i]->ReturnValue;
  237. resultraw = (*NUMBERS)[i]->ReturnRawValue;
  238. resultpre = (*NUMBERS)[i]->ReturnPreValue;
  239. resulterror = (*NUMBERS)[i]->ErrorMessageText;
  240. resultrate = (*NUMBERS)[i]->ReturnRateValue; // Unit per minutes
  241. resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
  242. resulttimestamp = (*NUMBERS)[i]->timeStamp;
  243. DomoticzIdx = (*NUMBERS)[i]->DomoticzIdx;
  244. domoticzpayload = "{\"command\":\"udevice\",\"idx\":" + DomoticzIdx + ",\"svalue\":\""+ result + "\"}";
  245. namenumber = (*NUMBERS)[i]->name;
  246. if (namenumber == "default")
  247. namenumber = maintopic + "/";
  248. else
  249. namenumber = maintopic + "/" + namenumber + "/";
  250. if ((domoticzintopic.length() > 0) && (result.length() > 0))
  251. success |= MQTTPublish(domoticzintopic, domoticzpayload, qos, SetRetainFlag);
  252. if (result.length() > 0)
  253. success |= MQTTPublish(namenumber + "value", result, qos, SetRetainFlag);
  254. if (resulterror.length() > 0)
  255. success |= MQTTPublish(namenumber + "error", resulterror, qos, SetRetainFlag);
  256. if (resultrate.length() > 0) {
  257. success |= MQTTPublish(namenumber + "rate", resultrate, qos, SetRetainFlag);
  258. std::string resultRatePerTimeUnit;
  259. if (getTimeUnit() == "h") { // Need conversion to be per hour
  260. resultRatePerTimeUnit = resultRatePerTimeUnit = to_string((*NUMBERS)[i]->FlowRateAct * 60); // per minutes => per hour
  261. }
  262. else { // Keep per minute
  263. resultRatePerTimeUnit = resultrate;
  264. }
  265. success |= MQTTPublish(namenumber + "rate_per_time_unit", resultRatePerTimeUnit, qos, SetRetainFlag);
  266. }
  267. if (resultchangabs.length() > 0) {
  268. success |= MQTTPublish(namenumber + "changeabsolut", resultchangabs, qos, SetRetainFlag); // Legacy API
  269. success |= MQTTPublish(namenumber + "rate_per_digitization_round", resultchangabs, qos, SetRetainFlag);
  270. }
  271. if (resultraw.length() > 0)
  272. success |= MQTTPublish(namenumber + "raw", resultraw, qos, SetRetainFlag);
  273. if (resulttimestamp.length() > 0)
  274. success |= MQTTPublish(namenumber + "timestamp", resulttimestamp, qos, SetRetainFlag);
  275. std::string json = flowpostprocessing->getJsonFromNumber(i, "\n");
  276. success |= MQTTPublish(namenumber + "json", json, qos, SetRetainFlag);
  277. }
  278. }
  279. /* Disabled because this is no longer a use case */
  280. // else
  281. // {
  282. // for (int i = 0; i < ListFlowControll->size(); ++i)
  283. // {
  284. // zw = (*ListFlowControll)[i]->getReadout();
  285. // if (zw.length() > 0)
  286. // {
  287. // if (result.length() == 0)
  288. // result = zw;
  289. // else
  290. // result = result + "\t" + zw;
  291. // }
  292. // }
  293. // success |= MQTTPublish(topic, result, qos, SetRetainFlag);
  294. // }
  295. OldValue = result;
  296. if (!success) {
  297. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "One or more MQTT topics failed to be published!");
  298. }
  299. return true;
  300. }
  301. void ClassFlowMQTT::handleIdx(string _decsep, string _value)
  302. {
  303. string _digit, _decpos;
  304. int _pospunkt = _decsep.find_first_of(".");
  305. // ESP_LOGD(TAG, "Name: %s, Pospunkt: %d", _decsep.c_str(), _pospunkt);
  306. if (_pospunkt > -1)
  307. _digit = _decsep.substr(0, _pospunkt);
  308. else
  309. _digit = "default";
  310. for (int j = 0; j < flowpostprocessing->NUMBERS.size(); ++j)
  311. {
  312. if (_digit == "default") // Set to default first (if nothing else is set)
  313. {
  314. flowpostprocessing->NUMBERS[j]->DomoticzIdx = _value;
  315. }
  316. if (flowpostprocessing->NUMBERS[j]->name == _digit)
  317. {
  318. flowpostprocessing->NUMBERS[j]->DomoticzIdx = _value;
  319. }
  320. }
  321. }
  322. #endif //ENABLE_MQTT