ClassFlowMQTT.cpp 10 KB

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