interface_mqtt.cpp 10 KB

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