ClassFlowMQTT.cpp 10 KB

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