interface_mqtt.cpp 15 KB

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