interface_mqtt.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. #include "server_tflite.h"
  7. #define __HIDE_PASSWORD
  8. static const char *TAG = "MQTT INTERFACE";
  9. std::map<std::string, std::function<void()>>* connectFunktionMap = NULL;
  10. std::map<std::string, std::function<bool(std::string, char*, int)>>* subscribeFunktionMap = NULL;
  11. int failedOnRound = -1;
  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. std::string uri, client_id, lwt_topic, lwt_connected, lwt_disconnected, user, password, maintopic;
  17. int keepalive, SetRetainFlag;
  18. void (*callbackOnConnected)(std::string, int) = NULL;
  19. bool MQTTPublish(std::string _key, std::string _content, int retained_flag) {
  20. int msg_id;
  21. std::string zw;
  22. if (failedOnRound == getCountFlowRounds()) { // we already failed in this round, do not retry until the next round
  23. return true; // Fail quietly
  24. }
  25. LogFile.WriteHeapInfo("MQTT Publish");
  26. if (!mqtt_connected) {
  27. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Not connected, trying to re-connect...");
  28. if (!MQTT_Init()) {
  29. if (!MQTT_Init()) { // Retry
  30. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to init, skipping all MQTT publishings in this round!");
  31. failedOnRound = getCountFlowRounds();
  32. return false;
  33. }
  34. }
  35. }
  36. msg_id = esp_mqtt_client_publish(client, _key.c_str(), _content.c_str(), 0, 1, retained_flag);
  37. if (msg_id < 0) {
  38. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Failed to publish topic '" + _key + "', re-trying...");
  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(ESP_LOG_ERROR, TAG, "Failed to publish topic '" + _key + "', skipping all MQTT publishings in this round!");
  42. mqtt_connected = false; // Force re-init on next call
  43. failedOnRound = getCountFlowRounds();
  44. return false;
  45. }
  46. }
  47. if (_content.length() > 80) { // Truncate message if too long
  48. _content.resize(80);
  49. _content.append("..");
  50. }
  51. zw = "Published topic: " + _key + ", content: " + _content + " (msg_id=" + std::to_string(msg_id) + ")";
  52. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, zw);
  53. return true;
  54. }
  55. static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
  56. {
  57. int msg_id;
  58. std::string topic = "";
  59. switch (event->event_id) {
  60. case MQTT_EVENT_BEFORE_CONNECT:
  61. ESP_LOGD(TAG, "MQTT_EVENT_BEFORE_CONNECT");
  62. break;
  63. case MQTT_EVENT_CONNECTED:
  64. ESP_LOGD(TAG, "MQTT_EVENT_CONNECTED");
  65. mqtt_connected = true;
  66. MQTTconnected();
  67. break;
  68. case MQTT_EVENT_DISCONNECTED:
  69. ESP_LOGD(TAG, "MQTT_EVENT_DISCONNECTED");
  70. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected! Going to re-connect...");
  71. mqtt_connected = false; // Force re-init on next call
  72. esp_mqtt_client_reconnect(client);
  73. break;
  74. case MQTT_EVENT_SUBSCRIBED:
  75. ESP_LOGD(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
  76. msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
  77. ESP_LOGD(TAG, "sent publish successful, msg_id=%d", msg_id);
  78. break;
  79. case MQTT_EVENT_UNSUBSCRIBED:
  80. ESP_LOGD(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
  81. break;
  82. case MQTT_EVENT_PUBLISHED:
  83. ESP_LOGD(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
  84. break;
  85. case MQTT_EVENT_DATA:
  86. ESP_LOGD(TAG, "MQTT_EVENT_DATA");
  87. ESP_LOGD(TAG, "TOPIC=%.*s\r\n", event->topic_len, event->topic);
  88. ESP_LOGD(TAG, "DATA=%.*s\r\n", event->data_len, event->data);
  89. topic.assign(event->topic, event->topic_len);
  90. if (subscribeFunktionMap != NULL) {
  91. if (subscribeFunktionMap->find(topic) != subscribeFunktionMap->end()) {
  92. ESP_LOGD(TAG, "call handler function\r\n");
  93. (*subscribeFunktionMap)[topic](topic, event->data, event->data_len);
  94. }
  95. } else {
  96. ESP_LOGW(TAG, "no handler available\r\n");
  97. }
  98. break;
  99. case MQTT_EVENT_ERROR:
  100. ESP_LOGD(TAG, "MQTT_EVENT_ERROR");
  101. mqtt_connected = false; // Force re-init on next call
  102. break;
  103. default:
  104. ESP_LOGD(TAG, "Other event id:%d", event->event_id);
  105. break;
  106. }
  107. return ESP_OK;
  108. }
  109. static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
  110. ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%d", base, event_id);
  111. mqtt_event_handler_cb((esp_mqtt_event_handle_t) event_data);
  112. }
  113. void MQTT_Configure(std::string _mqttURI, std::string _clientid, std::string _user, std::string _password,
  114. std::string _maintopic, std::string _lwt, std::string _lwt_connected, std::string _lwt_disconnected,
  115. int _keepalive, int _SetRetainFlag, void *_callbackOnConnected){
  116. #ifdef __HIDE_PASSWORD
  117. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "URI: " + _mqttURI + ", clientname: " + _clientid +
  118. ", user: " + _user + ", password: XXXXXXXX, maintopic: " + _maintopic + ", last-will-topic: " + _maintopic + "/" + _lwt + ", keepAlive: " + std::to_string(_keepalive));
  119. #else
  120. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "URI: " + _mqttURI + ", clientname: " + _clientid +
  121. ", user: " + _user + ", password: " + _password + ", maintopic: " + _maintopic + ", last-will-topic: " + _maintopic + "/" + _lwt + ", keepAlive: " + std::to_string(_keepalive));
  122. #endif
  123. uri = _mqttURI;
  124. client_id = _clientid;
  125. lwt_topic = _maintopic + "/" + _lwt;
  126. lwt_connected = _lwt_connected;
  127. lwt_disconnected = _lwt_disconnected;
  128. keepalive = _keepalive;
  129. SetRetainFlag = _SetRetainFlag;
  130. maintopic = _maintopic;
  131. callbackOnConnected = ( void (*)(std::string, int) )(_callbackOnConnected);
  132. if (_user.length() && _password.length()){
  133. user = _user;
  134. password = _password;
  135. }
  136. }
  137. bool MQTT_Init() {
  138. esp_err_t ret;
  139. LogFile.WriteToFile(ESP_LOG_INFO, TAG, std::string("Init"));
  140. MQTTdestroy_client();
  141. std::string lw = lwt_disconnected;
  142. esp_mqtt_client_config_t mqtt_cfg = {
  143. .uri = uri.c_str(),
  144. .client_id = client_id.c_str(),
  145. .lwt_topic = lwt_topic.c_str(),
  146. .lwt_msg = lw.c_str(),
  147. .lwt_retain = 1,
  148. .lwt_msg_len = (int)(lw.length()),
  149. .keepalive = keepalive
  150. };
  151. if (user.length() && password.length()){
  152. mqtt_cfg.username = user.c_str();
  153. mqtt_cfg.password = password.c_str();
  154. };
  155. LogFile.WriteHeapInfo("MQTT Client Init");
  156. client = esp_mqtt_client_init(&mqtt_cfg);
  157. if (client)
  158. {
  159. ret = esp_mqtt_client_register_event(client, esp_mmqtt_ID, mqtt_event_handler, client);
  160. if (ret != ESP_OK)
  161. {
  162. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not register event (ret=" + std::to_string(ret) + ")!");
  163. return false;
  164. }
  165. LogFile.WriteHeapInfo("MQTT Client Start");
  166. ret = esp_mqtt_client_start(client);
  167. if (ret != ESP_OK)
  168. {
  169. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Could not start client (ret=" + std::to_string(ret) + "), retrying...");
  170. ret = esp_mqtt_client_start(client);
  171. if (ret != ESP_OK)
  172. {
  173. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not start client (ret=" + std::to_string(ret) + ")!");
  174. return false;
  175. }
  176. }
  177. }
  178. else
  179. {
  180. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Could not init client!");
  181. return false;
  182. }
  183. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init successful");
  184. return true;
  185. }
  186. void MQTTdestroy_client() {
  187. if (client != NULL) {
  188. esp_mqtt_client_stop(client);
  189. esp_mqtt_client_destroy(client);
  190. }
  191. }
  192. bool MQTTisConnected() {
  193. return mqtt_connected;
  194. }
  195. void MQTTregisterConnectFunction(std::string name, std::function<void()> func){
  196. ESP_LOGD(TAG, "MQTTregisteronnectFunction %s\r\n", name.c_str());
  197. if (connectFunktionMap == NULL) {
  198. connectFunktionMap = new std::map<std::string, std::function<void()>>();
  199. }
  200. if ((*connectFunktionMap)[name] != NULL) {
  201. ESP_LOGW(TAG, "connect function %s already registred", name.c_str());
  202. return;
  203. }
  204. (*connectFunktionMap)[name] = func;
  205. if (mqtt_connected) {
  206. func();
  207. }
  208. }
  209. void MQTTunregisterConnectFunction(std::string name){
  210. ESP_LOGD(TAG, "unregisterConnnectFunction %s\r\n", name.c_str());
  211. if ((connectFunktionMap != NULL) && (connectFunktionMap->find(name) != connectFunktionMap->end())) {
  212. connectFunktionMap->erase(name);
  213. }
  214. }
  215. void MQTTregisterSubscribeFunction(std::string topic, std::function<bool(std::string, char*, int)> func){
  216. ESP_LOGD(TAG, "registerSubscribeFunction %s\r\n", topic.c_str());
  217. if (subscribeFunktionMap == NULL) {
  218. subscribeFunktionMap = new std::map<std::string, std::function<bool(std::string, char*, int)>>();
  219. }
  220. if ((*subscribeFunktionMap)[topic] != NULL) {
  221. ESP_LOGW(TAG, "topic %s already registered for subscription", topic.c_str());
  222. return;
  223. }
  224. (*subscribeFunktionMap)[topic] = func;
  225. if (mqtt_connected) {
  226. int msg_id = esp_mqtt_client_subscribe(client, topic.c_str(), 0);
  227. ESP_LOGD(TAG, "topic %s subscribe successful, msg_id=%d", topic.c_str(), msg_id);
  228. }
  229. }
  230. void MQTTconnected(){
  231. if (mqtt_connected) {
  232. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected");
  233. MQTTPublish(lwt_topic, lwt_connected, true);
  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, "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. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "topic " + it->first + " subscribe successful, msg_id=" + std::to_string(msg_id));
  244. }
  245. }
  246. if (callbackOnConnected) {
  247. callbackOnConnected(maintopic, SetRetainFlag);
  248. }
  249. }
  250. }
  251. void MQTTdestroySubscribeFunction(){
  252. if (subscribeFunktionMap != NULL) {
  253. if (mqtt_connected) {
  254. for(std::map<std::string, std::function<bool(std::string, char*, int)>>::iterator it = subscribeFunktionMap->begin(); it != subscribeFunktionMap->end(); ++it) {
  255. int msg_id = esp_mqtt_client_unsubscribe(client, it->first.c_str());
  256. ESP_LOGI(TAG, "topic %s unsubscribe successful, msg_id=%d", it->first.c_str(), msg_id);
  257. }
  258. }
  259. subscribeFunktionMap->clear();
  260. delete subscribeFunktionMap;
  261. subscribeFunktionMap = NULL;
  262. }
  263. }