interface_mqtt.cpp 24 KB

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