interface_mqtt.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. #ifdef ENABLE_MQTT
  2. #include "interface_mqtt.h"
  3. #include "esp_log.h"
  4. #include "connect_wlan.h"
  5. #include "mqtt_client.h"
  6. #include "ClassLogFile.h"
  7. #include "server_tflite.h"
  8. #include "../../include/defines.h"
  9. static const char *TAG = "MQTT IF";
  10. std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
  11. std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFunktionMap = NULL;
  12. int failedOnRound = -1;
  13. int MQTTReconnectCnt = 0;
  14. esp_mqtt_event_id_t esp_mqtt_ID = MQTT_EVENT_ANY;
  15. // ESP_EVENT_ANY_ID
  16. bool mqtt_enabled = false;
  17. bool mqtt_configOK = false;
  18. bool mqtt_initialized = false;
  19. bool mqtt_connected = false;
  20. esp_mqtt_client_handle_t client = NULL;
  21. std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic;
  22. int keepalive;
  23. bool SetRetainFlag;
  24. void (*callbackOnConnected)(std::string, bool) = NULL;
  25. bool MQTTPublish(std::string _key, std::string _content, bool retained_flag)
  26. {
  27. if (!mqtt_enabled) { // MQTT sevice not started / configured (MQTT_Init not called before)
  28. return false;
  29. }
  30. if (failedOnRound == getCountFlowRounds()) { // we already failed in this round, do not retry until the next round
  31. return true; // Fail quietly
  32. }
  33. #ifdef DEBUG_DETAIL_ON
  34. LogFile.WriteHeapInfo("MQTT Publish");
  35. #endif
  36. MQTT_Init(); // Re-Init client if not initialized yet/anymore
  37. if (mqtt_initialized && mqtt_connected) {
  38. #ifdef DEBUG_DETAIL_ON
  39. long long int starttime = esp_timer_get_time();
  40. #endif
  41. int msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, 1, retained_flag);
  42. #ifdef DEBUG_DETAIL_ON
  43. ESP_LOGD(TAG, "Publish msg_id %d in %lld ms", msg_id, (esp_timer_get_time() - starttime)/1000);
  44. #endif
  45. if (msg_id == -1) {
  46. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Failed to publish topic '" + _key + "', re-trying...");
  47. #ifdef DEBUG_DETAIL_ON
  48. starttime = esp_timer_get_time();
  49. #endif
  50. msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, 1, 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_ERROR, TAG, "Failed to publish topic '" + _key + "', skipping all MQTT publishings in this round!");
  56. failedOnRound = getCountFlowRounds();
  57. return false;
  58. }
  59. }
  60. if (_content.length() > 80) { // Truncate message if too long
  61. _content.resize(80);
  62. _content.append("..");
  63. }
  64. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Published topic: " + _key + ", content: " + _content + " (msg_id=" + std::to_string(msg_id) + ")");
  65. return true;
  66. }
  67. else {
  68. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publish skipped. Client not initalized or not connected. (topic: " + _key + ")");
  69. return false;
  70. }
  71. }
  72. static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
  73. std::string topic = "";
  74. switch (event->event_id) {
  75. case MQTT_EVENT_BEFORE_CONNECT:
  76. mqtt_initialized = true;
  77. break;
  78. case MQTT_EVENT_CONNECTED:
  79. MQTTReconnectCnt = 0;
  80. mqtt_initialized = true;
  81. mqtt_connected = true;
  82. MQTTconnected();
  83. break;
  84. case MQTT_EVENT_DISCONNECTED:
  85. mqtt_connected = false;
  86. MQTTReconnectCnt++;
  87. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected, trying to reconnect");
  88. if (MQTTReconnectCnt >= 5) {
  89. MQTTReconnectCnt = 0;
  90. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Disconnected, multiple reconnect attempts failed, still retrying...");
  91. }
  92. break;
  93. case MQTT_EVENT_SUBSCRIBED:
  94. ESP_LOGD(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
  95. break;
  96. case MQTT_EVENT_UNSUBSCRIBED:
  97. ESP_LOGD(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
  98. break;
  99. case MQTT_EVENT_PUBLISHED:
  100. ESP_LOGD(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
  101. break;
  102. case MQTT_EVENT_DATA:
  103. ESP_LOGD(TAG, "MQTT_EVENT_DATA");
  104. ESP_LOGD(TAG, "TOPIC=%.*s", event->topic_len, event->topic);
  105. ESP_LOGD(TAG, "DATA=%.*s", event->data_len, event->data);
  106. topic.assign(event->topic, event->topic_len);
  107. if (subscribeFunktionMap != NULL) {
  108. if (subscribeFunktionMap->find(topic) != subscribeFunktionMap->end()) {
  109. ESP_LOGD(TAG, "call subcribe function for topic %s", topic.c_str());
  110. (*subscribeFunktionMap)[topic](topic, event->data, event->data_len);
  111. }
  112. } else {
  113. ESP_LOGW(TAG, "no handler available\r\n");
  114. }
  115. break;
  116. case MQTT_EVENT_ERROR:
  117. #ifdef DEBUG_DETAIL_ON
  118. ESP_LOGD(TAG, "MQTT_EVENT_ERROR - esp_mqtt_error_codes:");
  119. ESP_LOGD(TAG, "error_type:%d", event->error_handle->error_type);
  120. ESP_LOGD(TAG, "connect_return_code:%d", event->error_handle->connect_return_code);
  121. ESP_LOGD(TAG, "esp_transport_sock_errno:%d", event->error_handle->esp_transport_sock_errno);
  122. ESP_LOGD(TAG, "esp_tls_last_esp_err:%d", event->error_handle->esp_tls_last_esp_err);
  123. ESP_LOGD(TAG, "esp_tls_stack_err:%d", event->error_handle->esp_tls_stack_err);
  124. ESP_LOGD(TAG, "esp_tls_cert_verify_flags:%d", event->error_handle->esp_tls_cert_verify_flags);
  125. #endif
  126. //mqtt_connected = false;
  127. break;
  128. default:
  129. ESP_LOGD(TAG, "Other event id:%d", event->event_id);
  130. break;
  131. }
  132. return ESP_OK;
  133. }
  134. static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
  135. ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
  136. mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data);
  137. }
  138. bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
  139. std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
  140. int _keepalive, bool _SetRetainFlag, void *_callbackOnConnected) {
  141. if ((_mqttURI.length() == 0) || (_maintopic.length() == 0) || (_clientid.length() == 0))
  142. {
  143. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init aborted! Config error (URI, MainTopic or ClientID missing)");
  144. return false;
  145. }
  146. uri = _mqttURI;
  147. client_id = _clientid;
  148. lwt_topic = _maintopic + "/" + _lwt;
  149. lwt_connected = _lwt_connected;
  150. lwt_disconnected = _lwt_disconnected;
  151. keepalive = _keepalive;
  152. SetRetainFlag = _SetRetainFlag;
  153. maintopic = _maintopic;
  154. callbackOnConnected = ( void (*)(std::string, bool) )(_callbackOnConnected);
  155. if (_user.length() && _password.length()){
  156. user = _user;
  157. password = _password;
  158. }
  159. #ifdef __HIDE_PASSWORD
  160. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: XXXXXXXX, maintopic: "
  161. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  162. #else
  163. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: " + password + ", maintopic: "
  164. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  165. #endif
  166. mqtt_configOK = true;
  167. return true;
  168. }
  169. int MQTT_Init() {
  170. if (mqtt_initialized) {
  171. return 0;
  172. }
  173. if (mqtt_configOK) {
  174. mqtt_enabled = true;
  175. } else {
  176. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but client is not yet configured.");
  177. return 0;
  178. }
  179. if (!getWIFIisConnected()) {
  180. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but WIFI is not yet connected.");
  181. return 0;
  182. }
  183. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init");
  184. MQTTdestroy_client(false);
  185. esp_mqtt_client_config_t mqtt_cfg = {
  186. .uri = uri.c_str(),
  187. .client_id = client_id.c_str(),
  188. .lwt_topic = lwt_topic.c_str(),
  189. .lwt_msg = lwt_disconnected.c_str(),
  190. .lwt_retain = 1,
  191. .lwt_msg_len = (int)(lwt_disconnected.length()),
  192. .keepalive = keepalive,
  193. .disable_auto_reconnect = false, // Reconnection routine active (Default: false)
  194. .buffer_size = 1536, // size of MQTT send/receive buffer (Default: 1024)
  195. .reconnect_timeout_ms = 15000, // Try to reconnect to broker (Default: 10000ms)
  196. .network_timeout_ms = 20000, // Network Timeout (Default: 10000ms)
  197. .message_retransmit_timeout = 3000 // Tiem after message resent when broker not acknowledged (QoS1, QoS2)
  198. };
  199. if (user.length() && password.length()){
  200. mqtt_cfg.username = user.c_str();
  201. mqtt_cfg.password = password.c_str();
  202. }
  203. #ifdef DEBUG_DETAIL_ON
  204. LogFile.WriteHeapInfo("MQTT Client Init");
  205. #endif
  206. client = esp_mqtt_client_init(&mqtt_cfg);
  207. if (client)
  208. {
  209. esp_err_t ret = esp_mqtt_client_register_event(client, esp_mqtt_ID, mqtt_event_handler, client);
  210. if (ret != ESP_OK)
  211. {
  212. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not register event (ret=" + std::to_string(ret) + ")!");
  213. mqtt_initialized = false;
  214. return -1;
  215. }
  216. #ifdef DEBUG_DETAIL_ON
  217. LogFile.WriteHeapInfo("MQTT Client Start");
  218. #endif
  219. ret = esp_mqtt_client_start(client);
  220. if (ret != ESP_OK)
  221. {
  222. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Client start failed (retval=" + std::to_string(ret) + ")!");
  223. mqtt_initialized = false;
  224. return -1;
  225. }
  226. else {
  227. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Client started, waiting for established connection...");
  228. mqtt_initialized = true;
  229. return 1;
  230. }
  231. }
  232. else
  233. {
  234. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init failed, no handle created!");
  235. mqtt_initialized = false;
  236. return -1;
  237. }
  238. }
  239. void MQTTdestroy_client(bool _disable = false) {
  240. if (client) {
  241. if (mqtt_connected) {
  242. MQTTdestroySubscribeFunction();
  243. esp_mqtt_client_disconnect(client);
  244. mqtt_connected = false;
  245. }
  246. esp_mqtt_client_stop(client);
  247. esp_mqtt_client_destroy(client);
  248. client = NULL;
  249. mqtt_initialized = false;
  250. }
  251. if (_disable) // Disable MQTT service, avoid restart with MQTTPublish
  252. mqtt_configOK = false;
  253. }
  254. bool getMQTTisEnabled() {
  255. return mqtt_enabled;
  256. }
  257. bool getMQTTisConnected() {
  258. return mqtt_connected;
  259. }
  260. bool mqtt_handler_flow_start(std::string _topic, char* _data, int _data_len) {
  261. ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
  262. if (_data_len > 0) {
  263. MQTTCtrlFlowStart(_topic);
  264. }
  265. return ESP_OK;
  266. }
  267. void MQTTconnected(){
  268. if (mqtt_connected) {
  269. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to broker");
  270. if (connectFunktionMap != NULL) {
  271. for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
  272. it->second();
  273. ESP_LOGD(TAG, "call connect function %s", it->first.c_str());
  274. }
  275. }
  276. /* Subcribe to topics */
  277. std::function<bool(std::string topic, char* data, int data_len)> subHandler = mqtt_handler_flow_start;
  278. MQTTregisterSubscribeFunction(maintopic + "/ctrl/flow_start", subHandler); // subcribe to maintopic/ctrl/flow_start
  279. if (subscribeFunktionMap != NULL) {
  280. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  281. int msg_id = esp_mqtt_client_subscribe(client, it->first.c_str(), 0);
  282. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "topic " + it->first + " subscribe successful, msg_id=" + std::to_string(msg_id));
  283. }
  284. }
  285. vTaskDelay(10000 / portTICK_PERIOD_MS); // Delay execution of callback routine after connection got established
  286. if (callbackOnConnected) { // Call onConnected callback routine --> mqtt_server
  287. callbackOnConnected(maintopic, SetRetainFlag);
  288. }
  289. }
  290. }
  291. void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
  292. ESP_LOGD(TAG, "MQTTregisteronnectFunction %s\r\n", name.c_str());
  293. if (connectFunktionMap == NULL) {
  294. connectFunktionMap = new std::map<std::string, std::function<void()>>();
  295. }
  296. if ((*connectFunktionMap)[name] != NULL) {
  297. ESP_LOGW(TAG, "connect function %s already registred", name.c_str());
  298. return;
  299. }
  300. (*connectFunktionMap)[name] = func;
  301. if (mqtt_connected) {
  302. func();
  303. }
  304. }
  305. void MQTTunregisterConnectFunction(std::string name){
  306. ESP_LOGD(TAG, "unregisterConnnectFunction %s\r\n", name.c_str());
  307. if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
  308. connectFunktionMap->erase(name);
  309. }
  310. }
  311. void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
  312. ESP_LOGD(TAG, "registerSubscribeFunction %s", topic.c_str());
  313. if (subscribeFunktionMap == NULL) {
  314. subscribeFunktionMap = new std::map<std::string, std::function<bool(std::string, char*, int)>>();
  315. }
  316. if ((*subscribeFunktionMap)[topic] != NULL) {
  317. ESP_LOGW(TAG, "topic %s already registered for subscription", topic.c_str());
  318. return;
  319. }
  320. (*subscribeFunktionMap)[topic] = func;
  321. }
  322. void MQTTdestroySubscribeFunction(){
  323. if (subscribeFunktionMap != NULL) {
  324. if (mqtt_connected) {
  325. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  326. int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
  327. ESP_LOGD(TAG, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);
  328. }
  329. }
  330. subscribeFunktionMap->clear();
  331. delete subscribeFunktionMap;
  332. subscribeFunktionMap = NULL;
  333. }
  334. }
  335. #endif //ENABLE_MQTT