ClassFlowMQTT.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. #include <sstream>
  2. #include <iomanip>
  3. #include "ClassFlowMQTT.h"
  4. #include "Helper.h"
  5. #include "connect_wlan.h"
  6. #include "ClassLogFile.h"
  7. #include "time_sntp.h"
  8. #include "interface_mqtt.h"
  9. #include "ClassFlowPostProcessing.h"
  10. #include "ClassFlowControll.h"
  11. #include "server_mqtt.h"
  12. #include <time.h>
  13. #define __HIDE_PASSWORD
  14. #define LWT_TOPIC "connection"
  15. #define LWT_CONNECTED "connected"
  16. #define LWT_DISCONNECTED "connection lost"
  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 = hostname;
  28. topicUptime = "";
  29. topicFreeMem = "";
  30. clientname = "AIOTED-" + getMac();
  31. OldValue = "";
  32. flowpostprocessing = NULL;
  33. user = "";
  34. password = "";
  35. SetRetainFlag = 0;
  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> zerlegt;
  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 passt nich zu MakeImage
  78. return false;
  79. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
  80. {
  81. zerlegt = this->ZerlegeZeile(aktparamgraph);
  82. if ((toUpper(zerlegt[0]) == "USER") && (zerlegt.size() > 1))
  83. {
  84. this->user = zerlegt[1];
  85. }
  86. if ((toUpper(zerlegt[0]) == "PASSWORD") && (zerlegt.size() > 1))
  87. {
  88. this->password = zerlegt[1];
  89. }
  90. if ((toUpper(zerlegt[0]) == "URI") && (zerlegt.size() > 1))
  91. {
  92. this->uri = zerlegt[1];
  93. }
  94. if ((toUpper(zerlegt[0]) == "SETRETAINFLAG") && (zerlegt.size() > 1))
  95. {
  96. if (toUpper(zerlegt[1]) == "TRUE") {
  97. SetRetainFlag = 1;
  98. setMqtt_Server_Retain(SetRetainFlag);
  99. }
  100. }
  101. if ((toUpper(zerlegt[0]) == "HOMEASSISTANTDISCOVERY") && (zerlegt.size() > 1))
  102. {
  103. if (toUpper(zerlegt[1]) == "TRUE")
  104. SetHomeassistantDiscoveryEnabled(true);
  105. }
  106. if ((toUpper(zerlegt[0]) == "METERTYPE") && (zerlegt.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(zerlegt[1]) == "WATER_M3") {
  110. mqttServer_setMeterType("water", "m³", "h", "m³/h");
  111. }
  112. else if (toUpper(zerlegt[1]) == "WATER_L") {
  113. mqttServer_setMeterType("water", "L", "h", "L/h");
  114. }
  115. else if (toUpper(zerlegt[1]) == "WATER_FT3") {
  116. mqttServer_setMeterType("water", "ft³", "m", "ft³/m"); // Minutes
  117. }
  118. else if (toUpper(zerlegt[1]) == "WATER_GAL") {
  119. mqttServer_setMeterType("water", "gal", "h", "gal/h");
  120. }
  121. else if (toUpper(zerlegt[1]) == "GAS_M3") {
  122. mqttServer_setMeterType("gas", "m³", "h", "m³/h");
  123. }
  124. else if (toUpper(zerlegt[1]) == "GAS_FT3") {
  125. mqttServer_setMeterType("gas", "ft³", "m", "ft³/m"); // Minutes
  126. }
  127. else if (toUpper(zerlegt[1]) == "ENERGY_WH") {
  128. mqttServer_setMeterType("energy", "Wh", "h", "W");
  129. }
  130. else if (toUpper(zerlegt[1]) == "ENERGY_KWH") {
  131. mqttServer_setMeterType("energy", "kWh", "h", "kW");
  132. }
  133. else if (toUpper(zerlegt[1]) == "ENERGY_MWH") {
  134. mqttServer_setMeterType("energy", "MWh", "h", "MW");
  135. }
  136. }
  137. if ((toUpper(zerlegt[0]) == "CLIENTID") && (zerlegt.size() > 1))
  138. {
  139. this->clientname = zerlegt[1];
  140. }
  141. if (((toUpper(zerlegt[0]) == "TOPIC") || (toUpper(zerlegt[0]) == "MAINTOPIC")) && (zerlegt.size() > 1))
  142. {
  143. maintopic = zerlegt[1];
  144. mqttServer_setMainTopic(maintopic);
  145. }
  146. }
  147. /* Note:
  148. * Originally, we started the MQTT client here.
  149. * How ever we need the interval parameter from the ClassFlowControll, but that only gets started later.
  150. * To work around this, we delay the start and trigger it from ClassFlowControll::ReadParameter() */
  151. return true;
  152. }
  153. string ClassFlowMQTT::GetMQTTMainTopic()
  154. {
  155. return maintopic;
  156. }
  157. bool ClassFlowMQTT::Start(float AutoIntervall) {
  158. roundInterval = AutoIntervall; // 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_INFO, stream.str());
  164. mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval);
  165. MQTT_Configure(uri, clientname, user, password, maintopic, LWT_TOPIC, LWT_CONNECTED, LWT_DISCONNECTED,
  166. keepAlive, SetRetainFlag, (void *)&GotConnected);
  167. if (!MQTT_Init()) {
  168. if (!MQTT_Init()) { // Retry
  169. return false;
  170. }
  171. }
  172. return true;
  173. }
  174. bool ClassFlowMQTT::doFlow(string zwtime)
  175. {
  176. std::string result;
  177. std::string resulterror = "";
  178. std::string resultraw = "";
  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. publishSystemData();
  186. if (flowpostprocessing)
  187. {
  188. std::vector<NumberPost*>* NUMBERS = flowpostprocessing->GetNumbers();
  189. for (int i = 0; i < (*NUMBERS).size(); ++i)
  190. {
  191. result = (*NUMBERS)[i]->ReturnValue;
  192. resultraw = (*NUMBERS)[i]->ReturnRawValue;
  193. resulterror = (*NUMBERS)[i]->ErrorMessageText;
  194. resultrate = (*NUMBERS)[i]->ReturnRateValue; // Unit per minutes
  195. resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
  196. resulttimestamp = (*NUMBERS)[i]->timeStamp;
  197. namenumber = (*NUMBERS)[i]->name;
  198. if (namenumber == "default")
  199. namenumber = maintopic + "/";
  200. else
  201. namenumber = maintopic + "/" + namenumber + "/";
  202. LogFile.WriteToFile(ESP_LOG_INFO, "Publishing MQTT topics...");
  203. if (result.length() > 0)
  204. MQTTPublish(namenumber + "value", result, SetRetainFlag);
  205. if (resulterror.length() > 0)
  206. MQTTPublish(namenumber + "error", resulterror, SetRetainFlag);
  207. if (resultrate.length() > 0) {
  208. MQTTPublish(namenumber + "rate", resultrate, SetRetainFlag);
  209. std::string resultRatePerTimeUnit;
  210. if (getTimeUnit() == "h") { // Need conversion to be per hour
  211. resultRatePerTimeUnit = resultRatePerTimeUnit = to_string((*NUMBERS)[i]->FlowRateAct / 60); // per minutes => per hour
  212. }
  213. else { // Keep per minute
  214. resultRatePerTimeUnit = resultrate;
  215. }
  216. MQTTPublish(namenumber + "rate_per_time_unit", resultRatePerTimeUnit, SetRetainFlag);
  217. }
  218. if (resultchangabs.length() > 0) {
  219. MQTTPublish(namenumber + "changeabsolut", resultchangabs, SetRetainFlag); // Legacy API
  220. MQTTPublish(namenumber + "rate_per_digitalization_round", resultchangabs, SetRetainFlag);
  221. }
  222. if (resultraw.length() > 0)
  223. MQTTPublish(namenumber + "raw", resultraw, SetRetainFlag);
  224. if (resulttimestamp.length() > 0)
  225. MQTTPublish(namenumber + "timestamp", resulttimestamp, SetRetainFlag);
  226. std::string json = "";
  227. if (result.length() > 0)
  228. json += "{\"value\":"+result;
  229. else
  230. json += "{\"value\":\"\"";
  231. json += ",\"raw\":\""+resultraw;
  232. json += "\",\"error\":\""+resulterror;
  233. if (resultrate.length() > 0)
  234. json += "\",\"rate\":"+resultrate;
  235. else
  236. json += "\",\"rate\":\"\"";
  237. json += ",\"timestamp\":\""+resulttimestamp+"\"}";
  238. MQTTPublish(namenumber + "json", json, SetRetainFlag);
  239. }
  240. }
  241. else
  242. {
  243. for (int i = 0; i < ListFlowControll->size(); ++i)
  244. {
  245. zw = (*ListFlowControll)[i]->getReadout();
  246. if (zw.length() > 0)
  247. {
  248. if (result.length() == 0)
  249. result = zw;
  250. else
  251. result = result + "\t" + zw;
  252. }
  253. }
  254. MQTTPublish(topic, result, SetRetainFlag);
  255. }
  256. OldValue = result;
  257. return true;
  258. }