interface_mqtt.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. #define __HIDE_PASSWORD
  9. //#define DEBUG_DETAIL_ON
  10. static const char *TAG = "MQTT IF";
  11. std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
  12. std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFunktionMap = NULL;
  13. int failedOnRound = -1;
  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, SetRetainFlag;
  23. void (*callbackOnConnected)(std::string, int) = NULL;
  24. bool MQTTPublish(std::string _key, std::string _content, int 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. int msg_id;
  73. std::string topic = "";
  74. switch (event->event_id) {
  75. case MQTT_EVENT_BEFORE_CONNECT:
  76. ESP_LOGD(TAG, "MQTT_EVENT_BEFORE_CONNECT");
  77. mqtt_initialized = true;
  78. break;
  79. case MQTT_EVENT_CONNECTED:
  80. ESP_LOGD(TAG, "MQTT_EVENT_CONNECTED");
  81. mqtt_initialized = true;
  82. mqtt_connected = true;
  83. MQTTconnected();
  84. break;
  85. case MQTT_EVENT_DISCONNECTED:
  86. ESP_LOGD(TAG, "MQTT_EVENT_DISCONNECTED");
  87. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Disconnected from broker");
  88. mqtt_connected = false;
  89. break;
  90. case MQTT_EVENT_SUBSCRIBED:
  91. ESP_LOGD(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
  92. msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
  93. ESP_LOGD(TAG, "sent publish successful, msg_id=%d", msg_id);
  94. break;
  95. case MQTT_EVENT_UNSUBSCRIBED:
  96. ESP_LOGD(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
  97. break;
  98. case MQTT_EVENT_PUBLISHED:
  99. ESP_LOGD(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
  100. break;
  101. case MQTT_EVENT_DATA:
  102. ESP_LOGD(TAG, "MQTT_EVENT_DATA");
  103. ESP_LOGD(TAG, "TOPIC=%.*s\r\n", event->topic_len, event->topic);
  104. ESP_LOGD(TAG, "DATA=%.*s\r\n", event->data_len, event->data);
  105. topic.assign(event->topic, event->topic_len);
  106. if (subscribeFunktionMap != NULL) {
  107. if (subscribeFunktionMap->find(topic) != subscribeFunktionMap->end()) {
  108. ESP_LOGD(TAG, "call handler function\r\n");
  109. (*subscribeFunktionMap)[topic](topic, event->data, event->data_len);
  110. }
  111. } else {
  112. ESP_LOGW(TAG, "no handler available\r\n");
  113. }
  114. break;
  115. case MQTT_EVENT_ERROR:
  116. #ifdef DEBUG_DETAIL_ON
  117. ESP_LOGD(TAG, "MQTT_EVENT_ERROR - esp_mqtt_error_codes:");
  118. ESP_LOGD(TAG, "error_type:%d", event->error_handle->error_type);
  119. ESP_LOGD(TAG, "connect_return_code:%d", event->error_handle->connect_return_code);
  120. ESP_LOGD(TAG, "esp_transport_sock_errno:%d", event->error_handle->esp_transport_sock_errno);
  121. ESP_LOGD(TAG, "esp_tls_last_esp_err:%d", event->error_handle->esp_tls_last_esp_err);
  122. ESP_LOGD(TAG, "esp_tls_stack_err:%d", event->error_handle->esp_tls_stack_err);
  123. ESP_LOGD(TAG, "esp_tls_cert_verify_flags:%d", event->error_handle->esp_tls_cert_verify_flags);
  124. #endif
  125. mqtt_connected = false;
  126. break;
  127. default:
  128. ESP_LOGD(TAG, "Other event id:%d", event->event_id);
  129. break;
  130. }
  131. return ESP_OK;
  132. }
  133. static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
  134. ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
  135. mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data);
  136. }
  137. bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
  138. std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
  139. int _keepalive, int _SetRetainFlag, void *_callbackOnConnected) {
  140. if ((_mqttURI.length() == 0) || (_maintopic.length() == 0) || (_clientid.length() == 0))
  141. {
  142. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init aborted! Config error (URI, MainTopic or ClientID missing)");
  143. return false;
  144. }
  145. uri = _mqttURI;
  146. client_id = _clientid;
  147. lwt_topic = _maintopic + "/" + _lwt;
  148. lwt_connected = _lwt_connected;
  149. lwt_disconnected = _lwt_disconnected;
  150. keepalive = _keepalive;
  151. SetRetainFlag = _SetRetainFlag;
  152. maintopic = _maintopic;
  153. callbackOnConnected = ( void (*)(std::string, int) )(_callbackOnConnected);
  154. if (_user.length() && _password.length()){
  155. user = _user;
  156. password = _password;
  157. }
  158. #ifdef __HIDE_PASSWORD
  159. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: XXXXXXXX, maintopic: "
  160. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  161. #else
  162. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: " + password + ", maintopic: "
  163. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  164. #endif
  165. mqtt_configOK = true;
  166. return true;
  167. }
  168. int MQTT_Init() {
  169. if (mqtt_initialized) {
  170. return 0;
  171. }
  172. if (mqtt_configOK) {
  173. mqtt_enabled = true;
  174. } else {
  175. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but client is not yet configured.");
  176. return 0;
  177. }
  178. if (!getWIFIisConnected()) {
  179. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but WIFI is not yet connected.");
  180. return 0;
  181. }
  182. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init");
  183. MQTTdestroy_client();
  184. esp_mqtt_client_config_t mqtt_cfg = {
  185. .uri = uri.c_str(),
  186. .client_id = client_id.c_str(),
  187. .lwt_topic = lwt_topic.c_str(),
  188. .lwt_msg = lwt_disconnected.c_str(),
  189. .lwt_retain = 1,
  190. .lwt_msg_len = (int)(lwt_disconnected.length()),
  191. .keepalive = keepalive,
  192. .disable_auto_reconnect = false, // Reconnection routine active (Default: false)
  193. .buffer_size = 1536, // size of MQTT send/receive buffer (Default: 1024)
  194. .reconnect_timeout_ms = 15000, // Try to reconnect to broker (Default: 10000ms)
  195. .network_timeout_ms = 20000, // Network Timeout (Default: 10000ms)
  196. .message_retransmit_timeout = 3000 // Tiem after message resent when broker not acknowledged (QoS1, QoS2)
  197. };
  198. if (user.length() && password.length()){
  199. mqtt_cfg.username = user.c_str();
  200. mqtt_cfg.password = password.c_str();
  201. }
  202. #ifdef DEBUG_DETAIL_ON
  203. LogFile.WriteHeapInfo("MQTT Client Init");
  204. #endif
  205. client = esp_mqtt_client_init(&mqtt_cfg);
  206. if (client)
  207. {
  208. esp_err_t ret = esp_mqtt_client_register_event(client, esp_mqtt_ID, mqtt_event_handler, client);
  209. if (ret != ESP_OK)
  210. {
  211. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not register event (ret=" + std::to_string(ret) + ")!");
  212. mqtt_initialized = false;
  213. return -1;
  214. }
  215. #ifdef DEBUG_DETAIL_ON
  216. LogFile.WriteHeapInfo("MQTT Client Start");
  217. #endif
  218. ret = esp_mqtt_client_start(client);
  219. if (ret != ESP_OK)
  220. {
  221. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Client start failed (retval=" + std::to_string(ret) + ")!");
  222. mqtt_initialized = false;
  223. return -1;
  224. }
  225. else {
  226. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Client started, waiting for established connection...");
  227. mqtt_initialized = true;
  228. return 1;
  229. }
  230. }
  231. else
  232. {
  233. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init failed, no handle created!");
  234. mqtt_initialized = false;
  235. return -1;
  236. }
  237. }
  238. void MQTTdestroy_client() {
  239. if (client) {
  240. if (mqtt_connected) {
  241. esp_mqtt_client_disconnect(client);
  242. mqtt_connected = false;
  243. }
  244. esp_mqtt_client_stop(client);
  245. esp_mqtt_client_destroy(client);
  246. client = NULL;
  247. mqtt_initialized = false;
  248. }
  249. }
  250. bool getMQTTisEnabled() {
  251. return mqtt_enabled;
  252. }
  253. bool getMQTTisConnected() {
  254. return mqtt_connected;
  255. }
  256. void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
  257. ESP_LOGD(TAG, "MQTTregisteronnectFunction %s\r\n", name.c_str());
  258. if (connectFunktionMap == NULL) {
  259. connectFunktionMap = new std::map<std::string, std::function<void()>>();
  260. }
  261. if ((*connectFunktionMap)[name] != NULL) {
  262. ESP_LOGW(TAG, "connect function %s already registred", name.c_str());
  263. return;
  264. }
  265. (*connectFunktionMap)[name] = func;
  266. if (mqtt_connected) {
  267. func();
  268. }
  269. }
  270. void MQTTunregisterConnectFunction(std::string name){
  271. ESP_LOGD(TAG, "unregisterConnnectFunction %s\r\n", name.c_str());
  272. if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
  273. connectFunktionMap->erase(name);
  274. }
  275. }
  276. void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
  277. ESP_LOGD(TAG, "registerSubscribeFunction %s\r\n", topic.c_str());
  278. if (subscribeFunktionMap == NULL) {
  279. subscribeFunktionMap = new std::map<std::string, std::function<bool(std::string, char*, int)>>();
  280. }
  281. if ((*subscribeFunktionMap)[topic] != NULL) {
  282. ESP_LOGW(TAG, "topic %s already registered for subscription", topic.c_str());
  283. return;
  284. }
  285. (*subscribeFunktionMap)[topic] = func;
  286. if (mqtt_connected) {
  287. int msg_id = esp_mqtt_client_subscribe(client, topic.c_str(), 0);
  288. ESP_LOGD(TAG, "topic %s subscribe successful, msg_id=%d", topic.c_str(), msg_id);
  289. }
  290. }
  291. void MQTTconnected(){
  292. if (mqtt_connected) {
  293. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to broker");
  294. MQTTPublish(lwt_topic, lwt_connected, true);
  295. if (connectFunktionMap != NULL) {
  296. for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
  297. it->second();
  298. ESP_LOGD(TAG, "call connect function %s", it->first.c_str());
  299. }
  300. }
  301. if (subscribeFunktionMap != NULL) {
  302. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  303. int msg_id = esp_mqtt_client_subscribe(client, it->first.c_str(), 0);
  304. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "topic " + it->first + " subscribe successful, msg_id=" + std::to_string(msg_id));
  305. }
  306. }
  307. if (callbackOnConnected) {
  308. callbackOnConnected(maintopic, SetRetainFlag);
  309. }
  310. }
  311. }
  312. void MQTTdestroySubscribeFunction(){
  313. if (subscribeFunktionMap != NULL) {
  314. if (mqtt_connected) {
  315. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  316. int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
  317. ESP_LOGI(TAG, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);
  318. }
  319. }
  320. subscribeFunktionMap->clear();
  321. delete subscribeFunktionMap;
  322. subscribeFunktionMap = NULL;
  323. }
  324. }
  325. #endif //ENABLE_MQTT