ClassFlowMQTT.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 = 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 = splitted[1];
  99. }
  100. if ((toUpper(_param) == "CLIENTKEY") && (splitted.size() > 1))
  101. {
  102. this->clientKeyFilename = 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. }
  160. if ((toUpper(_param) == "CLIENTID") && (splitted.size() > 1))
  161. {
  162. this->clientname = splitted[1];
  163. }
  164. if (((toUpper(_param) == "TOPIC") || (toUpper(splitted[0]) == "MAINTOPIC")) && (splitted.size() > 1))
  165. {
  166. maintopic = splitted[1];
  167. }
  168. if (((toUpper(_param) == "DOMOTICZTOPICIN")) && (splitted.size() > 1))
  169. {
  170. this->domoticzintopic = splitted[1];
  171. }
  172. if (((toUpper(_param) == "DOMOTICZIDX")) && (splitted.size() > 1))
  173. {
  174. handleIdx(splitted[0], splitted[1]);
  175. }
  176. }
  177. /* Note:
  178. * Originally, we started the MQTT client here.
  179. * How ever we need the interval parameter from the ClassFlowControll, but that only gets started later.
  180. * To work around this, we delay the start and trigger it from ClassFlowControll::ReadParameter() */
  181. mqttServer_setMainTopic(maintopic);
  182. mqttServer_setDmoticzInTopic(domoticzintopic);
  183. return true;
  184. }
  185. bool ClassFlowMQTT::Start(float AutoInterval)
  186. {
  187. roundInterval = AutoInterval; // Minutes
  188. keepAlive = roundInterval * 60 * 2.5; // Seconds, make sure it is greater thatn 2 rounds!
  189. std::stringstream stream;
  190. stream << std::fixed << std::setprecision(1) << "Digitizer interval is " << roundInterval <<
  191. " minutes => setting MQTT LWT timeout to " << ((float)keepAlive/60) << " minutes.";
  192. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, stream.str());
  193. mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval);
  194. bool MQTTConfigCheck = MQTT_Configure(uri, clientname, user, password, maintopic, domoticzintopic, LWT_TOPIC, LWT_CONNECTED,
  195. LWT_DISCONNECTED, caCertFilename, validateServerCert, clientCertFilename, clientKeyFilename,
  196. keepAlive, SetRetainFlag, (void *)&GotConnected);
  197. if (!MQTTConfigCheck) {
  198. return false;
  199. }
  200. return (MQTT_Init() == 1);
  201. }
  202. bool ClassFlowMQTT::doFlow(string zwtime)
  203. {
  204. bool success;
  205. std::string result;
  206. std::string resulterror = "";
  207. std::string resultraw = "";
  208. std::string resultpre = "";
  209. std::string resultrate = ""; // Always Unit / Minute
  210. std::string resultRatePerTimeUnit = ""; // According to selection
  211. std::string resulttimestamp = "";
  212. std::string resultchangabs = "";
  213. string zw = "";
  214. string namenumber = "";
  215. string domoticzpayload = "";
  216. string DomoticzIdx = "";
  217. int qos = 1;
  218. /* Send the the Homeassistant Discovery and the Static Topics in case they where scheduled */
  219. sendDiscovery_and_static_Topics();
  220. success = publishSystemData(qos);
  221. if (flowpostprocessing && getMQTTisConnected())
  222. {
  223. std::vector<NumberPost*>* NUMBERS = flowpostprocessing->GetNumbers();
  224. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing MQTT topics...");
  225. for (int i = 0; i < (*NUMBERS).size(); ++i)
  226. {
  227. result = (*NUMBERS)[i]->ReturnValue;
  228. resultraw = (*NUMBERS)[i]->ReturnRawValue;
  229. resultpre = (*NUMBERS)[i]->ReturnPreValue;
  230. resulterror = (*NUMBERS)[i]->ErrorMessageText;
  231. resultrate = (*NUMBERS)[i]->ReturnRateValue; // Unit per minutes
  232. resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
  233. resulttimestamp = (*NUMBERS)[i]->timeStamp;
  234. DomoticzIdx = (*NUMBERS)[i]->DomoticzIdx;
  235. domoticzpayload = "{\"command\":\"udevice\",\"idx\":" + DomoticzIdx + ",\"svalue\":\""+ result + "\"}";
  236. namenumber = (*NUMBERS)[i]->name;
  237. if (namenumber == "default")
  238. namenumber = maintopic + "/";
  239. else
  240. namenumber = maintopic + "/" + namenumber + "/";
  241. if ((domoticzintopic.length() > 0) && (result.length() > 0))
  242. success |= MQTTPublish(domoticzintopic, domoticzpayload, qos, SetRetainFlag);
  243. if (result.length() > 0)
  244. success |= MQTTPublish(namenumber + "value", result, qos, SetRetainFlag);
  245. if (resulterror.length() > 0)
  246. success |= MQTTPublish(namenumber + "error", resulterror, qos, SetRetainFlag);
  247. if (resultrate.length() > 0) {
  248. success |= MQTTPublish(namenumber + "rate", resultrate, qos, SetRetainFlag);
  249. std::string resultRatePerTimeUnit;
  250. if (getTimeUnit() == "h") { // Need conversion to be per hour
  251. resultRatePerTimeUnit = resultRatePerTimeUnit = to_string((*NUMBERS)[i]->FlowRateAct * 60); // per minutes => per hour
  252. }
  253. else { // Keep per minute
  254. resultRatePerTimeUnit = resultrate;
  255. }
  256. success |= MQTTPublish(namenumber + "rate_per_time_unit", resultRatePerTimeUnit, qos, SetRetainFlag);
  257. }
  258. if (resultchangabs.length() > 0) {
  259. success |= MQTTPublish(namenumber + "changeabsolut", resultchangabs, qos, SetRetainFlag); // Legacy API
  260. success |= MQTTPublish(namenumber + "rate_per_digitization_round", resultchangabs, qos, SetRetainFlag);
  261. }
  262. if (resultraw.length() > 0)
  263. success |= MQTTPublish(namenumber + "raw", resultraw, qos, SetRetainFlag);
  264. if (resulttimestamp.length() > 0)
  265. success |= MQTTPublish(namenumber + "timestamp", resulttimestamp, qos, SetRetainFlag);
  266. std::string json = flowpostprocessing->getJsonFromNumber(i, "\n");
  267. success |= MQTTPublish(namenumber + "json", json, qos, SetRetainFlag);
  268. }
  269. }
  270. /* Disabled because this is no longer a use case */
  271. // else
  272. // {
  273. // for (int i = 0; i < ListFlowControll->size(); ++i)
  274. // {
  275. // zw = (*ListFlowControll)[i]->getReadout();
  276. // if (zw.length() > 0)
  277. // {
  278. // if (result.length() == 0)
  279. // result = zw;
  280. // else
  281. // result = result + "\t" + zw;
  282. // }
  283. // }
  284. // success |= MQTTPublish(topic, result, qos, SetRetainFlag);
  285. // }
  286. OldValue = result;
  287. if (!success) {
  288. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "One or more MQTT topics failed to be published!");
  289. }
  290. return true;
  291. }
  292. void ClassFlowMQTT::handleIdx(string _decsep, string _value)
  293. {
  294. string _digit, _decpos;
  295. int _pospunkt = _decsep.find_first_of(".");
  296. // ESP_LOGD(TAG, "Name: %s, Pospunkt: %d", _decsep.c_str(), _pospunkt);
  297. if (_pospunkt > -1)
  298. _digit = _decsep.substr(0, _pospunkt);
  299. else
  300. _digit = "default";
  301. for (int j = 0; j < flowpostprocessing->NUMBERS.size(); ++j)
  302. {
  303. if (_digit == "default") // Set to default first (if nothing else is set)
  304. {
  305. flowpostprocessing->NUMBERS[j]->DomoticzIdx = _value;
  306. }
  307. if (flowpostprocessing->NUMBERS[j]->name == _digit)
  308. {
  309. flowpostprocessing->NUMBERS[j]->DomoticzIdx = _value;
  310. }
  311. }
  312. }
  313. #endif //ENABLE_MQTT