ClassFlowMQTT.cpp 11 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 "read_wlanini.h"
  8. #include "ClassLogFile.h"
  9. #include "time_sntp.h"
  10. #include "websocket.h"
  11. #include "interface_mqtt.h"
  12. #include "ClassFlowPostProcessing.h"
  13. #include "ClassFlowControll.h"
  14. #include "server_mqtt.h"
  15. #include <time.h>
  16. #include "../../include/defines.h"
  17. static const char *TAG = "MQTT";
  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 = wlan_config.hostname;
  29. topicUptime = "";
  30. topicFreeMem = "";
  31. clientname = wlan_config.hostname;
  32. OldValue = "";
  33. flowpostprocessing = NULL;
  34. user = "";
  35. password = "";
  36. SetRetainFlag = false;
  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> splitted;
  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 does not fit MQTT
  79. return false;
  80. while (this->getNextLine(pfile, &aktparamgraph) && !this->isNewParagraph(aktparamgraph))
  81. {
  82. splitted = ZerlegeZeile(aktparamgraph);
  83. if ((toUpper(splitted[0]) == "USER") && (splitted.size() > 1))
  84. {
  85. this->user = splitted[1];
  86. }
  87. if ((toUpper(splitted[0]) == "PASSWORD") && (splitted.size() > 1))
  88. {
  89. this->password = splitted[1];
  90. }
  91. if ((toUpper(splitted[0]) == "URI") && (splitted.size() > 1))
  92. {
  93. this->uri = splitted[1];
  94. }
  95. if ((toUpper(splitted[0]) == "RETAINMESSAGES") && (splitted.size() > 1))
  96. {
  97. if (toUpper(splitted[1]) == "TRUE") {
  98. SetRetainFlag = true;
  99. setMqtt_Server_Retain(SetRetainFlag);
  100. }
  101. }
  102. if ((toUpper(splitted[0]) == "HOMEASSISTANTDISCOVERY") && (splitted.size() > 1))
  103. {
  104. if (toUpper(splitted[1]) == "TRUE")
  105. SetHomeassistantDiscoveryEnabled(true);
  106. }
  107. if ((toUpper(splitted[0]) == "METERTYPE") && (splitted.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(splitted[1]) == "WATER_M3") {
  111. mqttServer_setMeterType("water", "m³", "h", "m³/h");
  112. }
  113. else if (toUpper(splitted[1]) == "WATER_L") {
  114. mqttServer_setMeterType("water", "L", "h", "L/h");
  115. }
  116. else if (toUpper(splitted[1]) == "WATER_FT3") {
  117. mqttServer_setMeterType("water", "ft³", "m", "ft³/m"); // Minutes
  118. }
  119. else if (toUpper(splitted[1]) == "WATER_GAL") {
  120. mqttServer_setMeterType("water", "gal", "h", "gal/h");
  121. }
  122. else if (toUpper(splitted[1]) == "GAS_M3") {
  123. mqttServer_setMeterType("gas", "m³", "h", "m³/h");
  124. }
  125. else if (toUpper(splitted[1]) == "GAS_FT3") {
  126. mqttServer_setMeterType("gas", "ft³", "m", "ft³/m"); // Minutes
  127. }
  128. else if (toUpper(splitted[1]) == "ENERGY_WH") {
  129. mqttServer_setMeterType("energy", "Wh", "h", "W");
  130. }
  131. else if (toUpper(splitted[1]) == "ENERGY_KWH") {
  132. mqttServer_setMeterType("energy", "kWh", "h", "kW");
  133. }
  134. else if (toUpper(splitted[1]) == "ENERGY_MWH") {
  135. mqttServer_setMeterType("energy", "MWh", "h", "MW");
  136. }
  137. else if (toUpper(splitted[1]) == "ENERGY_GJ") {
  138. mqttServer_setMeterType("energy", "GJ", "h", "GJ/h");
  139. }
  140. }
  141. if ((toUpper(splitted[0]) == "CLIENTID") && (splitted.size() > 1))
  142. {
  143. this->clientname = splitted[1];
  144. }
  145. if (((toUpper(splitted[0]) == "TOPIC") || (toUpper(splitted[0]) == "MAINTOPIC")) && (splitted.size() > 1))
  146. {
  147. maintopic = splitted[1];
  148. }
  149. }
  150. /* Note:
  151. * Originally, we started the MQTT client here.
  152. * How ever we need the interval parameter from the ClassFlowControll, but that only gets started later.
  153. * To work around this, we delay the start and trigger it from ClassFlowControll::ReadParameter() */
  154. mqttServer_setMainTopic(maintopic);
  155. return true;
  156. }
  157. bool ClassFlowMQTT::Start(float AutoInterval)
  158. {
  159. roundInterval = AutoInterval; // 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_DEBUG, TAG, stream.str());
  165. mqttServer_setParameter(flowpostprocessing->GetNumbers(), keepAlive, roundInterval);
  166. bool MQTTConfigCheck = MQTT_Configure(uri, clientname, user, password, maintopic, LWT_TOPIC, LWT_CONNECTED,
  167. LWT_DISCONNECTED, keepAlive, SetRetainFlag, (void *)&GotConnected);
  168. if (!MQTTConfigCheck) {
  169. return false;
  170. }
  171. return (MQTT_Init() == 1);
  172. }
  173. bool ClassFlowMQTT::doFlow(string zwtime)
  174. {
  175. bool success;
  176. std::string result;
  177. std::string resulterror = "";
  178. std::string resultraw = "";
  179. std::string resultpre = "";
  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. int qos = 1;
  187. /* Send the the Homeassistant Discovery and the Static Topics in case they where scheduled */
  188. sendDiscovery_and_static_Topics();
  189. success = publishSystemData(qos);
  190. if (flowpostprocessing && getMQTTisConnected())
  191. {
  192. std::vector<NumberPost*>* NUMBERS = flowpostprocessing->GetNumbers();
  193. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publishing MQTT topics...");
  194. for (int i = 0; i < (*NUMBERS).size(); ++i)
  195. {
  196. result = (*NUMBERS)[i]->ReturnValue;
  197. resultraw = (*NUMBERS)[i]->ReturnRawValue;
  198. resultpre = (*NUMBERS)[i]->ReturnPreValue;
  199. resulterror = (*NUMBERS)[i]->ErrorMessageText;
  200. resultrate = (*NUMBERS)[i]->ReturnRateValue; // Unit per minutes
  201. resultchangabs = (*NUMBERS)[i]->ReturnChangeAbsolute; // Units per round
  202. resulttimestamp = (*NUMBERS)[i]->timeStamp;
  203. namenumber = (*NUMBERS)[i]->name;
  204. if (namenumber == "default")
  205. namenumber = maintopic + "/";
  206. else
  207. namenumber = maintopic + "/" + namenumber + "/";
  208. if (result.length() > 0) {
  209. success |= MQTTPublish(namenumber + "value", result, qos, SetRetainFlag);
  210. schedule_websocket_message("{\"value\": \"" + result + "\", \"number\": \"" + (*NUMBERS)[i]->name + "\"}");
  211. }
  212. if (resulterror.length() > 0) {
  213. success |= MQTTPublish(namenumber + "error", resulterror, qos, SetRetainFlag);
  214. schedule_websocket_message("{\"error\": \"" + resulterror + "\", \"number\": \"" + (*NUMBERS)[i]->name + "\"}");
  215. }
  216. if (resultrate.length() > 0) {
  217. success |= MQTTPublish(namenumber + "rate", resultrate, qos, SetRetainFlag);
  218. std::string resultRatePerTimeUnit;
  219. if (getTimeUnit() == "h") { // Need conversion to be per hour
  220. resultRatePerTimeUnit = resultRatePerTimeUnit = to_string((*NUMBERS)[i]->FlowRateAct * 60); // per minutes => per hour
  221. }
  222. else { // Keep per minute
  223. resultRatePerTimeUnit = resultrate;
  224. }
  225. success |= MQTTPublish(namenumber + "rate_per_time_unit", resultRatePerTimeUnit, qos, SetRetainFlag);
  226. }
  227. if (resultchangabs.length() > 0) {
  228. success |= MQTTPublish(namenumber + "changeabsolut", resultchangabs, qos, SetRetainFlag); // Legacy API
  229. success |= MQTTPublish(namenumber + "rate_per_digitalization_round", resultchangabs, qos, SetRetainFlag);
  230. }
  231. if (resultraw.length() > 0) {
  232. success |= MQTTPublish(namenumber + "raw", resultraw, qos, SetRetainFlag);
  233. schedule_websocket_message("{\"raw\": \"" + resultraw + "\", \"number\": \"" + (*NUMBERS)[i]->name + "\"}");
  234. }
  235. if (resulttimestamp.length() > 0)
  236. success |= MQTTPublish(namenumber + "timestamp", resulttimestamp, qos, SetRetainFlag);
  237. std::string json = flowpostprocessing->getJsonFromNumber(i, "\n");
  238. success |= MQTTPublish(namenumber + "json", json, qos, SetRetainFlag);
  239. }
  240. }
  241. /* Disabled because this is no longer a use case */
  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. // success |= MQTTPublish(topic, result, qos, SetRetainFlag);
  256. // }
  257. OldValue = result;
  258. if (!success) {
  259. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "One or more MQTT topics failed to be published!");
  260. }
  261. return true;
  262. }
  263. #endif //ENABLE_MQTT