interface_mqtt.cpp 12 KB

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