interface_mqtt.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. #ifdef ENABLE_MQTT
  2. #include "interface_mqtt.h"
  3. #include "esp_log.h"
  4. #include "esp_timer.h"
  5. #include "connect_wlan.h"
  6. #include "mqtt_client.h"
  7. #include "ClassLogFile.h"
  8. #include "MainFlowControl.h"
  9. #include "cJSON.h"
  10. #include "../../include/defines.h"
  11. #include <mutex>
  12. #include <new>
  13. #include <utility>
  14. static const char *TAG = "MQTT IF";
  15. std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
  16. std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFunktionMap = NULL;
  17. static std::mutex connectFunctionMutex;
  18. static std::mutex subscribeFunctionMutex;
  19. // Serialize the outbox-size check and enqueue operation across application tasks.
  20. static std::mutex mqttPublishMutex;
  21. // Keep the MQTT outbox bounded so a slow or unavailable broker cannot consume
  22. // an unbounded amount of internal heap. QoS acknowledgements release entries.
  23. static constexpr size_t MQTT_MAX_OUTBOX_BYTES = 12 * 1024;
  24. static constexpr size_t MQTT_OUTBOX_ENTRY_OVERHEAD = 64;
  25. int failedOnRound = -1;
  26. int MQTTReconnectCnt = 0;
  27. esp_mqtt_event_id_t esp_mqtt_ID = MQTT_EVENT_ANY;
  28. // ESP_EVENT_ANY_ID
  29. bool mqtt_enabled = false;
  30. bool mqtt_configOK = false;
  31. bool mqtt_initialized = false;
  32. bool mqtt_connected = false;
  33. esp_mqtt_client_handle_t client = NULL;
  34. std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic, domoticz_in_topic;
  35. std::string caCert, clientCert, clientKey;
  36. bool validateServerCert = true;
  37. int keepalive;
  38. bool SetRetainFlag;
  39. void (*callbackOnConnected)(std::string, bool) = NULL;
  40. bool MQTTPublish(std::string _key, std::string _content, int qos, bool retained_flag)
  41. {
  42. if (!mqtt_enabled) {
  43. return false;
  44. }
  45. if (failedOnRound == getCountFlowRounds()) {
  46. return true; // A previous queue failure already stopped MQTT publishing for this round.
  47. }
  48. #ifdef DEBUG_DETAIL_ON
  49. LogFile.WriteHeapInfo("MQTT Publish");
  50. #endif
  51. MQTT_Init(); // Re-Init client if not initialized yet/anymore
  52. if (!mqtt_initialized || !mqtt_connected || client == NULL) {
  53. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publish skipped. Client not initialized or not connected. (topic: " + _key + ")");
  54. return false;
  55. }
  56. // esp_mqtt_client_enqueue() only adds the message to the outbox. The MQTT task
  57. // performs the network operation, keeping socket waits out of the calling task.
  58. // Serialize the size check with enqueue so concurrent publishers respect the cap.
  59. std::lock_guard<std::mutex> publishLock(mqttPublishMutex);
  60. const int outboxSize = esp_mqtt_client_get_outbox_size(client);
  61. const size_t estimatedEntrySize = _key.length() + _content.length() + MQTT_OUTBOX_ENTRY_OVERHEAD;
  62. if (outboxSize < 0 ||
  63. static_cast<size_t>(outboxSize) + estimatedEntrySize > MQTT_MAX_OUTBOX_BYTES) {
  64. failedOnRound = getCountFlowRounds();
  65. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  66. "MQTT outbox limit reached (" + std::to_string(outboxSize) +
  67. " bytes); skipping further MQTT messages in this round");
  68. return false;
  69. }
  70. const int64_t enqueueStartUs = esp_timer_get_time();
  71. const int msg_id = esp_mqtt_client_enqueue(client, _key.c_str(), _content.c_str(), 0, qos, retained_flag, true);
  72. const int64_t enqueueDurationUs = esp_timer_get_time() - enqueueStartUs;
  73. if (msg_id < 0) {
  74. failedOnRound = getCountFlowRounds();
  75. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  76. "Failed to enqueue MQTT topic '" + _key +
  77. "' (outbox=" + std::to_string(outboxSize) + " bytes); skipping further MQTT messages in this round");
  78. return false;
  79. }
  80. // Log only unusually slow enqueue operations. Normal publishes should not
  81. // generate an additional SD-card write just for timing instrumentation.
  82. if (enqueueDurationUs >= 10000) {
  83. LogFile.WriteToFile(ESP_LOG_WARN, TAG,
  84. "MQTT enqueue for topic '" + _key + "' took " +
  85. std::to_string(enqueueDurationUs / 1000) + " ms (outbox=" +
  86. std::to_string(outboxSize) + " bytes)");
  87. }
  88. if (_content.length() > 80) {
  89. _content.resize(80);
  90. _content.append("..");
  91. }
  92. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Queued topic: " + _key + ", content: " + _content);
  93. return true;
  94. }
  95. static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
  96. std::string topic = "";
  97. switch (event->event_id) {
  98. case MQTT_EVENT_BEFORE_CONNECT:
  99. mqtt_initialized = true;
  100. break;
  101. case MQTT_EVENT_CONNECTED:
  102. MQTTReconnectCnt = 0;
  103. mqtt_initialized = true;
  104. mqtt_connected = true;
  105. MQTTconnected();
  106. break;
  107. case MQTT_EVENT_DISCONNECTED:
  108. mqtt_connected = false;
  109. MQTTReconnectCnt++;
  110. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected, trying to reconnect");
  111. if (MQTTReconnectCnt >= 5) {
  112. MQTTReconnectCnt = 0;
  113. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Disconnected, multiple reconnect attempts failed, still retrying...");
  114. }
  115. break;
  116. case MQTT_EVENT_SUBSCRIBED:
  117. ESP_LOGD(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
  118. break;
  119. case MQTT_EVENT_UNSUBSCRIBED:
  120. ESP_LOGD(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
  121. break;
  122. case MQTT_EVENT_PUBLISHED:
  123. ESP_LOGD(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
  124. break;
  125. case MQTT_EVENT_DATA:
  126. ESP_LOGD(TAG, "MQTT_EVENT_DATA");
  127. ESP_LOGD(TAG, "TOPIC=%.*s", event->topic_len, event->topic);
  128. ESP_LOGD(TAG, "DATA=%.*s", event->data_len, event->data);
  129. topic.assign(event->topic, event->topic_len);
  130. {
  131. // Keep callback targets alive until invocation finishes. Unregister waits for this lock.
  132. std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
  133. if (subscribeFunktionMap != NULL) {
  134. const auto handler = subscribeFunktionMap->find(topic);
  135. if (handler != subscribeFunktionMap->end()) {
  136. ESP_LOGD(TAG, "call subcribe function for topic %s", topic.c_str());
  137. handler->second(topic, event->data, event->data_len);
  138. }
  139. } else {
  140. ESP_LOGW(TAG, "no handler available\r\n");
  141. }
  142. }
  143. break;
  144. case MQTT_EVENT_ERROR:
  145. // http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033 --> chapter 3.2.2.3
  146. // The server does not support the level of the MQTT protocol requested by the client
  147. // NOTE: Only protocol 3.1.1 is supported (refer to setting in sdkconfig)
  148. if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_PROTOCOL) {
  149. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, unacceptable protocol version (0x01)");
  150. }
  151. // The client identifier is correct UTF-8 but not allowed by the server
  152. // e.g. clientID empty (cannot be the case -> default set in firmware)
  153. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_ID_REJECTED) {
  154. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, identifier rejected (0x02)");
  155. }
  156. // The network connection has been made but the MQTT service is unavailable
  157. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_SERVER_UNAVAILABLE) {
  158. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, Server unavailable (0x03)");
  159. }
  160. // The data in the user name or password is malformed
  161. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_BAD_USERNAME) {
  162. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, malformed data in username or password (0x04)");
  163. }
  164. // The client is not authorized to connect
  165. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED) {
  166. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, not authorized. Check username/password (0x05)");
  167. }
  168. else {
  169. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Other event id:" + event->error_handle->connect_return_code);
  170. ESP_LOGE(TAG, "Other event id:%d", event->error_handle->connect_return_code);
  171. }
  172. #ifdef DEBUG_DETAIL_ON
  173. ESP_LOGD(TAG, "MQTT_EVENT_ERROR - esp_mqtt_error_codes:");
  174. ESP_LOGD(TAG, "error_type:%d", event->error_handle->error_type);
  175. ESP_LOGD(TAG, "connect_return_code:%d", event->error_handle->connect_return_code);
  176. ESP_LOGD(TAG, "esp_transport_sock_errno:%d", event->error_handle->esp_transport_sock_errno);
  177. ESP_LOGD(TAG, "esp_tls_last_esp_err:%d", event->error_handle->esp_tls_last_esp_err);
  178. ESP_LOGD(TAG, "esp_tls_stack_err:%d", event->error_handle->esp_tls_stack_err);
  179. ESP_LOGD(TAG, "esp_tls_cert_verify_flags:%d", event->error_handle->esp_tls_cert_verify_flags);
  180. #endif
  181. break;
  182. default:
  183. ESP_LOGD(TAG, "Other event id:%d", event->event_id);
  184. break;
  185. }
  186. return ESP_OK;
  187. }
  188. static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
  189. ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, (int)event_id);
  190. mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data);
  191. }
  192. bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
  193. std::string _maintopic, std::string _domoticz_in_topic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
  194. std::string _cacertfilename, bool _validateServerCert, std::string _clientcertfilename, std::string _clientkeyfilename,
  195. int _keepalive, bool _SetRetainFlag, void *_callbackOnConnected) {
  196. if ((_mqttURI.length() == 0) || (_maintopic.length() == 0) || (_clientid.length() == 0))
  197. {
  198. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init aborted! Config error (URI, MainTopic or ClientID missing)");
  199. return false;
  200. }
  201. uri = _mqttURI;
  202. client_id = _clientid;
  203. lwt_topic = _maintopic + "/" + _lwt;
  204. lwt_connected = _lwt_connected;
  205. lwt_disconnected = _lwt_disconnected;
  206. keepalive = _keepalive;
  207. SetRetainFlag = _SetRetainFlag;
  208. maintopic = _maintopic;
  209. domoticz_in_topic = _domoticz_in_topic;
  210. callbackOnConnected = ( void (*)(std::string, bool) )(_callbackOnConnected);
  211. if (_clientcertfilename.length() && _clientkeyfilename.length()) {
  212. std::ifstream cert_ifs(_clientcertfilename);
  213. if (cert_ifs.is_open()) {
  214. std::string cert_content((std::istreambuf_iterator<char>(cert_ifs)), (std::istreambuf_iterator<char>()));
  215. clientCert = cert_content;
  216. cert_ifs.close();
  217. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using clientCert: " + _clientcertfilename);
  218. }
  219. else {
  220. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "could not open clientCert: " + _clientcertfilename);
  221. }
  222. std::ifstream key_ifs(_clientkeyfilename);
  223. if (key_ifs.is_open()) {
  224. std::string key_content((std::istreambuf_iterator<char>(key_ifs)), (std::istreambuf_iterator<char>()));
  225. clientKey = key_content;
  226. key_ifs.close();
  227. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using clientKey: " + _clientkeyfilename);
  228. }
  229. else {
  230. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "could not open clientKey: " + _clientkeyfilename);
  231. }
  232. }
  233. if (_cacertfilename.length()) {
  234. std::ifstream ca_ifs(_cacertfilename);
  235. if (ca_ifs.is_open()) {
  236. std::string content((std::istreambuf_iterator<char>(ca_ifs)), (std::istreambuf_iterator<char>()));
  237. caCert = content;
  238. ca_ifs.close();
  239. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "using caCert: " + _cacertfilename);
  240. }
  241. else {
  242. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "could not open caCert: " + _cacertfilename);
  243. }
  244. }
  245. validateServerCert = _validateServerCert;
  246. if (_user.length() && _password.length()){
  247. user = _user;
  248. password = _password;
  249. }
  250. #ifdef __HIDE_PASSWORD
  251. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: XXXXXXXX, maintopic: "
  252. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  253. #else
  254. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: " + password + ", maintopic: "
  255. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  256. #endif
  257. mqtt_configOK = true;
  258. return true;
  259. }
  260. int MQTT_Init() {
  261. if (mqtt_initialized) {
  262. return 0;
  263. }
  264. if (mqtt_configOK) {
  265. mqtt_enabled = true;
  266. } else {
  267. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but client is not yet configured.");
  268. return 0;
  269. }
  270. if (!getWIFIisConnected()) {
  271. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but WIFI is not yet connected.");
  272. return 0;
  273. }
  274. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init");
  275. MQTTdestroy_client(false);
  276. esp_mqtt_client_config_t mqtt_cfg = { };
  277. mqtt_cfg.broker.address.uri = uri.c_str();
  278. mqtt_cfg.credentials.client_id = client_id.c_str();
  279. mqtt_cfg.network.disable_auto_reconnect = false; // Reconnection routine active (Default: false)
  280. mqtt_cfg.network.reconnect_timeout_ms = 15000; // Try to reconnect to broker (Default: 10000ms)
  281. mqtt_cfg.network.timeout_ms = 20000; // Network Timeout (Default: 10000ms)
  282. mqtt_cfg.session.message_retransmit_timeout = 3000; // Time after message resent when broker not acknowledged (QoS1, QoS2)
  283. mqtt_cfg.session.last_will.topic = lwt_topic.c_str();
  284. mqtt_cfg.session.last_will.retain = 1;
  285. mqtt_cfg.session.last_will.msg = lwt_disconnected.c_str();
  286. mqtt_cfg.session.last_will.msg_len = (int)(lwt_disconnected.length());
  287. mqtt_cfg.session.keepalive = keepalive;
  288. mqtt_cfg.buffer.size = 2048; // size of MQTT send/receive buffer
  289. if (caCert.length()) {
  290. mqtt_cfg.broker.verification.certificate = caCert.c_str();
  291. mqtt_cfg.broker.verification.certificate_len = caCert.length() + 1;
  292. // Skip any validation of server certificate CN field, this reduces the
  293. // security of TLS and makes the *MQTT* client susceptible to MITM attacks
  294. mqtt_cfg.broker.verification.skip_cert_common_name_check = !validateServerCert;
  295. }
  296. if (clientCert.length() && clientKey.length()) {
  297. mqtt_cfg.credentials.authentication.certificate = clientCert.c_str();
  298. mqtt_cfg.credentials.authentication.certificate_len = clientCert.length() + 1;
  299. mqtt_cfg.credentials.authentication.key = clientKey.c_str();
  300. mqtt_cfg.credentials.authentication.key_len = clientKey.length() + 1;
  301. }
  302. if (user.length() && password.length()){
  303. mqtt_cfg.credentials.username = user.c_str();
  304. mqtt_cfg.credentials.authentication.password = password.c_str();
  305. }
  306. #ifdef DEBUG_DETAIL_ON
  307. LogFile.WriteHeapInfo("MQTT Client Init");
  308. #endif
  309. client = esp_mqtt_client_init(&mqtt_cfg);
  310. if (client)
  311. {
  312. esp_err_t ret = esp_mqtt_client_register_event(client, esp_mqtt_ID, mqtt_event_handler, client);
  313. if (ret != ESP_OK)
  314. {
  315. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not register event (ret=" + std::to_string(ret) + ")!");
  316. esp_mqtt_client_destroy(client);
  317. client = NULL;
  318. mqtt_connected = false;
  319. mqtt_initialized = false;
  320. return -1;
  321. }
  322. #ifdef DEBUG_DETAIL_ON
  323. LogFile.WriteHeapInfo("MQTT Client Start");
  324. #endif
  325. ret = esp_mqtt_client_start(client);
  326. if (ret != ESP_OK)
  327. {
  328. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Client start failed (retval=" + std::to_string(ret) + ")!");
  329. esp_mqtt_client_destroy(client);
  330. client = NULL;
  331. mqtt_connected = false;
  332. mqtt_initialized = false;
  333. return -1;
  334. }
  335. else {
  336. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Client started, waiting for established connection...");
  337. mqtt_initialized = true;
  338. return 1;
  339. }
  340. }
  341. else
  342. {
  343. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init failed, no handle created!");
  344. mqtt_initialized = false;
  345. return -1;
  346. }
  347. }
  348. void MQTTdestroy_client(bool _disable = false) {
  349. if (client) {
  350. if (mqtt_connected) {
  351. MQTTdestroySubscribeFunction();
  352. esp_mqtt_client_disconnect(client);
  353. mqtt_connected = false;
  354. }
  355. esp_mqtt_client_stop(client);
  356. esp_mqtt_client_destroy(client);
  357. client = NULL;
  358. mqtt_initialized = false;
  359. }
  360. if (_disable) // Disable MQTT service, avoid restart with MQTTPublish
  361. mqtt_configOK = false;
  362. }
  363. bool getMQTTisEnabled() {
  364. return mqtt_enabled;
  365. }
  366. bool getMQTTisConnected() {
  367. return mqtt_connected;
  368. }
  369. bool mqtt_handler_flow_start(std::string _topic, char* _data, int _data_len)
  370. {
  371. ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
  372. MQTTCtrlFlowStart(_topic);
  373. return ESP_OK;
  374. }
  375. bool mqtt_handler_set_prevalue(std::string _topic, char* _data, int _data_len)
  376. {
  377. //ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
  378. //example: {"numbersname": "main", "value": 12345.1234567}
  379. if (_data != NULL && _data_len > 0) {
  380. // MQTT event payloads are length-delimited and are not guaranteed to be NUL-terminated.
  381. cJSON *jsonData = cJSON_ParseWithLength(_data, static_cast<size_t>(_data_len));
  382. if (jsonData == NULL) {
  383. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: invalid JSON payload");
  384. return ESP_FAIL;
  385. }
  386. cJSON *numbersname = cJSON_GetObjectItemCaseSensitive(jsonData, "numbersname");
  387. cJSON *value = cJSON_GetObjectItemCaseSensitive(jsonData, "value");
  388. bool updateOkay = false;
  389. if (cJSON_IsString(numbersname) && numbersname->valuestring != NULL) {
  390. if (cJSON_IsNumber(value)) {
  391. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_set_prevalue called: numbersname: " + std::string(numbersname->valuestring) +
  392. ", value: " + std::to_string(value->valuedouble));
  393. updateOkay = flowctrl.UpdatePrevalue(std::to_string(value->valuedouble),
  394. std::string(numbersname->valuestring), true);
  395. } else {
  396. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: value not a valid number (\"value\": 12345.12345)");
  397. }
  398. } else {
  399. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: numbersname not a valid string (\"numbersname\": \"main\")");
  400. }
  401. cJSON_Delete(jsonData);
  402. return updateOkay;
  403. }
  404. else {
  405. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: handler called, but no data received");
  406. }
  407. return ESP_FAIL;
  408. }
  409. void MQTTconnected(){
  410. if (mqtt_connected) {
  411. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to broker");
  412. {
  413. // Callback owners cannot be destroyed until a connect callback has returned.
  414. std::lock_guard<std::mutex> lock(connectFunctionMutex);
  415. if (connectFunktionMap != NULL) {
  416. for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
  417. it->second();
  418. ESP_LOGD(TAG, "call connect function %s", it->first.c_str());
  419. }
  420. }
  421. }
  422. // Subcribe to topics
  423. // Note: Further subsriptions are handled in GPIO class
  424. //*****************************************
  425. std::function<bool(std::string topic, char* data, int data_len)> subHandler1 = mqtt_handler_flow_start;
  426. MQTTregisterSubscribeFunction(maintopic + "/ctrl/flow_start", subHandler1); // subcribe to maintopic/ctrl/flow_start
  427. std::function<bool(std::string topic, char* data, int data_len)> subHandler2 = mqtt_handler_set_prevalue;
  428. MQTTregisterSubscribeFunction(maintopic + "/ctrl/set_prevalue", subHandler2); // subcribe to maintopic/ctrl/set_prevalue
  429. {
  430. std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
  431. if (subscribeFunktionMap != NULL && client != NULL) {
  432. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  433. const int msg_id = esp_mqtt_client_subscribe(client, it->first.c_str(), 0);
  434. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "topic " + it->first + " subscribe requested, msg_id=" + std::to_string(msg_id));
  435. }
  436. }
  437. }
  438. /* Send Static Topics and Homeassistant Discovery */
  439. if (callbackOnConnected) { // Call onConnected callback routine --> mqtt_server
  440. callbackOnConnected(maintopic, SetRetainFlag);
  441. }
  442. }
  443. }
  444. void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
  445. ESP_LOGD(TAG, "MQTTregisterConnectFunction %s\r\n", name.c_str());
  446. std::lock_guard<std::mutex> lock(connectFunctionMutex);
  447. if (connectFunktionMap == NULL) {
  448. connectFunktionMap = new (std::nothrow) std::map<std::string, std::function<void()>>();
  449. if (connectFunktionMap == NULL) {
  450. ESP_LOGE(TAG, "Unable to allocate MQTT connect callback map");
  451. return;
  452. }
  453. }
  454. if (connectFunktionMap->find(name) != connectFunktionMap->end()) {
  455. ESP_LOGW(TAG, "connect function %s already registered", name.c_str());
  456. return;
  457. }
  458. connectFunktionMap->emplace(name, std::move(func));
  459. if (mqtt_connected) {
  460. connectFunktionMap->find(name)->second();
  461. }
  462. }
  463. void MQTTunregisterConnectFunction(std::string name){
  464. ESP_LOGD(TAG, "unregisterConnectFunction %s\r\n", name.c_str());
  465. std::lock_guard<std::mutex> lock(connectFunctionMutex);
  466. if (connectFunktionMap != NULL) {
  467. connectFunktionMap->erase(name);
  468. if (connectFunktionMap->empty()) {
  469. delete connectFunktionMap;
  470. connectFunktionMap = NULL;
  471. }
  472. }
  473. }
  474. void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
  475. ESP_LOGD(TAG, "registerSubscribeFunction %s", topic.c_str());
  476. std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
  477. if (subscribeFunktionMap == NULL) {
  478. subscribeFunktionMap = new (std::nothrow) std::map<std::string, std::function<bool(std::string, char*, int)>>();
  479. if (subscribeFunktionMap == NULL) {
  480. ESP_LOGE(TAG, "Unable to allocate MQTT subscription callback map");
  481. return;
  482. }
  483. }
  484. if (subscribeFunktionMap->find(topic) != subscribeFunktionMap->end()) {
  485. ESP_LOGW(TAG, "topic %s already registered for subscription", topic.c_str());
  486. return;
  487. }
  488. subscribeFunktionMap->emplace(topic, std::move(func));
  489. }
  490. void MQTTunregisterSubscribeFunction(std::string topic) {
  491. std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
  492. if (subscribeFunktionMap == NULL) return;
  493. const auto handler = subscribeFunktionMap->find(topic);
  494. if (handler == subscribeFunktionMap->end()) return;
  495. if (mqtt_connected && client != NULL) {
  496. const int msg_id = esp_mqtt_client_unsubscribe(client, topic.c_str());
  497. ESP_LOGD(TAG, "topic %s unsubscribe requested, msg_id=%d", topic.c_str(), msg_id);
  498. }
  499. subscribeFunktionMap->erase(handler);
  500. if (subscribeFunktionMap->empty()) {
  501. delete subscribeFunktionMap;
  502. subscribeFunktionMap = NULL;
  503. }
  504. }
  505. void MQTTdestroySubscribeFunction(){
  506. std::lock_guard<std::mutex> lock(subscribeFunctionMutex);
  507. if (subscribeFunktionMap != NULL) {
  508. if (mqtt_connected && client != NULL) {
  509. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  510. int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
  511. ESP_LOGD(TAG, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);
  512. }
  513. }
  514. subscribeFunktionMap->clear();
  515. delete subscribeFunktionMap;
  516. subscribeFunktionMap = NULL;
  517. }
  518. }
  519. #endif //ENABLE_MQTT