interface_mqtt.cpp 21 KB

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