interface_mqtt.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #include "interface_mqtt.h"
  2. //#define LOG_LOCAL_LEVEL ESP_LOG_DEBUG
  3. #include "esp_log.h"
  4. #include "mqtt_client.h"
  5. #include "ClassLogFile.h"
  6. #define __HIDE_PASSWORD
  7. static const char *TAG_INTERFACEMQTT = "interface_mqtt";
  8. std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
  9. std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFunktionMap = NULL;
  10. esp_mqtt_event_id_t esp_mmqtt_ID = MQTT_EVENT_ANY;
  11. // ESP_EVENT_ANY_ID
  12. bool mqtt_connected = false;
  13. esp_mqtt_client_handle_t client = NULL;
  14. std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic;
  15. int keepalive, SetRetainFlag;
  16. void (*callbackOnConnected)(std::string, int) = NULL;
  17. bool MQTTPublish(std::string _key, std::string _content, int retained_flag) {
  18. int msg_id;
  19. std::string zw;
  20. if (!mqtt_connected) {
  21. LogFile.WriteToFile(ESP_LOG_WARN, "MQTT - Not connected, trying to re-connect...");
  22. if (!MQTT_Init()) {
  23. if (!MQTT_Init()) { // Retry
  24. LogFile.WriteToFile(ESP_LOG_ERROR, "MQTT - Failed to init!");
  25. return false;
  26. }
  27. }
  28. }
  29. msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, 1, retained_flag);
  30. if (msg_id < 0) {
  31. LogFile.WriteToFile(ESP_LOG_WARN, "MQTT - Failed to publish topic '" + _key + "', re-trying...");
  32. msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, 1, retained_flag);
  33. if (msg_id < 0) {
  34. LogFile.WriteToFile(ESP_LOG_ERROR, "MQTT - Failed to publish topic '" + _key + "'!");
  35. mqtt_connected = false; // Force re-init on next call
  36. return false;
  37. }
  38. }
  39. if (_content.length() > 80) { // Truncate message if too long
  40. _content.resize(80);
  41. _content.append("..");
  42. }
  43. zw = "MQTT - Published topic: " + _key + ", content: " + _content + " (msg_id=" + std::to_string(msg_id) + ")";
  44. LogFile.WriteToFile(ESP_LOG_DEBUG, zw);
  45. return true;
  46. }
  47. static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
  48. {
  49. int msg_id;
  50. std::string topic = "";
  51. switch (event->event_id) {
  52. case MQTT_EVENT_BEFORE_CONNECT:
  53. ESP_LOGI(TAG_INTERFACEMQTT, "MQTT_EVENT_BEFORE_CONNECT");
  54. break;
  55. case MQTT_EVENT_CONNECTED:
  56. ESP_LOGI(TAG_INTERFACEMQTT, "MQTT_EVENT_CONNECTED");
  57. mqtt_connected = true;
  58. MQTTconnected();
  59. break;
  60. case MQTT_EVENT_DISCONNECTED:
  61. ESP_LOGI(TAG_INTERFACEMQTT, "MQTT_EVENT_DISCONNECTED");
  62. mqtt_connected = false; // Force re-init on next call
  63. esp_mqtt_client_reconnect(client);
  64. break;
  65. case MQTT_EVENT_SUBSCRIBED:
  66. ESP_LOGI(TAG_INTERFACEMQTT, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
  67. msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
  68. ESP_LOGI(TAG_INTERFACEMQTT, "sent publish successful, msg_id=%d", msg_id);
  69. break;
  70. case MQTT_EVENT_UNSUBSCRIBED:
  71. ESP_LOGI(TAG_INTERFACEMQTT, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
  72. break;
  73. case MQTT_EVENT_PUBLISHED:
  74. ESP_LOGI(TAG_INTERFACEMQTT, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
  75. break;
  76. case MQTT_EVENT_DATA:
  77. ESP_LOGI(TAG_INTERFACEMQTT, "MQTT_EVENT_DATA");
  78. ESP_LOGI(TAG_INTERFACEMQTT, "TOPIC=%.*s\r\n", event->topic_len, event->topic);
  79. ESP_LOGI(TAG_INTERFACEMQTT, "DATA=%.*s\r\n", event->data_len, event->data);
  80. topic.assign(event->topic, event->topic_len);
  81. if (subscribeFunktionMap != NULL) {
  82. if (subscribeFunktionMap->find(topic) != subscribeFunktionMap->end()) {
  83. ESP_LOGD(TAG_INTERFACEMQTT, "call handler function\r\n");
  84. (*subscribeFunktionMap)[topic](topic, event->data, event->data_len);
  85. }
  86. } else {
  87. ESP_LOGW(TAG_INTERFACEMQTT, "no handler available\r\n");
  88. }
  89. break;
  90. case MQTT_EVENT_ERROR:
  91. ESP_LOGI(TAG_INTERFACEMQTT, "MQTT_EVENT_ERROR");
  92. mqtt_connected = false; // Force re-init on next call
  93. break;
  94. default:
  95. ESP_LOGI(TAG_INTERFACEMQTT, "Other event id:%d", event->event_id);
  96. break;
  97. }
  98. return ESP_OK;
  99. }
  100. static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
  101. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0))
  102. ESP_LOGD(TAG_INTERFACEMQTT, "Event dispatched from event loop base=%s, event_id=%ld", base, event_id);
  103. #else
  104. ESP_LOGD(TAG_INTERFACEMQTT, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
  105. #endif
  106. mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data);
  107. }
  108. void MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
  109. std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
  110. int _keepalive, int _SetRetainFlag, void *_callbackOnConnected){
  111. #ifdef __HIDE_PASSWORD
  112. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT Configuration: uri: " + _mqttURI + ", clientname: " + _clientid +
  113. ", user: " + _user + ", password: XXXXXXXX, maintopic: " + _maintopic + ", last-will-topic: " + _maintopic + "/" + _lwt + ", keepAlive: " + std::to_string(_keepalive));
  114. #else
  115. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT Configuration: uri: " + _mqttURI + ", clientname: " + _clientid +
  116. ", user: " + _user + ", password: " + _password + ", maintopic: " + _maintopic + ", last-will-topic: " + _maintopic + "/" + _lwt + ", keepAlive: " + std::to_string(_keepalive));
  117. #endif
  118. uri = _mqttURI;
  119. client_id = _clientid;
  120. lwt_topic = _maintopic + "/" + _lwt;
  121. lwt_connected = _lwt_connected;
  122. lwt_disconnected = _lwt_disconnected;
  123. keepalive = _keepalive;
  124. SetRetainFlag = _SetRetainFlag;
  125. maintopic = _maintopic;
  126. callbackOnConnected = ( void (*)(std::string, int) )(_callbackOnConnected);
  127. if (_user.length() && _password.length()){
  128. user = _user;
  129. password = _password;
  130. }
  131. }
  132. bool MQTT_Init() {
  133. esp_mqtt_client_config_t mqtt_cfg;
  134. esp_err_t ret;
  135. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT - Init");
  136. MQTTdestroy_client();
  137. std::string lw = lwt_disconnected;
  138. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0))
  139. mqtt_cfg.broker.address.uri = uri.c_str();
  140. mqtt_cfg.credentials.client_id = client_id.c_str();
  141. mqtt_cfg.session.last_will.topic = lwt_topic.c_str();
  142. mqtt_cfg.session.last_will.msg = lw.c_str();
  143. mqtt_cfg.session.last_will.msg_len = (int)(lw.length());
  144. mqtt_cfg.session.last_will.retain = 1;
  145. mqtt_cfg.session.keepalive = keepalive;
  146. #else
  147. mqtt_cfg.uri = uri.c_str();
  148. mqtt_cfg.client_id = client_id.c_str();
  149. mqtt_cfg.lwt_topic = lwt_topic.c_str();
  150. mqtt_cfg.lwt_msg = lw.c_str();
  151. mqtt_cfg.lwt_retain = 1;
  152. mqtt_cfg.lwt_msg_len = (int)(lw.length());
  153. mqtt_cfg.keepalive = keepalive;
  154. #endif
  155. if (user.length() && password.length()){
  156. #if (ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0))
  157. mqtt_cfg.credentials.username = user.c_str();
  158. mqtt_cfg.credentials.authentication.password = password.c_str();
  159. mqtt_cfg.credentials.authentication.key_password_len = password.length();
  160. #else
  161. mqtt_cfg.username = user.c_str();
  162. mqtt_cfg.password = password.c_str();
  163. #endif
  164. };
  165. client = esp_mqtt_client_init(&mqtt_cfg);
  166. if (client)
  167. {
  168. ret = esp_mqtt_client_register_event(client, esp_mmqtt_ID, mqtt_event_handler, client);
  169. if (ret != ESP_OK)
  170. {
  171. LogFile.WriteToFile(ESP_LOG_ERROR, "MQTT - Could not register event (ret=" + std::to_string(ret) + ")!");
  172. return false;
  173. }
  174. ret = esp_mqtt_client_start(client);
  175. if (ret != ESP_OK)
  176. {
  177. LogFile.WriteToFile(ESP_LOG_WARN, "MQTT - Could not start client (ret=" + std::to_string(ret) + "), retrying...");
  178. ret = esp_mqtt_client_start(client);
  179. if (ret != ESP_OK)
  180. {
  181. LogFile.WriteToFile(ESP_LOG_ERROR, "MQTT - Could not start client (ret=" + std::to_string(ret) + ")!");
  182. return false;
  183. }
  184. }
  185. }
  186. else
  187. {
  188. LogFile.WriteToFile(ESP_LOG_ERROR, "MQTT - Could not init client!");
  189. return false;
  190. }
  191. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT - Init successful");
  192. return true;
  193. }
  194. void MQTTdestroy_client() {
  195. if (client != NULL) {
  196. esp_mqtt_client_stop(client);
  197. esp_mqtt_client_destroy(client);
  198. }
  199. }
  200. bool MQTTisConnected() {
  201. return mqtt_connected;
  202. }
  203. void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
  204. ESP_LOGD(TAG_INTERFACEMQTT, "MQTTregisteronnectFunction %s\r\n", name.c_str());
  205. if (connectFunktionMap == NULL) {
  206. connectFunktionMap = new std::map<std::string, std::function<void()>>();
  207. }
  208. if ((*connectFunktionMap)[name] != NULL) {
  209. ESP_LOGW(TAG_INTERFACEMQTT, "connect function %s already registred", name.c_str());
  210. return;
  211. }
  212. (*connectFunktionMap)[name] = func;
  213. if (mqtt_connected) {
  214. func();
  215. }
  216. }
  217. void MQTTunregisterConnectFunction(std::string name){
  218. ESP_LOGD(TAG_INTERFACEMQTT, "MQTTregisteronnectFunction %s\r\n", name.c_str());
  219. if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
  220. connectFunktionMap->erase(name);
  221. }
  222. }
  223. void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
  224. ESP_LOGD(TAG_INTERFACEMQTT, "MQTTregisterSubscribeFunction %s\r\n", topic.c_str());
  225. if (subscribeFunktionMap == NULL) {
  226. subscribeFunktionMap = new std::map<std::string, std::function<bool(std::string, char*, int)>>();
  227. }
  228. if ((*subscribeFunktionMap)[topic] != NULL) {
  229. ESP_LOGW(TAG_INTERFACEMQTT, "topic %s already registred for subscription", topic.c_str());
  230. return;
  231. }
  232. (*subscribeFunktionMap)[topic] = func;
  233. if (mqtt_connected) {
  234. int msg_id = esp_mqtt_client_subscribe(client, topic.c_str(), 0);
  235. ESP_LOGD(TAG_INTERFACEMQTT, "topic %s subscribe successful, msg_id=%d", topic.c_str(), msg_id);
  236. }
  237. }
  238. void MQTTconnected(){
  239. if (mqtt_connected) {
  240. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT - Connected");
  241. MQTTPublish(lwt_topic, lwt_connected, true);
  242. if (connectFunktionMap != NULL) {
  243. for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
  244. it->second();
  245. ESP_LOGD(TAG_INTERFACEMQTT, "call connect function %s", it->first.c_str());
  246. }
  247. }
  248. if (subscribeFunktionMap != NULL) {
  249. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  250. int msg_id = esp_mqtt_client_subscribe(client, it->first.c_str(), 0);
  251. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT - topic " + it->first + " subscribe successful, msg_id=" + std::to_string(msg_id));
  252. }
  253. }
  254. if (callbackOnConnected) {
  255. callbackOnConnected(maintopic, SetRetainFlag);
  256. }
  257. }
  258. }
  259. void MQTTdestroySubscribeFunction(){
  260. if (subscribeFunktionMap != NULL) {
  261. if (mqtt_connected) {
  262. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  263. int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
  264. ESP_LOGI(TAG_INTERFACEMQTT, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);
  265. }
  266. }
  267. subscribeFunktionMap->clear();
  268. delete subscribeFunktionMap;
  269. subscribeFunktionMap = NULL;
  270. }
  271. }