interface_mqtt.cpp 22 KB

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