ClassFlowMQTT.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. #include "../../include/defines.h"
  15. static const char *TAG = "MQTT";
  16. extern const char* libfive_git_version(void);
  17. extern const char* libfive_git_revision(void);
  18. extern const char* libfive_git_branch(void);
  19. void ClassFlowMQTT::SetInitialParameter(void)
  20. {
  21. uri = "";
  22. topic = "";
  23. topicError = "";
  24. topicRate = "";
  25. topicTimeStamp = "";
  26. maintopic = hostname;
  27. topicUptime = "";
  28. topicFreeMem = "";
  29. clientname = "AIOTED-" + getMac();
  30. OldValue = "";
  31. flowpostprocessing = NULL;
  32. user = "";
  33. password = "";
  34. SetRetainFlag = false;
  35. previousElement = NULL;
  36. ListFlowControll = NULL;
  37. disabled = false;
  38. keepAlive = 25*60;
  39. }
  40. ClassFlowMQTT::ClassFlowMQTT()
  41. {
  42. SetInitialParameter();
  43. }
  44. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow*>* lfc)
  45. {
  46. SetInitialParameter();
  47. ListFlowControll = lfc;
  48. for (int i = 0; i < ListFlowControll->size(); ++i)
  49. {
  50. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  51. {
  52. flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
  53. }
  54. }
  55. }
  56. ClassFlowMQTT::ClassFlowMQTT(std::vector<ClassFlow*>* lfc, ClassFlow *_prev)
  57. {
  58. SetInitialParameter();
  59. previousElement = _prev;
  60. ListFlowControll = lfc;
  61. for (int i = 0; i < ListFlowControll->size(); ++i)
  62. {
  63. if (((*ListFlowControll)[i])->name().compare("ClassFlowPostProcessing") == 0)
  64. {
  65. flowpostprocessing = (ClassFlowPostProcessing*) (*ListFlowControll)[i];
  66. }
  67. }
  68. }
  69. bool ClassFlowMQTT::ReadParameter(FILE* pfile, string& aktparamgraph)
  70. {
  71. std::vector<string> splitted;
  72. aktparamgraph = trim(aktparamgraph);
  73. if (aktparamgraph.size() == 0)
  74. if (!this->GetNextParagraph(pfile, aktparamgraph))
  75. return false;
  76. if (toUpper(aktparamgraph).compare("[MQTT]") != 0) // Paragraph does not fit MQTT
  77. return false;
  78. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
  79. {
  80. splitted = ZerlegeZeile(aktparamgraph);
  81. if ((toUpper(splitted[0]) == "USER") && (splitted.size() > 1))
  82. {
  83. this->user = splitted[1];
  84. }
  85. if ((toUpper(splitted[0]) == "PASSWORD") && (splitted.size() > 1))
  86. {
  87. this->password = splitted[1];
  88. }
  89. if ((toUpper(splitted[0]) == "URI") && (splitted.size() > 1))
  90. {
  91. this->uri = splitted[1];
  92. }
  93. if ((toUpper(splitted[0]) == "RETAINMESSAGES") && (splitted.size() > 1))
  94. {
  95. if (toUpper(splitted[1]) == "TRUE") {
  96. SetRetainFlag = true;
  97. setMqtt_Server_Retain(SetRetainFlag);
  98. }
  99. }
  100. if ((toUpper(splitted[0]) == "HOMEASSISTANTDISCOVERY") && (splitted.size() > 1))
  101. {
  102. if (toUpper(splitted[1]) == "TRUE")
  103. SetHomeassistantDiscoveryEnabled(true);
  104. }
  105. if ((toUpper(splitted[0]) == "METERTYPE") && (splitted.size() > 1)) {
  106. /* Use meter type for the device class
  107. Make sure it is a listed one on https://developers.home-assistant.io/docs/core/entity/sensor/#available-device-classes */
  108. if (toUpper(splitted[1]) == "WATER_M3") {
  109. mqttServer_setMeterType("water", "m³", "h", "m³/h");
  110. }
  111. else if (toUpper(splitted[1]) == "WATER_L") {
  112. mqttServer_setMeterType("water", "L", "h", "L/h");
  113. }
  114. else if (toUpper(splitted[1]) == "WATER_FT3") {
  115. mqttServer_setMeterType("water", "ft³", "m", "ft³/m"); // Minutes
  116. }
  117. else if (toUpper(splitted[1]) == "WATER_GAL") {
  118. mqttServer_setMeterType("water", "gal", "h", "gal/h");
  119. }
  120. else if (toUpper(splitted[1]) == "GAS_M3") {
  121. mqttServer_setMeterType("gas", "m³", "h", "m³/h");
  122. }
  123. else if (toUpper(splitted[1]) == "GAS_FT3") {
  124. mqttServer_setMeterType("gas", "ft³", "m", "ft³/m"); // Minutes
  125. }
  126. else if (toUpper(splitted[1]) == "ENERGY_WH") {
  127. mqttServer_setMeterType("energy", "Wh", "h", "W");
  128. }
  129. else if (toUpper(splitted[1]) == "ENERGY_KWH") {
  130. mqttServer_setMeterType("energy", "kWh", "h", "kW");
  131. }
  132. else if (toUpper(splitted[1]) == "ENERGY_MWH") {
  133. mqttServer_setMeterType("energy", "MWh", "h", "MW");
  134. }
  135. }
  136. if ((toUpper(splitted[0]) == "CLIENTID") && (splitted.size() > 1))
  137. {
  138. this->clientname = splitted[1];
  139. }
  140. if (((toUpper(splitted[0]) == "TOPIC") || (toUpper(splitted[0]) == "MAINTOPIC")) && (splitted.size() > 1))
  141. {
  142. maintopic = splitted[1];
  143. mqttServer_setMainTopic(maintopic);
  144. }
  145. }
  146. /* Note:
  147. * Originally, we started the MQTT client here.
  148. * How ever we need the interval parameter from the ClassFlowControll, but that only gets started later.
  149. * To work around this, we delay the start and trigger it from ClassFlowControll::ReadParameter() */
  150. return true;
  151. }
  152. string ClassFlowMQTT::GetMQTTMainTopic()
  153. {
  154. return maintopic;
  155. }
  156. bool ClassFlowMQTT::Start(float AutoInterval)
  157. {
  158. roundInterval = AutoInterval; // 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_DEBUG, TAG, stream.str());
  164. mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval);
  165. bool MQTTConfigCheck = MQTT_Configure(uri, clientname, user, password, maintopic, LWT_TOPIC, LWT_CONNECTED,
  166. LWT_DISCONNECTED, keepAlive, SetRetainFlag, (void *)&GotConnected);
  167. if (!MQTTConfigCheck) {
  168. return false;
  169. }
  170. return (MQTT_Init() == 1);
  171. }
  172. bool ClassFlowMQTT::doFlow(string zwtime)
  173. {
  174. std::string result;
  175. std::string resulterror = "";
  176. std::string resultraw = "";
  177. std::string resultpre = "";
  178. std::string resultrate = ""; // Always Unit / Minute
  179. std::string resultRatePerTimeUnit = ""; // According to selection
  180. std::string resulttimestamp = "";
  181. std::string resultchangabs = "";
  182. string zw = "";
  183. string namenumber = "";
  184. publishSystemData();
  185. if (flowpostprocessing && getMQTTisConnected())
  186. {
  187. std::vector<NumberPost*>* NUMBERS = flowpostprocessing->GetNumbers();
  188. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing MQTT topics...");
  189. for (int i = 0; i < (*NUMBERS).size(); ++i)
  190. {
  191. result = (*NUMBERS)[i]->ReturnValue;
  192. resultraw = (*NUMBERS)[i]->ReturnRawValue;
  193. resultpre = (*NUMBERS)[i]->ReturnPreValue;
  194. resulterror = (*NUMBERS)[i]->ErrorMessageText;
  195. resultrate = (*NUMBERS)[i]->ReturnRateValue; // Unit per minutes
  196. resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
  197. resulttimestamp = (*NUMBERS)[i]->timeStamp;
  198. namenumber = (*NUMBERS)[i]->name;
  199. if (namenumber == "default")
  200. namenumber = maintopic + "/";
  201. else
  202. namenumber = maintopic + "/" + namenumber + "/";
  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 = flowpostprocessing->getJsonFromNumber(i, "\n");
  227. MQTTPublish(namenumber + "json", json, SetRetainFlag);
  228. }
  229. }
  230. /* Disabled because this is no longer a use case */
  231. // else
  232. // {
  233. // for (int i = 0; i < ListFlowControll->size(); ++i)
  234. // {
  235. // zw = (*ListFlowControll)[i]->getReadout();
  236. // if (zw.length() > 0)
  237. // {
  238. // if (result.length() == 0)
  239. // result = zw;
  240. // else
  241. // result = result + "\t" + zw;
  242. // }
  243. // }
  244. // MQTTPublish(topic, result, SetRetainFlag);
  245. // }
  246. OldValue = result;
  247. return true;
  248. }
  249. #endif //ENABLE_MQTT