interface_mqtt.cpp 22 KB

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