ClassFlowMQTT.cpp 12 KB

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