Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

710 lines
20 KiB

8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. MQTT MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if MQTT_SUPPORT
  6. #include <ESP8266WiFi.h>
  7. #include <ESP8266mDNS.h>
  8. #include <ArduinoJson.h>
  9. #include <vector>
  10. #include <Ticker.h>
  11. #if MQTT_USE_ASYNC // Using AsyncMqttClient
  12. #include <AsyncMqttClient.h>
  13. AsyncMqttClient _mqtt;
  14. #else // Using PubSubClient
  15. #include <PubSubClient.h>
  16. PubSubClient _mqtt;
  17. bool _mqtt_connected = false;
  18. WiFiClient _mqtt_client;
  19. #if ASYNC_TCP_SSL_ENABLED
  20. WiFiClientSecure _mqtt_client_secure;
  21. #endif // ASYNC_TCP_SSL_ENABLED
  22. #endif // MQTT_USE_ASYNC
  23. bool _mqtt_enabled = MQTT_ENABLED;
  24. bool _mqtt_use_json = false;
  25. unsigned long _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  26. unsigned char _mqtt_qos = MQTT_QOS;
  27. bool _mqtt_retain = MQTT_RETAIN;
  28. unsigned char _mqtt_keepalive = MQTT_KEEPALIVE;
  29. String _mqtt_topic;
  30. String _mqtt_topic_json;
  31. String _mqtt_setter;
  32. String _mqtt_getter;
  33. bool _mqtt_forward;
  34. char *_mqtt_user = 0;
  35. char *_mqtt_pass = 0;
  36. char *_mqtt_will;
  37. char *_mqtt_clientid;
  38. #if MQTT_SKIP_RETAINED
  39. unsigned long _mqtt_connected_at = 0;
  40. #endif
  41. std::vector<mqtt_callback_f> _mqtt_callbacks;
  42. typedef struct {
  43. char * topic;
  44. char * message;
  45. } mqtt_message_t;
  46. std::vector<mqtt_message_t> _mqtt_queue;
  47. Ticker _mqtt_flush_ticker;
  48. // -----------------------------------------------------------------------------
  49. // Private
  50. // -----------------------------------------------------------------------------
  51. void _mqttConnect() {
  52. // Do not connect if disabled
  53. if (!_mqtt_enabled) return;
  54. // Do not connect if already connected
  55. if (_mqtt.connected()) return;
  56. // Check reconnect interval
  57. static unsigned long last = 0;
  58. if (millis() - last < _mqtt_reconnect_delay) return;
  59. last = millis();
  60. // Increase the reconnect delay
  61. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  62. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  63. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  64. }
  65. String h = getSetting("mqttServer", MQTT_SERVER);
  66. #if MDNS_CLIENT_SUPPORT
  67. h = mdnsResolve(h);
  68. #endif
  69. char * host = strdup(h.c_str());
  70. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  71. if (_mqtt_user) free(_mqtt_user);
  72. if (_mqtt_pass) free(_mqtt_pass);
  73. if (_mqtt_will) free(_mqtt_will);
  74. if (_mqtt_clientid) free(_mqtt_clientid);
  75. _mqtt_user = strdup(getSetting("mqttUser", MQTT_USER).c_str());
  76. _mqtt_pass = strdup(getSetting("mqttPassword", MQTT_PASS).c_str());
  77. _mqtt_will = strdup(mqttTopic(MQTT_TOPIC_STATUS, false).c_str());
  78. _mqtt_clientid = strdup(getSetting("mqttClientID", getIdentifier()).c_str());
  79. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d\n"), host, port);
  80. #if MQTT_USE_ASYNC
  81. _mqtt.setServer(host, port);
  82. _mqtt.setClientId(_mqtt_clientid);
  83. _mqtt.setKeepAlive(_mqtt_keepalive);
  84. _mqtt.setCleanSession(false);
  85. _mqtt.setWill(_mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  86. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  87. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  88. _mqtt.setCredentials(_mqtt_user, _mqtt_pass);
  89. }
  90. #if ASYNC_TCP_SSL_ENABLED
  91. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  92. _mqtt.setSecure(secure);
  93. if (secure) {
  94. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  95. unsigned char fp[20] = {0};
  96. if (sslFingerPrintArray(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  97. _mqtt.addServerFingerprint(fp);
  98. } else {
  99. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  100. }
  101. }
  102. #endif // ASYNC_TCP_SSL_ENABLED
  103. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid);
  104. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  105. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  106. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  107. _mqtt.connect();
  108. #else // not MQTT_USE_ASYNC
  109. bool response = true;
  110. #if ASYNC_TCP_SSL_ENABLED
  111. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  112. if (secure) {
  113. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  114. if (_mqtt_client_secure.connect(host, port)) {
  115. char fp[60] = {0};
  116. if (sslFingerPrintChar(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  117. if (_mqtt_client_secure.verify(fp, host)) {
  118. _mqtt.setClient(_mqtt_client_secure);
  119. } else {
  120. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  121. response = false;
  122. }
  123. _mqtt_client_secure.stop();
  124. yield();
  125. } else {
  126. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  127. response = false;
  128. }
  129. } else {
  130. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  131. response = false;
  132. }
  133. } else {
  134. _mqtt.setClient(_mqtt_client);
  135. }
  136. #else // not ASYNC_TCP_SSL_ENABLED
  137. _mqtt.setClient(_mqtt_client);
  138. #endif // ASYNC_TCP_SSL_ENABLED
  139. if (response) {
  140. _mqtt.setServer(host, port);
  141. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  142. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  143. response = _mqtt.connect(_mqtt_clientid, _mqtt_user, _mqtt_pass, _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  144. } else {
  145. response = _mqtt.connect(_mqtt_clientid, _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  146. }
  147. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid);
  148. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  149. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  150. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  151. }
  152. if (response) {
  153. _mqttOnConnect();
  154. } else {
  155. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  156. }
  157. #endif // MQTT_USE_ASYNC
  158. free(host);
  159. }
  160. void _mqttConfigure() {
  161. // Get base topic
  162. _mqtt_topic = getSetting("mqttTopic", MQTT_TOPIC);
  163. if (_mqtt_topic.indexOf("#") == -1) _mqtt_topic = _mqtt_topic + "/#";
  164. // Placeholders
  165. _mqtt_topic.replace("{identifier}", getSetting("hostname"));
  166. _mqtt_topic.replace("{hostname}", getSetting("hostname"));
  167. String mac = WiFi.macAddress();
  168. mac.replace(":", "");
  169. _mqtt_topic.replace("{mac}", mac);
  170. // Getters and setters
  171. _mqtt_setter = getSetting("mqttSetter", MQTT_SETTER);
  172. _mqtt_getter = getSetting("mqttGetter", MQTT_GETTER);
  173. _mqtt_forward = !_mqtt_getter.equals(_mqtt_setter);
  174. // MQTT options
  175. _mqtt_qos = getSetting("mqttQoS", MQTT_QOS).toInt();
  176. _mqtt_retain = getSetting("mqttRetain", MQTT_RETAIN).toInt() == 1;
  177. _mqtt_keepalive = getSetting("mqttKeep", MQTT_KEEPALIVE).toInt();
  178. if (getSetting("mqttClientID").length() == 0) delSetting("mqttClientID");
  179. // Enable
  180. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  181. mqttEnabled(false);
  182. } else {
  183. _mqtt_enabled = getSetting("mqttEnabled", MQTT_ENABLED).toInt() == 1;
  184. }
  185. _mqtt_use_json = (getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1);
  186. mqttQueueTopic(MQTT_TOPIC_JSON);
  187. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  188. }
  189. // -----------------------------------------------------------------------------
  190. // WEB
  191. // -----------------------------------------------------------------------------
  192. #if WEB_SUPPORT
  193. void _mqttWebSocketOnSend(JsonObject& root) {
  194. root["mqttVisible"] = 1;
  195. root["mqttStatus"] = mqttConnected();
  196. root["mqttEnabled"] = mqttEnabled();
  197. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  198. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  199. root["mqttUser"] = getSetting("mqttUser");
  200. root["mqttClientID"] = getSetting("mqttClientID");
  201. root["mqttPassword"] = getSetting("mqttPassword");
  202. root["mqttKeep"] = _mqtt_keepalive;
  203. root["mqttRetain"] = _mqtt_retain;
  204. root["mqttQoS"] = _mqtt_qos;
  205. #if ASYNC_TCP_SSL_ENABLED
  206. root["mqttsslVisible"] = 1;
  207. root["mqttUseSSL"] = getSetting("mqttUseSSL", 0).toInt() == 1;
  208. root["mqttFP"] = getSetting("mqttFP");
  209. #endif
  210. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  211. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  212. }
  213. #endif
  214. // -----------------------------------------------------------------------------
  215. // SETTINGS
  216. // -----------------------------------------------------------------------------
  217. #if TERMINAL_SUPPORT
  218. void _mqttInitCommands() {
  219. settingsRegisterCommand(F("MQTT.RESET"), [](Embedis* e) {
  220. _mqttConfigure();
  221. mqttDisconnect();
  222. DEBUG_MSG_P(PSTR("+OK\n"));
  223. });
  224. }
  225. #endif // TERMINAL_SUPPORT
  226. // -----------------------------------------------------------------------------
  227. // MQTT Callbacks
  228. // -----------------------------------------------------------------------------
  229. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  230. if (type == MQTT_CONNECT_EVENT) {
  231. // Subscribe to internal action topics
  232. mqttSubscribe(MQTT_TOPIC_ACTION);
  233. // Send heartbeat messages
  234. heartbeat();
  235. }
  236. if (type == MQTT_MESSAGE_EVENT) {
  237. // Match topic
  238. String t = mqttTopicKey((char *) topic);
  239. // Actions
  240. if (t.equals(MQTT_TOPIC_ACTION)) {
  241. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  242. deferredReset(100, CUSTOM_RESET_MQTT);
  243. }
  244. }
  245. }
  246. }
  247. void _mqttOnConnect() {
  248. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  249. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  250. #if MQTT_SKIP_RETAINED
  251. _mqtt_connected_at = millis();
  252. #endif
  253. // Clean subscriptions
  254. mqttUnsubscribeRaw("#");
  255. // Send connect event to subscribers
  256. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  257. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  258. }
  259. }
  260. void _mqttOnDisconnect() {
  261. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  262. // Send disconnect event to subscribers
  263. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  264. (_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  265. }
  266. }
  267. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  268. if (len == 0) return;
  269. char message[len + 1];
  270. strlcpy(message, (char *) payload, len + 1);
  271. #if MQTT_SKIP_RETAINED
  272. if (millis() - _mqtt_connected_at < MQTT_SKIP_TIME) {
  273. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  274. return;
  275. }
  276. #endif
  277. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  278. // Send message event to subscribers
  279. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  280. (_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  281. }
  282. }
  283. // -----------------------------------------------------------------------------
  284. // Public API
  285. // -----------------------------------------------------------------------------
  286. String mqttTopicKey(char * topic) {
  287. String pattern = _mqtt_topic + _mqtt_setter;
  288. int position = pattern.indexOf("#");
  289. if (position == -1) return String();
  290. String start = pattern.substring(0, position);
  291. String end = pattern.substring(position + 1);
  292. String response = String(topic);
  293. if (response.startsWith(start) && response.endsWith(end)) {
  294. response.replace(start, "");
  295. response.replace(end, "");
  296. } else {
  297. response = String();
  298. }
  299. return response;
  300. }
  301. String mqttTopic(const char * topic, bool is_set) {
  302. String output = _mqtt_topic;
  303. output.replace("#", topic);
  304. output += is_set ? _mqtt_setter : _mqtt_getter;
  305. return output;
  306. }
  307. String mqttTopic(const char * topic, unsigned int index, bool is_set) {
  308. char buffer[strlen(topic)+5];
  309. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  310. return mqttTopic(buffer, is_set);
  311. }
  312. // -----------------------------------------------------------------------------
  313. void mqttSendRaw(const char * topic, const char * message) {
  314. if (_mqtt.connected()) {
  315. #if MQTT_USE_ASYNC
  316. unsigned int packetId = _mqtt.publish(topic, _mqtt_qos, _mqtt_retain, message);
  317. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %d)\n"), topic, message, packetId);
  318. #else
  319. _mqtt.publish(topic, message, _mqtt_retain);
  320. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  321. #endif
  322. }
  323. }
  324. void mqttFlush() {
  325. if (_mqtt_queue.size() == 0) return;
  326. DynamicJsonBuffer jsonBuffer;
  327. JsonObject& root = jsonBuffer.createObject();
  328. // Add enqueued messages
  329. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  330. mqtt_message_t element = _mqtt_queue[i];
  331. root[element.topic] = element.message;
  332. }
  333. // Add extra propeties
  334. #if NTP_SUPPORT && MQTT_ENQUEUE_DATETIME
  335. if (ntpConnected()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  336. #endif
  337. #if MQTT_ENQUEUE_MAC
  338. root[MQTT_TOPIC_MAC] = WiFi.macAddress();
  339. #endif
  340. #if MQTT_ENQUEUE_HOSTNAME
  341. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  342. #endif
  343. #if MQTT_ENQUEUE_IP
  344. root[MQTT_TOPIC_IP] = getIP();
  345. #endif
  346. // Send
  347. String output;
  348. root.printTo(output);
  349. mqttSendRaw(_mqtt_topic_json.c_str(), output.c_str());
  350. // Clear queue
  351. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  352. mqtt_message_t element = _mqtt_queue[i];
  353. free(element.topic);
  354. free(element.message);
  355. }
  356. _mqtt_queue.clear();
  357. }
  358. void mqttQueueTopic(const char * topic) {
  359. String t = mqttTopic(topic, false);
  360. if (!t.equals(_mqtt_topic_json)) {
  361. mqttFlush();
  362. _mqtt_topic_json = t;
  363. }
  364. }
  365. void mqttEnqueue(const char * topic, const char * message) {
  366. // Force flusing the queue if the MQTT_QUEUE_MAX_SIZE has been reached
  367. if (_mqtt_queue.size() >= MQTT_QUEUE_MAX_SIZE) mqttFlush();
  368. // Enqueue new message
  369. mqtt_message_t element;
  370. element.topic = strdup(topic);
  371. element.message = strdup(message);
  372. _mqtt_queue.push_back(element);
  373. }
  374. void mqttSend(const char * topic, const char * message, bool force) {
  375. bool useJson = force ? false : _mqtt_use_json;
  376. // Equeue message
  377. if (useJson) {
  378. // Set default queue topic
  379. mqttQueueTopic(MQTT_TOPIC_JSON);
  380. // Enqueue new message
  381. mqttEnqueue(topic, message);
  382. // Reset flush timer
  383. _mqtt_flush_ticker.once_ms(MQTT_USE_JSON_DELAY, mqttFlush);
  384. // Send it right away
  385. } else {
  386. mqttSendRaw(mqttTopic(topic, false).c_str(), message);
  387. }
  388. }
  389. void mqttSend(const char * topic, const char * message) {
  390. mqttSend(topic, message, false);
  391. }
  392. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  393. char buffer[strlen(topic)+5];
  394. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  395. mqttSend(buffer, message, force);
  396. }
  397. void mqttSend(const char * topic, unsigned int index, const char * message) {
  398. mqttSend(topic, index, message, false);
  399. }
  400. // -----------------------------------------------------------------------------
  401. void mqttSubscribeRaw(const char * topic) {
  402. if (_mqtt.connected() && (strlen(topic) > 0)) {
  403. #if MQTT_USE_ASYNC
  404. unsigned int packetId = _mqtt.subscribe(topic, _mqtt_qos);
  405. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  406. #else
  407. _mqtt.subscribe(topic, _mqtt_qos);
  408. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  409. #endif
  410. }
  411. }
  412. void mqttSubscribe(const char * topic) {
  413. mqttSubscribeRaw(mqttTopic(topic, true).c_str());
  414. }
  415. void mqttUnsubscribeRaw(const char * topic) {
  416. if (_mqtt.connected() && (strlen(topic) > 0)) {
  417. #if MQTT_USE_ASYNC
  418. unsigned int packetId = _mqtt.unsubscribe(topic);
  419. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  420. #else
  421. _mqtt.unsubscribe(topic);
  422. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  423. #endif
  424. }
  425. }
  426. void mqttUnsubscribe(const char * topic) {
  427. mqttUnsubscribeRaw(mqttTopic(topic, true).c_str());
  428. }
  429. // -----------------------------------------------------------------------------
  430. void mqttEnabled(bool status) {
  431. _mqtt_enabled = status;
  432. setSetting("mqttEnabled", status ? 1 : 0);
  433. }
  434. bool mqttEnabled() {
  435. return _mqtt_enabled;
  436. }
  437. bool mqttConnected() {
  438. return _mqtt.connected();
  439. }
  440. void mqttDisconnect() {
  441. if (_mqtt.connected()) {
  442. DEBUG_MSG_P(PSTR("[MQTT] Disconnecting\n"));
  443. _mqtt.disconnect();
  444. }
  445. }
  446. bool mqttForward() {
  447. return _mqtt_forward;
  448. }
  449. void mqttRegister(mqtt_callback_f callback) {
  450. _mqtt_callbacks.push_back(callback);
  451. }
  452. void mqttSetBroker(IPAddress ip, unsigned int port) {
  453. setSetting("mqttServer", ip.toString());
  454. setSetting("mqttPort", port);
  455. mqttEnabled(MQTT_AUTOCONNECT);
  456. }
  457. void mqttSetBrokerIfNone(IPAddress ip, unsigned int port) {
  458. if (!hasSetting("mqttServer")) mqttSetBroker(ip, port);
  459. }
  460. void mqttReset() {
  461. _mqttConfigure();
  462. mqttDisconnect();
  463. }
  464. // -----------------------------------------------------------------------------
  465. // Initialization
  466. // -----------------------------------------------------------------------------
  467. void mqttSetup() {
  468. DEBUG_MSG_P(PSTR("[MQTT] Async %s, SSL %s, Autoconnect %s\n"),
  469. MQTT_USE_ASYNC ? "ENABLED" : "DISABLED",
  470. ASYNC_TCP_SSL_ENABLED ? "ENABLED" : "DISABLED",
  471. MQTT_AUTOCONNECT ? "ENABLED" : "DISABLED"
  472. );
  473. #if MQTT_USE_ASYNC
  474. _mqtt.onConnect([](bool sessionPresent) {
  475. _mqttOnConnect();
  476. });
  477. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  478. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  479. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  480. }
  481. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  482. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  483. }
  484. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  485. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  486. }
  487. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  488. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  489. }
  490. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  491. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  492. }
  493. #if ASYNC_TCP_SSL_ENABLED
  494. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  495. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  496. }
  497. #endif
  498. _mqttOnDisconnect();
  499. });
  500. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  501. _mqttOnMessage(topic, payload, len);
  502. });
  503. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  504. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  505. });
  506. _mqtt.onPublish([](uint16_t packetId) {
  507. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  508. });
  509. #else // not MQTT_USE_ASYNC
  510. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  511. _mqttOnMessage(topic, (char *) payload, length);
  512. });
  513. #endif // MQTT_USE_ASYNC
  514. _mqttConfigure();
  515. mqttRegister(_mqttCallback);
  516. #if WEB_SUPPORT
  517. wsOnSendRegister(_mqttWebSocketOnSend);
  518. wsOnAfterParseRegister(_mqttConfigure);
  519. #endif
  520. #if TERMINAL_SUPPORT
  521. _mqttInitCommands();
  522. #endif
  523. }
  524. void mqttLoop() {
  525. if (WiFi.status() != WL_CONNECTED) return;
  526. #if MQTT_USE_ASYNC
  527. _mqttConnect();
  528. #else // not MQTT_USE_ASYNC
  529. if (_mqtt.connected()) {
  530. _mqtt.loop();
  531. } else {
  532. if (_mqtt_connected) {
  533. _mqttOnDisconnect();
  534. _mqtt_connected = false;
  535. }
  536. _mqttConnect();
  537. }
  538. #endif
  539. }
  540. #endif // MQTT_SUPPORT