interface_mqtt.cpp 12 KB

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