interface_mqtt.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 "MainFlowControl.h"
  8. #include "cJSON.h"
  9. #include "../../include/defines.h"
  10. #if DEBUG_DETAIL_ON
  11. #include "esp_timer.h"
  12. #endif
  13. static const char *TAG = "MQTT IF";
  14. std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
  15. std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFunktionMap = NULL;
  16. int failedOnRound = -1;
  17. int MQTTReconnectCnt = 0;
  18. esp_mqtt_event_id_t esp_mqtt_ID = MQTT_EVENT_ANY;
  19. // ESP_EVENT_ANY_ID
  20. bool mqtt_enabled = false;
  21. bool mqtt_configOK = false;
  22. bool mqtt_initialized = false;
  23. bool mqtt_connected = false;
  24. esp_mqtt_client_handle_t client = NULL;
  25. std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic;
  26. int keepalive;
  27. bool SetRetainFlag;
  28. void (*callbackOnConnected)(std::string, bool) = NULL;
  29. bool MQTTPublish(std::string _key, std::string _content, int qos, bool retained_flag)
  30. {
  31. if (!mqtt_enabled) { // MQTT sevice not started / configured (MQTT_Init not called before)
  32. return false;
  33. }
  34. if (failedOnRound == getCountFlowRounds()) { // we already failed in this round, do not retry until the next round
  35. return true; // Fail quietly
  36. }
  37. #ifdef DEBUG_DETAIL_ON
  38. LogFile.WriteHeapInfo("MQTT Publish");
  39. #endif
  40. MQTT_Init(); // Re-Init client if not initialized yet/anymore
  41. if (mqtt_initialized && mqtt_connected) {
  42. #ifdef DEBUG_DETAIL_ON
  43. long long int starttime = esp_timer_get_time();
  44. #endif
  45. int msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, qos, retained_flag);
  46. #ifdef DEBUG_DETAIL_ON
  47. ESP_LOGD(TAG, "Publish msg_id %d in %lld ms", msg_id, (esp_timer_get_time() - starttime)/1000);
  48. #endif
  49. if (msg_id == -1) {
  50. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Failed to publish topic '" + _key + "', re-trying...");
  51. #ifdef DEBUG_DETAIL_ON
  52. starttime = esp_timer_get_time();
  53. #endif
  54. msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, qos, retained_flag);
  55. #ifdef DEBUG_DETAIL_ON
  56. ESP_LOGD(TAG, "Publish msg_id %d in %lld ms", msg_id, (esp_timer_get_time() - starttime)/1000);
  57. #endif
  58. if (msg_id == -1) {
  59. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to publish topic '" + _key + "', skipping all MQTT publishings in this round!");
  60. failedOnRound = getCountFlowRounds();
  61. return false;
  62. }
  63. }
  64. if (_content.length() > 80) { // Truncate message if too long
  65. _content.resize(80);
  66. _content.append("..");
  67. }
  68. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Published topic: " + _key + ", content: " + _content + " (msg_id=" + std::to_string(msg_id) + ")");
  69. return true;
  70. }
  71. else {
  72. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Publish skipped. Client not initalized or not connected. (topic: " + _key + ")");
  73. return false;
  74. }
  75. }
  76. static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event) {
  77. std::string topic = "";
  78. switch (event->event_id) {
  79. case MQTT_EVENT_BEFORE_CONNECT:
  80. mqtt_initialized = true;
  81. break;
  82. case MQTT_EVENT_CONNECTED:
  83. MQTTReconnectCnt = 0;
  84. mqtt_initialized = true;
  85. mqtt_connected = true;
  86. MQTTconnected();
  87. break;
  88. case MQTT_EVENT_DISCONNECTED:
  89. mqtt_connected = false;
  90. MQTTReconnectCnt++;
  91. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected, trying to reconnect");
  92. if (MQTTReconnectCnt >= 5) {
  93. MQTTReconnectCnt = 0;
  94. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Disconnected, multiple reconnect attempts failed, still retrying...");
  95. }
  96. break;
  97. case MQTT_EVENT_SUBSCRIBED:
  98. ESP_LOGD(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
  99. break;
  100. case MQTT_EVENT_UNSUBSCRIBED:
  101. ESP_LOGD(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
  102. break;
  103. case MQTT_EVENT_PUBLISHED:
  104. ESP_LOGD(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
  105. break;
  106. case MQTT_EVENT_DATA:
  107. ESP_LOGD(TAG, "MQTT_EVENT_DATA");
  108. ESP_LOGD(TAG, "TOPIC=%.*s", event->topic_len, event->topic);
  109. ESP_LOGD(TAG, "DATA=%.*s", event->data_len, event->data);
  110. topic.assign(event->topic, event->topic_len);
  111. if (subscribeFunktionMap != NULL) {
  112. if (subscribeFunktionMap->find(topic) != subscribeFunktionMap->end()) {
  113. ESP_LOGD(TAG, "call subcribe function for topic %s", topic.c_str());
  114. (*subscribeFunktionMap)[topic](topic, event->data, event->data_len);
  115. }
  116. } else {
  117. ESP_LOGW(TAG, "no handler available\r\n");
  118. }
  119. break;
  120. case MQTT_EVENT_ERROR:
  121. // http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718033 --> chapter 3.2.2.3
  122. // The server does not support the level of the MQTT protocol requested by the client
  123. // NOTE: Only protocol 3.1.1 is supported (refer to setting in sdkconfig)
  124. if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_PROTOCOL) {
  125. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, unacceptable protocol version (0x01)");
  126. }
  127. // The client identifier is correct UTF-8 but not allowed by the server
  128. // e.g. clientID empty (cannot be the case -> default set in firmware)
  129. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_ID_REJECTED) {
  130. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, identifier rejected (0x02)");
  131. }
  132. // The network connection has been made but the MQTT service is unavailable
  133. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_SERVER_UNAVAILABLE) {
  134. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, Server unavailable (0x03)");
  135. }
  136. // The data in the user name or password is malformed
  137. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_BAD_USERNAME) {
  138. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, malformed data in username or password (0x04)");
  139. }
  140. // The client is not authorized to connect
  141. else if (event->error_handle->connect_return_code == MQTT_CONNECTION_REFUSE_NOT_AUTHORIZED) {
  142. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Connection refused, not authorized. Check username/password (0x05)");
  143. }
  144. #ifdef DEBUG_DETAIL_ON
  145. ESP_LOGD(TAG, "MQTT_EVENT_ERROR - esp_mqtt_error_codes:");
  146. ESP_LOGD(TAG, "error_type:%d", event->error_handle->error_type);
  147. ESP_LOGD(TAG, "connect_return_code:%d", event->error_handle->connect_return_code);
  148. ESP_LOGD(TAG, "esp_transport_sock_errno:%d", event->error_handle->esp_transport_sock_errno);
  149. ESP_LOGD(TAG, "esp_tls_last_esp_err:%d", event->error_handle->esp_tls_last_esp_err);
  150. ESP_LOGD(TAG, "esp_tls_stack_err:%d", event->error_handle->esp_tls_stack_err);
  151. ESP_LOGD(TAG, "esp_tls_cert_verify_flags:%d", event->error_handle->esp_tls_cert_verify_flags);
  152. #endif
  153. break;
  154. default:
  155. ESP_LOGD(TAG, "Other event id:%d", event->event_id);
  156. break;
  157. }
  158. return ESP_OK;
  159. }
  160. static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
  161. ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, (int)event_id);
  162. mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data);
  163. }
  164. bool MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
  165. std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
  166. int _keepalive, bool _SetRetainFlag, void *_callbackOnConnected) {
  167. if ((_mqttURI.length() == 0) || (_maintopic.length() == 0) || (_clientid.length() == 0))
  168. {
  169. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init aborted! Config error (URI, MainTopic or ClientID missing)");
  170. return false;
  171. }
  172. uri = _mqttURI;
  173. client_id = _clientid;
  174. lwt_topic = _maintopic + "/" + _lwt;
  175. lwt_connected = _lwt_connected;
  176. lwt_disconnected = _lwt_disconnected;
  177. keepalive = _keepalive;
  178. SetRetainFlag = _SetRetainFlag;
  179. maintopic = _maintopic;
  180. callbackOnConnected = ( void (*)(std::string, bool) )(_callbackOnConnected);
  181. if (_user.length() && _password.length()){
  182. user = _user;
  183. password = _password;
  184. }
  185. #ifdef __HIDE_PASSWORD
  186. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: XXXXXXXX, maintopic: "
  187. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  188. #else
  189. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "URI: " + uri + ", clientname: " + client_id + ", user: " + user + ", password: " + password + ", maintopic: "
  190. + maintopic + ", last-will-topic: " + lwt_topic + ", keepAlive: " + std::to_string(keepalive) + ", RetainFlag: " + std::to_string(SetRetainFlag));
  191. #endif
  192. mqtt_configOK = true;
  193. return true;
  194. }
  195. int MQTT_Init() {
  196. if (mqtt_initialized) {
  197. return 0;
  198. }
  199. if (mqtt_configOK) {
  200. mqtt_enabled = true;
  201. } else {
  202. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but client is not yet configured.");
  203. return 0;
  204. }
  205. if (!getWIFIisConnected()) {
  206. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init called, but WIFI is not yet connected.");
  207. return 0;
  208. }
  209. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init");
  210. MQTTdestroy_client(false);
  211. esp_mqtt_client_config_t mqtt_cfg = { };
  212. mqtt_cfg.broker.address.uri = uri.c_str();
  213. mqtt_cfg.credentials.client_id = client_id.c_str();
  214. mqtt_cfg.network.disable_auto_reconnect = false; // Reconnection routine active (Default: false)
  215. mqtt_cfg.network.reconnect_timeout_ms = 15000; // Try to reconnect to broker (Default: 10000ms)
  216. mqtt_cfg.network.timeout_ms = 20000; // Network Timeout (Default: 10000ms)
  217. mqtt_cfg.session.message_retransmit_timeout = 3000; // Time after message resent when broker not acknowledged (QoS1, QoS2)
  218. mqtt_cfg.session.last_will.topic = lwt_topic.c_str();
  219. mqtt_cfg.session.last_will.retain = 1;
  220. mqtt_cfg.session.last_will.msg = lwt_disconnected.c_str();
  221. mqtt_cfg.session.last_will.msg_len = (int)(lwt_disconnected.length());
  222. mqtt_cfg.session.keepalive = keepalive;
  223. mqtt_cfg.buffer.size = 1536; // size of MQTT send/receive buffer (Default: 1024)
  224. if (user.length() && password.length()){
  225. mqtt_cfg.credentials.username = user.c_str();
  226. mqtt_cfg.credentials.authentication.password = password.c_str();
  227. }
  228. #ifdef DEBUG_DETAIL_ON
  229. LogFile.WriteHeapInfo("MQTT Client Init");
  230. #endif
  231. client = esp_mqtt_client_init(&mqtt_cfg);
  232. if (client)
  233. {
  234. esp_err_t ret = esp_mqtt_client_register_event(client, esp_mqtt_ID, mqtt_event_handler, client);
  235. if (ret != ESP_OK)
  236. {
  237. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not register event (ret=" + std::to_string(ret) + ")!");
  238. mqtt_initialized = false;
  239. return -1;
  240. }
  241. #ifdef DEBUG_DETAIL_ON
  242. LogFile.WriteHeapInfo("MQTT Client Start");
  243. #endif
  244. ret = esp_mqtt_client_start(client);
  245. if (ret != ESP_OK)
  246. {
  247. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Client start failed (retval=" + std::to_string(ret) + ")!");
  248. mqtt_initialized = false;
  249. return -1;
  250. }
  251. else {
  252. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Client started, waiting for established connection...");
  253. mqtt_initialized = true;
  254. return 1;
  255. }
  256. }
  257. else
  258. {
  259. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Init failed, no handle created!");
  260. mqtt_initialized = false;
  261. return -1;
  262. }
  263. }
  264. void MQTTdestroy_client(bool _disable = false) {
  265. if (client) {
  266. if (mqtt_connected) {
  267. MQTTdestroySubscribeFunction();
  268. esp_mqtt_client_disconnect(client);
  269. mqtt_connected = false;
  270. }
  271. esp_mqtt_client_stop(client);
  272. esp_mqtt_client_destroy(client);
  273. client = NULL;
  274. mqtt_initialized = false;
  275. }
  276. if (_disable) // Disable MQTT service, avoid restart with MQTTPublish
  277. mqtt_configOK = false;
  278. }
  279. bool getMQTTisEnabled() {
  280. return mqtt_enabled;
  281. }
  282. bool getMQTTisConnected() {
  283. return mqtt_connected;
  284. }
  285. bool mqtt_handler_flow_start(std::string _topic, char* _data, int _data_len)
  286. {
  287. ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
  288. if (_data_len > 0) {
  289. MQTTCtrlFlowStart(_topic);
  290. }
  291. else {
  292. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_flow_start: handler called, but no data");
  293. }
  294. return ESP_OK;
  295. }
  296. bool mqtt_handler_set_prevalue(std::string _topic, char* _data, int _data_len)
  297. {
  298. //ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
  299. //example: {"numbersname": "main", "value": 12345.1234567}
  300. if (_data_len > 0) { // Check if data length > 0
  301. cJSON *jsonData = cJSON_Parse(_data);
  302. cJSON *numbersname = cJSON_GetObjectItemCaseSensitive(jsonData, "numbersname");
  303. cJSON *value = cJSON_GetObjectItemCaseSensitive(jsonData, "value");
  304. if (cJSON_IsString(numbersname) && (numbersname->valuestring != NULL)) { // Check if numbersname is valid
  305. if (cJSON_IsNumber(value)) { // Check if value is a number
  306. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_set_prevalue called: numbersname: " + std::string(numbersname->valuestring) +
  307. ", value: " + std::to_string(value->valuedouble));
  308. if (flowctrl.UpdatePrevalue(std::to_string(value->valuedouble), std::string(numbersname->valuestring), true)) {
  309. cJSON_Delete(jsonData);
  310. return ESP_OK;
  311. }
  312. }
  313. else {
  314. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: value not a valid number (\"value\": 12345.12345)");
  315. }
  316. }
  317. else {
  318. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: numbersname not a valid string (\"numbersname\": \"main\")");
  319. }
  320. cJSON_Delete(jsonData);
  321. }
  322. else {
  323. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: handler called, but no data received");
  324. }
  325. return ESP_FAIL;
  326. }
  327. void MQTTconnected(){
  328. if (mqtt_connected) {
  329. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to broker");
  330. if (connectFunktionMap != NULL) {
  331. for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
  332. it->second();
  333. ESP_LOGD(TAG, "call connect function %s", it->first.c_str());
  334. }
  335. }
  336. // Subcribe to topics
  337. // Note: Further subsriptions are handled in GPIO class
  338. //*****************************************
  339. std::function<bool(std::string topic, char* data, int data_len)> subHandler1 = mqtt_handler_flow_start;
  340. MQTTregisterSubscribeFunction(maintopic + "/ctrl/flow_start", subHandler1); // subcribe to maintopic/ctrl/flow_start
  341. std::function<bool(std::string topic, char* data, int data_len)> subHandler2 = mqtt_handler_set_prevalue;
  342. MQTTregisterSubscribeFunction(maintopic + "/ctrl/set_prevalue", subHandler2); // subcribe to maintopic/ctrl/set_prevalue
  343. if (subscribeFunktionMap != NULL) {
  344. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  345. int msg_id = esp_mqtt_client_subscribe(client, it->first.c_str(), 0);
  346. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "topic " + it->first + " subscribe successful, msg_id=" + std::to_string(msg_id));
  347. }
  348. }
  349. /* Send Static Topics and Homeassistant Discovery */
  350. if (callbackOnConnected) { // Call onConnected callback routine --> mqtt_server
  351. callbackOnConnected(maintopic, SetRetainFlag);
  352. }
  353. }
  354. }
  355. void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
  356. ESP_LOGD(TAG, "MQTTregisteronnectFunction %s\r\n", name.c_str());
  357. if (connectFunktionMap == NULL) {
  358. connectFunktionMap = new std::map<std::string, std::function<void()>>();
  359. }
  360. if ((*connectFunktionMap)[name] != NULL) {
  361. ESP_LOGW(TAG, "connect function %s already registred", name.c_str());
  362. return;
  363. }
  364. (*connectFunktionMap)[name] = func;
  365. if (mqtt_connected) {
  366. func();
  367. }
  368. }
  369. void MQTTunregisterConnectFunction(std::string name){
  370. ESP_LOGD(TAG, "unregisterConnnectFunction %s\r\n", name.c_str());
  371. if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
  372. connectFunktionMap->erase(name);
  373. }
  374. }
  375. void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
  376. ESP_LOGD(TAG, "registerSubscribeFunction %s", topic.c_str());
  377. if (subscribeFunktionMap == NULL) {
  378. subscribeFunktionMap = new std::map<std::string, std::function<bool(std::string, char*, int)>>();
  379. }
  380. if ((*subscribeFunktionMap)[topic] != NULL) {
  381. ESP_LOGW(TAG, "topic %s already registered for subscription", topic.c_str());
  382. return;
  383. }
  384. (*subscribeFunktionMap)[topic] = func;
  385. }
  386. void MQTTdestroySubscribeFunction(){
  387. if (subscribeFunktionMap != NULL) {
  388. if (mqtt_connected) {
  389. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  390. int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
  391. ESP_LOGD(TAG, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);
  392. }
  393. }
  394. subscribeFunktionMap->clear();
  395. delete subscribeFunktionMap;
  396. subscribeFunktionMap = NULL;
  397. }
  398. }
  399. #endif //ENABLE_MQTT