ClassFlowMQTT.cpp 11 KB

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