interface_mqtt.cpp 14 KB

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