interface_mqtt.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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, int qos, 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, qos, 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, qos, 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. // http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033 --> chapter 3.2.2.3
  118. // The server does not support the level of the MQTT protocol requested by the client
  119. // NOTE: Only protocol 3.1.1 is supported (refer to setting in sdkconfig)
  120. if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_PROTOCOL) {
  121. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, unacceptable protocol version (0x01)");
  122. }
  123. // The client identifier is correct UTF-8 but not allowed by the server
  124. // e.g. clientID empty (cannot be the case -> default set in firmware)
  125. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_ID_REJECTED) {
  126. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, identifier rejected (0x02)");
  127. }
  128. // The network connection has been made but the MQTT service is unavailable
  129. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_SERVER_UNAVAILABLE) {
  130. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, Server unavailable (0x03)");
  131. }
  132. // The data in the user name or password is malformed
  133. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_BAD_USERNAME) {
  134. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, malformed data in username or password (0x04)");
  135. }
  136. // The client is not authorized to connect
  137. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED) {
  138. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, not authorized. Check username/password (0x05)");
  139. }
  140. #ifdef DEBUG_DETAIL_ON
  141. ESP_LOGD(TAG, "MQTT_EVENT_ERROR - esp_mqtt_error_codes:");
  142. ESP_LOGD(TAG, "error_type:%d", event->error_handle->error_type);
  143. ESP_LOGD(TAG, "connect_return_code:%d", event->error_handle->connect_return_code);
  144. ESP_LOGD(TAG, "esp_transport_sock_errno:%d", event->error_handle->esp_transport_sock_errno);
  145. ESP_LOGD(TAG, "esp_tls_last_esp_err:%d", event->error_handle->esp_tls_last_esp_err);
  146. ESP_LOGD(TAG, "esp_tls_stack_err:%d", event->error_handle->esp_tls_stack_err);
  147. ESP_LOGD(TAG, "esp_tls_cert_verify_flags:%d", event->error_handle->esp_tls_cert_verify_flags);
  148. #endif
  149. break;
  150. default:
  151. ESP_LOGD(TAG, "Other event id:%d", event->event_id);
  152. break;
  153. }
  154. return ESP_OK;
  155. }
  156. static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
  157. ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
  158. mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data);
  159. }
  160. bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
  161. std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
  162. int _keepalive, bool _SetRetainFlag, void *_callbackOnConnected) {
  163. if ((_mqttURI.length() == 0) || (_maintopic.length() == 0) || (_clientid.length() == 0))
  164. {
  165. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init aborted! Config error (URI, MainTopic or ClientID missing)");
  166. return false;
  167. }
  168. uri = _mqttURI;
  169. client_id = _clientid;
  170. lwt_topic = _maintopic + "/" + _lwt;
  171. lwt_connected = _lwt_connected;
  172. lwt_disconnected = _lwt_disconnected;
  173. keepalive = _keepalive;
  174. SetRetainFlag = _SetRetainFlag;
  175. maintopic = _maintopic;
  176. callbackOnConnected = ( void (*)(std::string, bool) )(_callbackOnConnected);
  177. if (_user.length() && _password.length()){
  178. user = _user;
  179. password = _password;
  180. }
  181. #ifdef __HIDE_PASSWORD
  182. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: XXXXXXXX, maintopic: "
  183. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  184. #else
  185. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: " + password + ", maintopic: "
  186. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  187. #endif
  188. mqtt_configOK = true;
  189. return true;
  190. }
  191. int MQTT_Init() {
  192. if (mqtt_initialized) {
  193. return 0;
  194. }
  195. if (mqtt_configOK) {
  196. mqtt_enabled = true;
  197. } else {
  198. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but client is not yet configured.");
  199. return 0;
  200. }
  201. if (!getWIFIisConnected()) {
  202. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but WIFI is not yet connected.");
  203. return 0;
  204. }
  205. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init");
  206. MQTTdestroy_client(false);
  207. esp_mqtt_client_config_t mqtt_cfg = {
  208. .uri = uri.c_str(),
  209. .client_id = client_id.c_str(),
  210. .lwt_topic = lwt_topic.c_str(),
  211. .lwt_msg = lwt_disconnected.c_str(),
  212. .lwt_retain = 1,
  213. .lwt_msg_len = (int)(lwt_disconnected.length()),
  214. .keepalive = keepalive,
  215. .disable_auto_reconnect = false, // Reconnection routine active (Default: false)
  216. .buffer_size = 1536, // size of MQTT send/receive buffer (Default: 1024)
  217. .reconnect_timeout_ms = 15000, // Try to reconnect to broker (Default: 10000ms)
  218. .network_timeout_ms = 20000, // Network Timeout (Default: 10000ms)
  219. .message_retransmit_timeout = 3000 // Time after message resent when broker not acknowledged (QoS1, QoS2)
  220. };
  221. if (user.length() && password.length()){
  222. mqtt_cfg.username = user.c_str();
  223. mqtt_cfg.password = password.c_str();
  224. }
  225. #ifdef DEBUG_DETAIL_ON
  226. LogFile.WriteHeapInfo("MQTT Client Init");
  227. #endif
  228. client = esp_mqtt_client_init(&mqtt_cfg);
  229. if (client)
  230. {
  231. esp_err_t ret = esp_mqtt_client_register_event(client, esp_mqtt_ID, mqtt_event_handler, client);
  232. if (ret != ESP_OK)
  233. {
  234. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not register event (ret=" + std::to_string(ret) + ")!");
  235. mqtt_initialized = false;
  236. return -1;
  237. }
  238. #ifdef DEBUG_DETAIL_ON
  239. LogFile.WriteHeapInfo("MQTT Client Start");
  240. #endif
  241. ret = esp_mqtt_client_start(client);
  242. if (ret != ESP_OK)
  243. {
  244. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Client start failed (retval=" + std::to_string(ret) + ")!");
  245. mqtt_initialized = false;
  246. return -1;
  247. }
  248. else {
  249. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Client started, waiting for established connection...");
  250. mqtt_initialized = true;
  251. return 1;
  252. }
  253. }
  254. else
  255. {
  256. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init failed, no handle created!");
  257. mqtt_initialized = false;
  258. return -1;
  259. }
  260. }
  261. void MQTTdestroy_client(bool _disable = false) {
  262. if (client) {
  263. if (mqtt_connected) {
  264. MQTTdestroySubscribeFunction();
  265. esp_mqtt_client_disconnect(client);
  266. mqtt_connected = false;
  267. }
  268. esp_mqtt_client_stop(client);
  269. esp_mqtt_client_destroy(client);
  270. client = NULL;
  271. mqtt_initialized = false;
  272. }
  273. if (_disable) // Disable MQTT service, avoid restart with MQTTPublish
  274. mqtt_configOK = false;
  275. }
  276. bool getMQTTisEnabled() {
  277. return mqtt_enabled;
  278. }
  279. bool getMQTTisConnected() {
  280. return mqtt_connected;
  281. }
  282. bool mqtt_handler_flow_start(std::string _topic, char* _data, int _data_len) {
  283. ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
  284. if (_data_len > 0) {
  285. MQTTCtrlFlowStart(_topic);
  286. }
  287. return ESP_OK;
  288. }
  289. void MQTTconnected(){
  290. if (mqtt_connected) {
  291. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to broker");
  292. if (connectFunktionMap != NULL) {
  293. for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
  294. it->second();
  295. ESP_LOGD(TAG, "call connect function %s", it->first.c_str());
  296. }
  297. }
  298. /* Subcribe to topics */
  299. std::function<bool(std::string topic, char* data, int data_len)> subHandler = mqtt_handler_flow_start;
  300. MQTTregisterSubscribeFunction(maintopic + "/ctrl/flow_start", subHandler); // subcribe to maintopic/ctrl/flow_start
  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_DEBUG, TAG, "topic " + it->first + " subscribe successful, msg_id=" + std::to_string(msg_id));
  305. }
  306. }
  307. /* Send Static Topics and Homeassistant Discovery */
  308. if (callbackOnConnected) { // Call onConnected callback routine --> mqtt_server
  309. callbackOnConnected(maintopic, SetRetainFlag);
  310. }
  311. }
  312. }
  313. void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
  314. ESP_LOGD(TAG, "MQTTregisteronnectFunction %s\r\n", name.c_str());
  315. if (connectFunktionMap == NULL) {
  316. connectFunktionMap = new std::map<std::string, std::function<void()>>();
  317. }
  318. if ((*connectFunktionMap)[name] != NULL) {
  319. ESP_LOGW(TAG, "connect function %s already registred", name.c_str());
  320. return;
  321. }
  322. (*connectFunktionMap)[name] = func;
  323. if (mqtt_connected) {
  324. func();
  325. }
  326. }
  327. void MQTTunregisterConnectFunction(std::string name){
  328. ESP_LOGD(TAG, "unregisterConnnectFunction %s\r\n", name.c_str());
  329. if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
  330. connectFunktionMap->erase(name);
  331. }
  332. }
  333. void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
  334. ESP_LOGD(TAG, "registerSubscribeFunction %s", topic.c_str());
  335. if (subscribeFunktionMap == NULL) {
  336. subscribeFunktionMap = new std::map<std::string, std::function<bool(std::string, char*, int)>>();
  337. }
  338. if ((*subscribeFunktionMap)[topic] != NULL) {
  339. ESP_LOGW(TAG, "topic %s already registered for subscription", topic.c_str());
  340. return;
  341. }
  342. (*subscribeFunktionMap)[topic] = func;
  343. }
  344. void MQTTdestroySubscribeFunction(){
  345. if (subscribeFunktionMap != NULL) {
  346. if (mqtt_connected) {
  347. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  348. int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
  349. ESP_LOGD(TAG, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);
  350. }
  351. }
  352. subscribeFunktionMap->clear();
  353. delete subscribeFunktionMap;
  354. subscribeFunktionMap = NULL;
  355. }
  356. }
  357. #endif //ENABLE_MQTT