ClassFlowMQTT.cpp 10 KB

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