interface_mqtt.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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_LOGD(TAG_INTERFACEMQTT, "MQTT_EVENT_BEFORE_CONNECT");
  54. break;
  55. case MQTT_EVENT_CONNECTED:
  56. ESP_LOGD(TAG_INTERFACEMQTT, "MQTT_EVENT_CONNECTED");
  57. mqtt_connected = true;
  58. MQTTconnected();
  59. break;
  60. case MQTT_EVENT_DISCONNECTED:
  61. ESP_LOGD(TAG_INTERFACEMQTT, "MQTT_EVENT_DISCONNECTED");
  62. LogFile.WriteToFile(ESP_LOG_WARN, "MQTT - Disconnected, going to re-connect...");
  63. mqtt_connected = false; // Force re-init on next call
  64. esp_mqtt_client_reconnect(client);
  65. break;
  66. case MQTT_EVENT_SUBSCRIBED:
  67. ESP_LOGD(TAG_INTERFACEMQTT, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
  68. msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
  69. ESP_LOGD(TAG_INTERFACEMQTT, "sent publish successful, msg_id=%d", msg_id);
  70. break;
  71. case MQTT_EVENT_UNSUBSCRIBED:
  72. ESP_LOGD(TAG_INTERFACEMQTT, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
  73. break;
  74. case MQTT_EVENT_PUBLISHED:
  75. ESP_LOGD(TAG_INTERFACEMQTT, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
  76. break;
  77. case MQTT_EVENT_DATA:
  78. ESP_LOGD(TAG_INTERFACEMQTT, "MQTT_EVENT_DATA");
  79. ESP_LOGD(TAG_INTERFACEMQTT, "TOPIC=%.*s", event->topic_len, event->topic);
  80. ESP_LOGD(TAG_INTERFACEMQTT, "DATA=%.*s", event->data_len, event->data);
  81. topic.assign(event->topic, event->topic_len);
  82. if (subscribeFunktionMap != NULL) {
  83. if (subscribeFunktionMap->find(topic) != subscribeFunktionMap->end()) {
  84. ESP_LOGD(TAG_INTERFACEMQTT, "call handler function");
  85. (*subscribeFunktionMap)[topic](topic, event->data, event->data_len);
  86. }
  87. } else {
  88. ESP_LOGW(TAG_INTERFACEMQTT, "no handler available");
  89. }
  90. break;
  91. case MQTT_EVENT_ERROR:
  92. ESP_LOGD(TAG_INTERFACEMQTT, "MQTT_EVENT_ERROR");
  93. mqtt_connected = false; // Force re-init on next call
  94. break;
  95. default:
  96. ESP_LOGD(TAG_INTERFACEMQTT, "Other event id:%d", event->event_id);
  97. break;
  98. }
  99. return ESP_OK;
  100. }
  101. static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
  102. ESP_LOGD(TAG_INTERFACEMQTT, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
  103. mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data);
  104. }
  105. void MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
  106. std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
  107. int _keepalive, int _SetRetainFlag, void *_callbackOnConnected){
  108. #ifdef __HIDE_PASSWORD
  109. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT Configuration: uri: " + _mqttURI + ", clientname: " + _clientid +
  110. ", user: " + _user + ", password: XXXXXXXX, maintopic: " + _maintopic + ", last-will-topic: " + _maintopic + "/" + _lwt + ", keepAlive: " + std::to_string(_keepalive) + " s");
  111. #else
  112. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT Configuration: uri: " + _mqttURI + ", clientname: " + _clientid +
  113. ", user: " + _user + ", password: " + _password + ", maintopic: " + _maintopic + ", last-will-topic: " + _maintopic + "/" + _lwt + ", keepAlive: " + std::to_string(_keepalive)+ " s");
  114. #endif
  115. uri = _mqttURI;
  116. client_id = _clientid;
  117. lwt_topic = _maintopic + "/" + _lwt;
  118. lwt_connected = _lwt_connected;
  119. lwt_disconnected = _lwt_disconnected;
  120. keepalive = _keepalive;
  121. SetRetainFlag = _SetRetainFlag;
  122. maintopic = _maintopic;
  123. callbackOnConnected = ( void (*)(std::string, int) )(_callbackOnConnected);
  124. if (_user.length() && _password.length()){
  125. user = _user;
  126. password = _password;
  127. }
  128. }
  129. bool MQTT_Init() {
  130. esp_err_t ret;
  131. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT - Init");
  132. MQTTdestroy_client();
  133. std::string lw = lwt_disconnected;
  134. esp_mqtt_client_config_t mqtt_cfg = {
  135. .uri = uri.c_str(),
  136. .client_id = client_id.c_str(),
  137. .lwt_topic = lwt_topic.c_str(),
  138. .lwt_msg = lw.c_str(),
  139. .lwt_retain = 1,
  140. .lwt_msg_len = (int)(lw.length()),
  141. .keepalive = keepalive
  142. };
  143. if (user.length() && password.length()){
  144. mqtt_cfg.username = user.c_str();
  145. mqtt_cfg.password = password.c_str();
  146. };
  147. client = esp_mqtt_client_init(&mqtt_cfg);
  148. if (client)
  149. {
  150. ret = esp_mqtt_client_register_event(client, esp_mmqtt_ID, mqtt_event_handler, client);
  151. if (ret != ESP_OK)
  152. {
  153. LogFile.WriteToFile(ESP_LOG_ERROR, "MQTT - Could not register event (ret=" + std::to_string(ret) + ")!");
  154. return false;
  155. }
  156. ret = esp_mqtt_client_start(client);
  157. if (ret != ESP_OK)
  158. {
  159. LogFile.WriteToFile(ESP_LOG_WARN, "MQTT - Could not start client (ret=" + std::to_string(ret) + "), retrying...");
  160. ret = esp_mqtt_client_start(client);
  161. if (ret != ESP_OK)
  162. {
  163. LogFile.WriteToFile(ESP_LOG_ERROR, "MQTT - Could not start client (ret=" + std::to_string(ret) + ")!");
  164. return false;
  165. }
  166. }
  167. }
  168. else
  169. {
  170. LogFile.WriteToFile(ESP_LOG_ERROR, "MQTT - Could not init client!");
  171. return false;
  172. }
  173. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT - Init successful");
  174. return true;
  175. }
  176. void MQTTdestroy_client() {
  177. if (client != NULL) {
  178. esp_mqtt_client_stop(client);
  179. esp_mqtt_client_destroy(client);
  180. }
  181. }
  182. bool MQTTisConnected() {
  183. return mqtt_connected;
  184. }
  185. void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
  186. ESP_LOGD(TAG_INTERFACEMQTT, "MQTTregisteronnectFunction %s", name.c_str());
  187. if (connectFunktionMap == NULL) {
  188. connectFunktionMap = new std::map<std::string, std::function<void()>>();
  189. }
  190. if ((*connectFunktionMap)[name] != NULL) {
  191. ESP_LOGW(TAG_INTERFACEMQTT, "connect function %s already registred", name.c_str());
  192. return;
  193. }
  194. (*connectFunktionMap)[name] = func;
  195. if (mqtt_connected) {
  196. func();
  197. }
  198. }
  199. void MQTTunregisterConnectFunction(std::string name){
  200. ESP_LOGD(TAG_INTERFACEMQTT, "MQTTregisteronnectFunction %s", name.c_str());
  201. if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
  202. connectFunktionMap->erase(name);
  203. }
  204. }
  205. void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
  206. ESP_LOGD(TAG_INTERFACEMQTT, "MQTTregisterSubscribeFunction %s", topic.c_str());
  207. if (subscribeFunktionMap == NULL) {
  208. subscribeFunktionMap = new std::map<std::string, std::function<bool(std::string, char*, int)>>();
  209. }
  210. if ((*subscribeFunktionMap)[topic] != NULL) {
  211. ESP_LOGW(TAG_INTERFACEMQTT, "topic %s already registred for subscription", topic.c_str());
  212. return;
  213. }
  214. (*subscribeFunktionMap)[topic] = func;
  215. if (mqtt_connected) {
  216. int msg_id = esp_mqtt_client_subscribe(client, topic.c_str(), 0);
  217. ESP_LOGD(TAG_INTERFACEMQTT, "topic %s subscribe successful, msg_id=%d", topic.c_str(), msg_id);
  218. }
  219. }
  220. void MQTTconnected(){
  221. if (mqtt_connected) {
  222. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT - Connected");
  223. MQTTPublish(lwt_topic, lwt_connected, true);
  224. if (connectFunktionMap != NULL) {
  225. for(std::map<std::string, std::function<void()>>::iterator it = connectFunktionMap->begin(); it != connectFunktionMap->end(); ++it) {
  226. it->second();
  227. ESP_LOGD(TAG_INTERFACEMQTT, "call connect function %s", it->first.c_str());
  228. }
  229. }
  230. if (subscribeFunktionMap != NULL) {
  231. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  232. int msg_id = esp_mqtt_client_subscribe(client, it->first.c_str(), 0);
  233. LogFile.WriteToFile(ESP_LOG_INFO, "MQTT - topic " + it->first + " subscribe successful, msg_id=" + std::to_string(msg_id));
  234. }
  235. }
  236. if (callbackOnConnected) {
  237. callbackOnConnected(maintopic, SetRetainFlag);
  238. }
  239. }
  240. }
  241. void MQTTdestroySubscribeFunction(){
  242. if (subscribeFunktionMap != NULL) {
  243. if (mqtt_connected) {
  244. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  245. int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
  246. ESP_LOGI(TAG_INTERFACEMQTT, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);
  247. }
  248. }
  249. subscribeFunktionMap->clear();
  250. delete subscribeFunktionMap;
  251. subscribeFunktionMap = NULL;
  252. }
  253. }