ClassFlowMQTT.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. // printf("URI: %s, MAINTOPIC: %s", uri.c_str(), maintopic.c_str());
  160. if ((uri.length() == 0) || (maintopic.length() == 0))
  161. {
  162. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "MQTT not started because URI or Maintopic is not set. MQTT will be disabled.");
  163. MQTTdisable();
  164. return false;
  165. }
  166. roundInterval = AutoIntervall; // Minutes
  167. keepAlive = roundInterval * 60 * 2.5; // Seconds, make sure it is greater thatn 2 rounds!
  168. std::stringstream stream;
  169. stream << std::fixed << std::setprecision(1) << "Digitizer interval is " << roundInterval <<
  170. " minutes => setting MQTT LWT timeout to " << ((float)keepAlive/60) << " minutes.";
  171. LogFile.WriteToFile(ESP_LOG_INFO, TAG, stream.str());
  172. mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval);
  173. MQTT_Configure(uri, clientname, user, password, maintopic, LWT_TOPIC, LWT_CONNECTED, LWT_DISCONNECTED,
  174. keepAlive, SetRetainFlag, (void *)&GotConnected);
  175. if (!MQTT_Init()) {
  176. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init at startup failed! Retry with next publish call");
  177. return false;
  178. }
  179. return true;
  180. }
  181. bool ClassFlowMQTT::doFlow(string zwtime)
  182. {
  183. std::string result;
  184. std::string resulterror = "";
  185. std::string resultraw = "";
  186. std::string resultrate = ""; // Always Unit / Minute
  187. std::string resultRatePerTimeUnit = ""; // According to selection
  188. std::string resulttimestamp = "";
  189. std::string resultchangabs = "";
  190. string zw = "";
  191. string namenumber = "";
  192. publishSystemData();
  193. if (flowpostprocessing)
  194. {
  195. std::vector<NumberPost*>* NUMBERS = flowpostprocessing->GetNumbers();
  196. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Publishing MQTT topics...");
  197. for (int i = 0; i < (*NUMBERS).size(); ++i)
  198. {
  199. result = (*NUMBERS)[i]->ReturnValue;
  200. resultraw = (*NUMBERS)[i]->ReturnRawValue;
  201. resulterror = (*NUMBERS)[i]->ErrorMessageText;
  202. resultrate = (*NUMBERS)[i]->ReturnRateValue; // Unit per minutes
  203. resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
  204. resulttimestamp = (*NUMBERS)[i]->timeStamp;
  205. namenumber = (*NUMBERS)[i]->name;
  206. if (namenumber == "default")
  207. namenumber = maintopic + "/";
  208. else
  209. namenumber = maintopic + "/" + namenumber + "/";
  210. if (result.length() > 0)
  211. MQTTPublish(namenumber + "value", result, SetRetainFlag);
  212. if (resulterror.length() > 0)
  213. MQTTPublish(namenumber + "error", resulterror, SetRetainFlag);
  214. if (resultrate.length() > 0) {
  215. MQTTPublish(namenumber + "rate", resultrate, SetRetainFlag);
  216. std::string resultRatePerTimeUnit;
  217. if (getTimeUnit() == "h") { // Need conversion to be per hour
  218. resultRatePerTimeUnit = resultRatePerTimeUnit = to_string((*NUMBERS)[i]->FlowRateAct * 60); // per minutes => per hour
  219. }
  220. else { // Keep per minute
  221. resultRatePerTimeUnit = resultrate;
  222. }
  223. MQTTPublish(namenumber + "rate_per_time_unit", resultRatePerTimeUnit, SetRetainFlag);
  224. }
  225. if (resultchangabs.length() > 0) {
  226. MQTTPublish(namenumber + "changeabsolut", resultchangabs, SetRetainFlag); // Legacy API
  227. MQTTPublish(namenumber + "rate_per_digitalization_round", resultchangabs, SetRetainFlag);
  228. }
  229. if (resultraw.length() > 0)
  230. MQTTPublish(namenumber + "raw", resultraw, SetRetainFlag);
  231. if (resulttimestamp.length() > 0)
  232. MQTTPublish(namenumber + "timestamp", resulttimestamp, SetRetainFlag);
  233. std::string json = "";
  234. if (result.length() > 0)
  235. json += "{\"value\":"+result;
  236. else
  237. json += "{\"value\":\"\"";
  238. json += ",\"raw\":\""+resultraw;
  239. json += "\",\"error\":\""+resulterror;
  240. if (resultrate.length() > 0)
  241. json += "\",\"rate\":"+resultrate;
  242. else
  243. json += "\",\"rate\":\"\"";
  244. json += ",\"timestamp\":\""+resulttimestamp+"\"}";
  245. MQTTPublish(namenumber + "json", json, SetRetainFlag);
  246. }
  247. }
  248. else
  249. {
  250. for (int i = 0; i < ListFlowControll->size(); ++i)
  251. {
  252. zw = (*ListFlowControll)[i]->getReadout();
  253. if (zw.length() > 0)
  254. {
  255. if (result.length() == 0)
  256. result = zw;
  257. else
  258. result = result + "\t" + zw;
  259. }
  260. }
  261. MQTTPublish(topic, result, SetRetainFlag);
  262. }
  263. OldValue = result;
  264. return true;
  265. }