interface_mqtt.cpp 10 KB

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