interface_mqtt.cpp 15 KB

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