interface_mqtt.cpp 10 KB

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