ClassFlowMQTT.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 "ClassLogFile.h"
  8. #include "time_sntp.h"
  9. #include "interface_mqtt.h"
  10. #include "ClassFlowPostProcessing.h"
  11. #include "ClassFlowControll.h"
  12. #include "server_mqtt.h"
  13. #include <time.h>
  14. #define __HIDE_PASSWORD
  15. static const char *TAG = "MQTT";
  16. #define LWT_TOPIC "connection"
  17. #define LWT_CONNECTED "connected"
  18. #define LWT_DISCONNECTED "connection lost"
  19. extern const char* libfive_git_version(void);
  20. extern const char* libfive_git_revision(void);
  21. extern const char* libfive_git_branch(void);
  22. void ClassFlowMQTT::SetInitialParameter(void)
  23. {
  24. uri = "";
  25. topic = "";
  26. topicError = "";
  27. topicRate = "";
  28. topicTimeStamp = "";
  29. maintopic = hostname;
  30. topicUptime = "";
  31. topicFreeMem = "";
  32. clientname = "AIOTED-" + getMac();
  33. OldValue = "";
  34. flowpostprocessing = NULL;
  35. user = "";
  36. password = "";
  37. SetRetainFlag = 0;
  38. previousElement = NULL;
  39. ListFlowControll = NULL;
  40. disabled = false;
  41. keepAlive = 25*60;
  42. }
  43. ClassFlowMQTT::ClassFlowMQTT()
  44. {
  45. SetInitialParameter();
  46. }
  47. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow*>* lfc)
  48. {
  49. SetInitialParameter();
  50. ListFlowControll = lfc;
  51. for (int i = 0; i < ListFlowControll->size(); ++i)
  52. {
  53. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  54. {
  55. flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
  56. }
  57. }
  58. }
  59. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow*>* lfc, ClassFlow *_prev)
  60. {
  61. SetInitialParameter();
  62. previousElement = _prev;
  63. ListFlowControll = lfc;
  64. for (int i = 0; i < ListFlowControll->size(); ++i)
  65. {
  66. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  67. {
  68. flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
  69. }
  70. }
  71. }
  72. bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
  73. {
  74. std::vector<string> zerlegt;
  75. aktparamgraph = trim(aktparamgraph);
  76. if (aktparamgraph.size() == 0)
  77. if (!this->GetNextParagraph(pfile, aktparamgraph))
  78. return false;
  79. if (toUpper(aktparamgraph).compare("[MQTT]") != 0) // Paragraph passt nich zu MakeImage
  80. return false;
  81. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
  82. {
  83. zerlegt = ZerlegeZeile(aktparamgraph);
  84. if ((toUpper(zerlegt[0]) == "USER") && (zerlegt.size() > 1))
  85. {
  86. this->user = zerlegt[1];
  87. }
  88. if ((toUpper(zerlegt[0]) == "PASSWORD") && (zerlegt.size() > 1))
  89. {
  90. this->password = zerlegt[1];
  91. }
  92. if ((toUpper(zerlegt[0]) == "URI") && (zerlegt.size() > 1))
  93. {
  94. this->uri = zerlegt[1];
  95. }
  96. if ((toUpper(zerlegt[0]) == "SETRETAINFLAG") && (zerlegt.size() > 1))
  97. {
  98. if (toUpper(zerlegt[1]) == "TRUE") {
  99. SetRetainFlag = 1;
  100. setMqtt_Server_Retain(SetRetainFlag);
  101. }
  102. }
  103. if ((toUpper(zerlegt[0]) == "HOMEASSISTANTDISCOVERY") && (zerlegt.size() > 1))
  104. {
  105. if (toUpper(zerlegt[1]) == "TRUE")
  106. SetHomeassistantDiscoveryEnabled(true);
  107. }
  108. if ((toUpper(zerlegt[0]) == "METERTYPE") && (zerlegt.size() > 1)) {
  109. /* Use meter type for the device class
  110. Make sure it is a listed one on https://developers.home-assistant.io/docs/core/entity/sensor/#available-device-classes */
  111. if (toUpper(zerlegt[1]) == "WATER_M3") {
  112. mqttServer_setMeterType("water", "m³", "h", "m³/h");
  113. }
  114. else if (toUpper(zerlegt[1]) == "WATER_L") {
  115. mqttServer_setMeterType("water", "L", "h", "L/h");
  116. }
  117. else if (toUpper(zerlegt[1]) == "WATER_FT3") {
  118. mqttServer_setMeterType("water", "ft³", "m", "ft³/m"); // Minutes
  119. }
  120. else if (toUpper(zerlegt[1]) == "WATER_GAL") {
  121. mqttServer_setMeterType("water", "gal", "h", "gal/h");
  122. }
  123. else if (toUpper(zerlegt[1]) == "GAS_M3") {
  124. mqttServer_setMeterType("gas", "m³", "h", "m³/h");
  125. }
  126. else if (toUpper(zerlegt[1]) == "GAS_FT3") {
  127. mqttServer_setMeterType("gas", "ft³", "m", "ft³/m"); // Minutes
  128. }
  129. else if (toUpper(zerlegt[1]) == "ENERGY_WH") {
  130. mqttServer_setMeterType("energy", "Wh", "h", "W");
  131. }
  132. else if (toUpper(zerlegt[1]) == "ENERGY_KWH") {
  133. mqttServer_setMeterType("energy", "kWh", "h", "kW");
  134. }
  135. else if (toUpper(zerlegt[1]) == "ENERGY_MWH") {
  136. mqttServer_setMeterType("energy", "MWh", "h", "MW");
  137. }
  138. }
  139. if ((toUpper(zerlegt[0]) == "CLIENTID") && (zerlegt.size() > 1))
  140. {
  141. this->clientname = zerlegt[1];
  142. }
  143. if (((toUpper(zerlegt[0]) == "TOPIC") || (toUpper(zerlegt[0]) == "MAINTOPIC")) && (zerlegt.size() > 1))
  144. {
  145. maintopic = zerlegt[1];
  146. mqttServer_setMainTopic(maintopic);
  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. return true;
  154. }
  155. string ClassFlowMQTT::GetMQTTMainTopic()
  156. {
  157. return maintopic;
  158. }
  159. bool ClassFlowMQTT::Start(float AutoIntervall)
  160. {
  161. roundInterval = AutoIntervall; // Minutes
  162. keepAlive = roundInterval * 60 * 2.5; // Seconds, make sure it is greater thatn 2 rounds!
  163. std::stringstream stream;
  164. stream << std::fixed << std::setprecision(1) << "Digitizer interval is " << roundInterval <<
  165. " minutes => setting MQTT LWT timeout to " << ((float)keepAlive/60) << " minutes.";
  166. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, stream.str());
  167. mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval);
  168. bool MQTTConfigCheck = MQTT_Configure(uri, clientname, user, password, maintopic, LWT_TOPIC, LWT_CONNECTED,
  169. LWT_DISCONNECTED, keepAlive, SetRetainFlag, (void *)&GotConnected);
  170. if (!MQTTConfigCheck) {
  171. return false;
  172. }
  173. return (MQTT_Init() == 1);
  174. }
  175. bool ClassFlowMQTT::doFlow(string zwtime)
  176. {
  177. std::string result;
  178. std::string resulterror = "";
  179. std::string resultraw = "";
  180. std::string resultpre = "";
  181. std::string resultrate = ""; // Always Unit / Minute
  182. std::string resultRatePerTimeUnit = ""; // According to selection
  183. std::string resulttimestamp = "";
  184. std::string resultchangabs = "";
  185. string zw = "";
  186. string namenumber = "";
  187. publishSystemData();
  188. if (flowpostprocessing && getMQTTisConnected())
  189. {
  190. std::vector<NumberPost*>* NUMBERS = flowpostprocessing->GetNumbers();
  191. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing MQTT topics...");
  192. for (int i = 0; i < (*NUMBERS).size(); ++i)
  193. {
  194. result = (*NUMBERS)[i]->ReturnValue;
  195. resultraw = (*NUMBERS)[i]->ReturnRawValue;
  196. resultpre = (*NUMBERS)[i]->ReturnPreValue;
  197. resulterror = (*NUMBERS)[i]->ErrorMessageText;
  198. resultrate = (*NUMBERS)[i]->ReturnRateValue; // Unit per minutes
  199. resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
  200. resulttimestamp = (*NUMBERS)[i]->timeStamp;
  201. namenumber = (*NUMBERS)[i]->name;
  202. if (namenumber == "default")
  203. namenumber = maintopic + "/";
  204. else
  205. namenumber = maintopic + "/" + namenumber + "/";
  206. if (result.length() > 0)
  207. MQTTPublish(namenumber + "value", result, SetRetainFlag);
  208. if (resulterror.length() > 0)
  209. MQTTPublish(namenumber + "error", resulterror, SetRetainFlag);
  210. if (resultrate.length() > 0) {
  211. MQTTPublish(namenumber + "rate", resultrate, SetRetainFlag);
  212. std::string resultRatePerTimeUnit;
  213. if (getTimeUnit() == "h") { // Need conversion to be per hour
  214. resultRatePerTimeUnit = resultRatePerTimeUnit = to_string((*NUMBERS)[i]->FlowRateAct * 60); // per minutes => per hour
  215. }
  216. else { // Keep per minute
  217. resultRatePerTimeUnit = resultrate;
  218. }
  219. MQTTPublish(namenumber + "rate_per_time_unit", resultRatePerTimeUnit, SetRetainFlag);
  220. }
  221. if (resultchangabs.length() > 0) {
  222. MQTTPublish(namenumber + "changeabsolut", resultchangabs, SetRetainFlag); // Legacy API
  223. MQTTPublish(namenumber + "rate_per_digitalization_round", resultchangabs, SetRetainFlag);
  224. }
  225. if (resultraw.length() > 0)
  226. MQTTPublish(namenumber + "raw", resultraw, SetRetainFlag);
  227. if (resulttimestamp.length() > 0)
  228. MQTTPublish(namenumber + "timestamp", resulttimestamp, SetRetainFlag);
  229. std::string json = flowpostprocessing->getJsonFromNumber(i, "\n");
  230. MQTTPublish(namenumber + "json", json, SetRetainFlag);
  231. }
  232. }
  233. /* Disabled because this is no longer a use case */
  234. // else
  235. // {
  236. // for (int i = 0; i < ListFlowControll->size(); ++i)
  237. // {
  238. // zw = (*ListFlowControll)[i]->getReadout();
  239. // if (zw.length() > 0)
  240. // {
  241. // if (result.length() == 0)
  242. // result = zw;
  243. // else
  244. // result = result + "\t" + zw;
  245. // }
  246. // }
  247. // MQTTPublish(topic, result, SetRetainFlag);
  248. // }
  249. OldValue = result;
  250. return true;
  251. }
  252. #endif //ENABLE_MQTT