interface_mqtt.cpp 21 KB

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