interface_mqtt.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. esp_mqtt_client_config_t mqtt_cfg = { };
  209. mqtt_cfg.broker.address.uri = uri.c_str();
  210. mqtt_cfg.credentials.client_id = client_id.c_str();
  211. mqtt_cfg.network.disable_auto_reconnect = false; // Reconnection routine active (Default: false)
  212. mqtt_cfg.network.reconnect_timeout_ms = 15000; // Try to reconnect to broker (Default: 10000ms)
  213. mqtt_cfg.network.timeout_ms = 20000; // Network Timeout (Default: 10000ms)
  214. mqtt_cfg.session.message_retransmit_timeout = 3000; // Time after message resent when broker not acknowledged (QoS1, QoS2)
  215. mqtt_cfg.session.last_will.topic = lwt_topic.c_str();
  216. mqtt_cfg.session.last_will.retain = 1;
  217. mqtt_cfg.session.last_will.msg = lwt_disconnected.c_str();
  218. mqtt_cfg.session.last_will.msg_len = (int)(lwt_disconnected.length());
  219. mqtt_cfg.session.keepalive = keepalive;
  220. mqtt_cfg.buffer.size = 1536; // size of MQTT send/receive buffer (Default: 1024)
  221. if (user.length() && password.length()){
  222. mqtt_cfg.credentials.username = user.c_str();
  223. mqtt_cfg.credentials.authentication.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. {
  284. ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
  285. if (_data_len > 0) {
  286. MQTTCtrlFlowStart(_topic);
  287. }
  288. else {
  289. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_flow_start: handler called, but no data");
  290. }
  291. return ESP_OK;
  292. }
  293. bool mqtt_handler_set_prevalue(std::string _topic, char* _data, int _data_len)
  294. {
  295. //ESP_LOGD(TAG, "Handler called: topic %s, data %.*s", _topic.c_str(), _data_len, _data);
  296. //example: {"numbersname": "main", "value": 12345.1234567}
  297. if (_data_len > 0) { // Check if data length > 0
  298. cJSON *jsonData = cJSON_Parse(_data);
  299. cJSON *numbersname = cJSON_GetObjectItemCaseSensitive(jsonData, "numbersname");
  300. cJSON *value = cJSON_GetObjectItemCaseSensitive(jsonData, "value");
  301. if (cJSON_IsString(numbersname) && (numbersname->valuestring != NULL)) { // Check if numbersname is valid
  302. if (cJSON_IsNumber(value)) { // Check if value is a number
  303. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "handler_set_prevalue called: numbersname: " + std::string(numbersname->valuestring) +
  304. ", value: " + std::to_string(value->valuedouble));
  305. if (flowctrl.UpdatePrevalue(std::to_string(value->valuedouble), std::string(numbersname->valuestring), true))
  306. return ESP_OK;
  307. }
  308. else {
  309. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: value not a valid number (\"value\": 12345.12345)");
  310. }
  311. }
  312. else {
  313. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: numbersname not a valid string (\"numbersname\": \"main\")");
  314. }
  315. }
  316. else {
  317. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "handler_set_prevalue: handler called, but no data received");
  318. }
  319. return ESP_FAIL;
  320. }
  321. void MQTTconnected(){
  322. if (mqtt_connected) {
  323. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to broker");
  324. if (connectFunktionMap != NULL) {
  325. for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
  326. it->second();
  327. ESP_LOGD(TAG, "call connect function %s", it->first.c_str());
  328. }
  329. }
  330. // Subcribe to topics
  331. // Note: Further subsriptions are handled in GPIO class
  332. //*****************************************
  333. std::function<bool(std::string topic, char* data, int data_len)> subHandler1 = mqtt_handler_flow_start;
  334. MQTTregisterSubscribeFunction(maintopic + "/ctrl/flow_start", subHandler1); // subcribe to maintopic/ctrl/flow_start
  335. std::function<bool(std::string topic, char* data, int data_len)> subHandler2 = mqtt_handler_set_prevalue;
  336. MQTTregisterSubscribeFunction(maintopic + "/ctrl/set_prevalue", subHandler2); // subcribe to maintopic/ctrl/set_prevalue
  337. if (subscribeFunktionMap != NULL) {
  338. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  339. int msg_id = esp_mqtt_client_subscribe(client, it->first.c_str(), 0);
  340. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "topic " + it->first + " subscribe successful, msg_id=" + std::to_string(msg_id));
  341. }
  342. }
  343. /* Send Static Topics and Homeassistant Discovery */
  344. if (callbackOnConnected) { // Call onConnected callback routine --> mqtt_server
  345. callbackOnConnected(maintopic, SetRetainFlag);
  346. }
  347. }
  348. }
  349. void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
  350. ESP_LOGD(TAG, "MQTTregisteronnectFunction %s\r\n", name.c_str());
  351. if (connectFunktionMap == NULL) {
  352. connectFunktionMap = new std::map<std::string, std::function<void()>>();
  353. }
  354. if ((*connectFunktionMap)[name] != NULL) {
  355. ESP_LOGW(TAG, "connect function %s already registred", name.c_str());
  356. return;
  357. }
  358. (*connectFunktionMap)[name] = func;
  359. if (mqtt_connected) {
  360. func();
  361. }
  362. }
  363. void MQTTunregisterConnectFunction(std::string name){
  364. ESP_LOGD(TAG, "unregisterConnnectFunction %s\r\n", name.c_str());
  365. if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
  366. connectFunktionMap->erase(name);
  367. }
  368. }
  369. void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
  370. ESP_LOGD(TAG, "registerSubscribeFunction %s", topic.c_str());
  371. if (subscribeFunktionMap == NULL) {
  372. subscribeFunktionMap = new std::map<std::string, std::function<bool(std::string, char*, int)>>();
  373. }
  374. if ((*subscribeFunktionMap)[topic] != NULL) {
  375. ESP_LOGW(TAG, "topic %s already registered for subscription", topic.c_str());
  376. return;
  377. }
  378. (*subscribeFunktionMap)[topic] = func;
  379. }
  380. void MQTTdestroySubscribeFunction(){
  381. if (subscribeFunktionMap != NULL) {
  382. if (mqtt_connected) {
  383. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  384. int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
  385. ESP_LOGD(TAG, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);
  386. }
  387. }
  388. subscribeFunktionMap->clear();
  389. delete subscribeFunktionMap;
  390. subscribeFunktionMap = NULL;
  391. }
  392. }
  393. #endif //ENABLE_MQTT