interface_mqtt.cpp 11 KB

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