interface_mqtt.cpp 20 KB

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