interface_mqtt.cpp 11 KB

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