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.

625 lines
18 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-2017 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_setter;
  31. String _mqtt_getter;
  32. bool _mqtt_forward;
  33. char *_mqtt_user = 0;
  34. char *_mqtt_pass = 0;
  35. char *_mqtt_will;
  36. #if MQTT_SKIP_RETAINED
  37. unsigned long _mqtt_connected_at = 0;
  38. #endif
  39. std::vector<mqtt_callback_f> _mqtt_callbacks;
  40. typedef struct {
  41. char * topic;
  42. char * message;
  43. } mqtt_message_t;
  44. std::vector<mqtt_message_t> _mqtt_queue;
  45. Ticker _mqtt_flush_ticker;
  46. // -----------------------------------------------------------------------------
  47. // Public API
  48. // -----------------------------------------------------------------------------
  49. bool mqttConnected() {
  50. return _mqtt.connected();
  51. }
  52. void mqttDisconnect() {
  53. if (_mqtt.connected()) {
  54. DEBUG_MSG_P(PSTR("[MQTT] Disconnecting\n"));
  55. _mqtt.disconnect();
  56. }
  57. }
  58. bool mqttForward() {
  59. return _mqtt_forward;
  60. }
  61. String mqttSubtopic(char * topic) {
  62. String response;
  63. String t = String(topic);
  64. if (t.startsWith(_mqtt_topic) && t.endsWith(_mqtt_setter)) {
  65. response = t.substring(_mqtt_topic.length(), t.length() - _mqtt_setter.length());
  66. }
  67. return response;
  68. }
  69. void mqttSendRaw(const char * topic, const char * message) {
  70. if (_mqtt.connected()) {
  71. #if MQTT_USE_ASYNC
  72. unsigned int packetId = _mqtt.publish(topic, _mqtt_qos, _mqtt_retain, message);
  73. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %d)\n"), topic, message, packetId);
  74. #else
  75. _mqtt.publish(topic, message, _mqtt_retain);
  76. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  77. #endif
  78. }
  79. }
  80. String getTopic(const char * topic, bool set) {
  81. String output = _mqtt_topic + String(topic);
  82. if (set) output += _mqtt_setter;
  83. return output;
  84. }
  85. String getTopic(const char * topic, unsigned int index, bool set) {
  86. char buffer[strlen(topic)+5];
  87. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  88. return getTopic(buffer, set);
  89. }
  90. void _mqttFlush() {
  91. if (_mqtt_queue.size() == 0) return;
  92. DynamicJsonBuffer jsonBuffer;
  93. JsonObject& root = jsonBuffer.createObject();
  94. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  95. mqtt_message_t element = _mqtt_queue[i];
  96. root[element.topic] = element.message;
  97. }
  98. #if NTP_SUPPORT
  99. if (ntpConnected()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  100. #endif
  101. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  102. root[MQTT_TOPIC_IP] = getIP();
  103. String output;
  104. root.printTo(output);
  105. String path = _mqtt_topic + String(MQTT_TOPIC_JSON);
  106. mqttSendRaw(path.c_str(), output.c_str());
  107. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  108. mqtt_message_t element = _mqtt_queue[i];
  109. free(element.topic);
  110. free(element.message);
  111. }
  112. _mqtt_queue.clear();
  113. }
  114. void mqttSend(const char * topic, const char * message, bool force) {
  115. bool useJson = force ? false : _mqtt_use_json;
  116. if (useJson) {
  117. if (_mqtt_queue.size() >= MQTT_QUEUE_MAX_SIZE) _mqttFlush();
  118. mqtt_message_t element;
  119. element.topic = strdup(topic);
  120. element.message = strdup(message);
  121. _mqtt_queue.push_back(element);
  122. _mqtt_flush_ticker.once_ms(MQTT_USE_JSON_DELAY, _mqttFlush);
  123. } else {
  124. String path = _mqtt_topic + String(topic) + _mqtt_getter;
  125. mqttSendRaw(path.c_str(), message);
  126. }
  127. }
  128. void mqttSend(const char * topic, const char * message) {
  129. mqttSend(topic, message, false);
  130. }
  131. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  132. char buffer[strlen(topic)+5];
  133. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  134. mqttSend(buffer, message, force);
  135. }
  136. void mqttSend(const char * topic, unsigned int index, const char * message) {
  137. mqttSend(topic, index, message, false);
  138. }
  139. void mqttSubscribeRaw(const char * topic) {
  140. if (_mqtt.connected() && (strlen(topic) > 0)) {
  141. #if MQTT_USE_ASYNC
  142. unsigned int packetId = _mqtt.subscribe(topic, _mqtt_qos);
  143. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  144. #else
  145. _mqtt.subscribe(topic, _mqtt_qos);
  146. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  147. #endif
  148. }
  149. }
  150. void mqttSubscribe(const char * topic) {
  151. String path = _mqtt_topic + String(topic) + _mqtt_setter;
  152. mqttSubscribeRaw(path.c_str());
  153. }
  154. void mqttUnsubscribeRaw(const char * topic) {
  155. if (_mqtt.connected() && (strlen(topic) > 0)) {
  156. #if MQTT_USE_ASYNC
  157. unsigned int packetId = _mqtt.unsubscribe(topic);
  158. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  159. #else
  160. _mqtt.unsubscribe(topic);
  161. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  162. #endif
  163. }
  164. }
  165. void mqttRegister(mqtt_callback_f callback) {
  166. _mqtt_callbacks.push_back(callback);
  167. }
  168. // -----------------------------------------------------------------------------
  169. // Callbacks
  170. // -----------------------------------------------------------------------------
  171. void _mqttWebSocketOnSend(JsonObject& root) {
  172. root["mqttVisible"] = 1;
  173. root["mqttStatus"] = mqttConnected();
  174. root["mqttEnabled"] = mqttEnabled();
  175. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  176. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  177. root["mqttUser"] = getSetting("mqttUser");
  178. root["mqttPassword"] = getSetting("mqttPassword");
  179. root["mqttKeep"] = _mqtt_keepalive;
  180. root["mqttRetain"] = _mqtt_retain;
  181. root["mqttQoS"] = _mqtt_qos;
  182. #if ASYNC_TCP_SSL_ENABLED
  183. root["mqttsslVisible"] = 1;
  184. root["mqttUseSSL"] = getSetting("mqttUseSSL", 0).toInt() == 1;
  185. root["mqttFP"] = getSetting("mqttFP");
  186. #endif
  187. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  188. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  189. }
  190. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  191. if (type == MQTT_CONNECT_EVENT) {
  192. // Subscribe to internal action topics
  193. mqttSubscribe(MQTT_TOPIC_ACTION);
  194. // Send heartbeat messages
  195. heartbeat();
  196. }
  197. if (type == MQTT_MESSAGE_EVENT) {
  198. // Match topic
  199. String t = mqttSubtopic((char *) topic);
  200. // Actions
  201. if (t.equals(MQTT_TOPIC_ACTION)) {
  202. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  203. deferredReset(100, CUSTOM_RESET_MQTT);
  204. }
  205. }
  206. }
  207. }
  208. void _mqttOnConnect() {
  209. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  210. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  211. #if MQTT_SKIP_RETAINED
  212. _mqtt_connected_at = millis();
  213. #endif
  214. // Clean subscriptions
  215. mqttUnsubscribeRaw("#");
  216. // Send connect event to subscribers
  217. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  218. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  219. }
  220. }
  221. void _mqttOnDisconnect() {
  222. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  223. // Send disconnect event to subscribers
  224. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  225. (_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  226. }
  227. }
  228. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  229. if (len == 0) return;
  230. char message[len + 1];
  231. strlcpy(message, (char *) payload, len + 1);
  232. #if MQTT_SKIP_RETAINED
  233. if (millis() - _mqtt_connected_at < MQTT_SKIP_TIME) {
  234. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  235. return;
  236. }
  237. #endif
  238. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  239. // Send message event to subscribers
  240. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  241. (_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  242. }
  243. }
  244. #if MQTT_USE_ASYNC
  245. bool mqttFormatFP(const char * fingerprint, unsigned char * bytearray) {
  246. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  247. if (strlen(fingerprint) != 59) return false;
  248. DEBUG_MSG_P(PSTR("[MQTT] Fingerprint %s\n"), fingerprint);
  249. // walk the fingerprint
  250. for (unsigned int i=0; i<20; i++) {
  251. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  252. }
  253. return true;
  254. }
  255. #else
  256. bool mqttFormatFP(const char * fingerprint, char * destination) {
  257. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  258. if (strlen(fingerprint) != 59) return false;
  259. DEBUG_MSG_P(PSTR("[MQTT] Fingerprint %s\n"), fingerprint);
  260. // copy it
  261. strncpy(destination, fingerprint, 59);
  262. // walk the fingerprint replacing ':' for ' '
  263. for (unsigned char i = 0; i<59; i++) {
  264. if (destination[i] == ':') destination[i] = ' ';
  265. }
  266. return true;
  267. }
  268. #endif
  269. void mqttEnabled(bool status) {
  270. _mqtt_enabled = status;
  271. setSetting("mqttEnabled", status ? 1 : 0);
  272. }
  273. bool mqttEnabled() {
  274. return _mqtt_enabled;
  275. }
  276. void mqttConnect() {
  277. // Do not connect if disabled
  278. if (!_mqtt_enabled) return;
  279. // Do not connect if already connected
  280. if (_mqtt.connected()) return;
  281. // Check reconnect interval
  282. static unsigned long last = 0;
  283. if (millis() - last < _mqtt_reconnect_delay) return;
  284. last = millis();
  285. // Increase the reconnect delay
  286. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  287. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  288. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  289. }
  290. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  291. if (strlen(host) == 0) return;
  292. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  293. if (_mqtt_user) free(_mqtt_user);
  294. if (_mqtt_pass) free(_mqtt_pass);
  295. if (_mqtt_will) free(_mqtt_will);
  296. _mqtt_user = strdup(getSetting("mqttUser", MQTT_USER).c_str());
  297. _mqtt_pass = strdup(getSetting("mqttPassword", MQTT_PASS).c_str());
  298. _mqtt_will = strdup((_mqtt_topic + MQTT_TOPIC_STATUS).c_str());
  299. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d\n"), host, port);
  300. #if MQTT_USE_ASYNC
  301. _mqtt.setServer(host, port);
  302. _mqtt.setKeepAlive(_mqtt_keepalive).setCleanSession(false);
  303. _mqtt.setWill(_mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  304. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  305. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  306. _mqtt.setCredentials(_mqtt_user, _mqtt_pass);
  307. }
  308. #if ASYNC_TCP_SSL_ENABLED
  309. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  310. _mqtt.setSecure(secure);
  311. if (secure) {
  312. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  313. unsigned char fp[20] = {0};
  314. if (mqttFormatFP(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  315. _mqtt.addServerFingerprint(fp);
  316. } else {
  317. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  318. }
  319. }
  320. #endif // ASYNC_TCP_SSL_ENABLED
  321. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  322. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  323. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  324. _mqtt.connect();
  325. #else // not MQTT_USE_ASYNC
  326. bool response = true;
  327. #if ASYNC_TCP_SSL_ENABLED
  328. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  329. if (secure) {
  330. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  331. if (_mqtt_client_secure.connect(host, port)) {
  332. char fp[60] = {0};
  333. if (mqttFormatFP(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  334. if (_mqtt_client_secure.verify(fp, host)) {
  335. _mqtt.setClient(_mqtt_client_secure);
  336. } else {
  337. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  338. response = false;
  339. }
  340. _mqtt_client_secure.stop();
  341. yield();
  342. } else {
  343. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  344. response = false;
  345. }
  346. } else {
  347. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  348. response = false;
  349. }
  350. } else {
  351. _mqtt.setClient(_mqtt_client);
  352. }
  353. #else // not ASYNC_TCP_SSL_ENABLED
  354. _mqtt.setClient(_mqtt_client);
  355. #endif // ASYNC_TCP_SSL_ENABLED
  356. if (response) {
  357. _mqtt.setServer(host, port);
  358. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  359. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  360. response = _mqtt.connect(getIdentifier().c_str(), _mqtt_user, _mqtt_pass, _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  361. } else {
  362. response = _mqtt.connect(getIdentifier().c_str(), _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  363. }
  364. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  365. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  366. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  367. }
  368. if (response) {
  369. _mqttOnConnect();
  370. } else {
  371. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  372. }
  373. #endif // MQTT_USE_ASYNC
  374. free(host);
  375. }
  376. void mqttConfigure() {
  377. // Replace identifier
  378. _mqtt_topic = getSetting("mqttTopic", MQTT_TOPIC);
  379. _mqtt_topic.replace("{identifier}", getSetting("hostname"));
  380. if (!_mqtt_topic.endsWith("/")) _mqtt_topic = _mqtt_topic + "/";
  381. // Getters and setters
  382. _mqtt_setter = getSetting("mqttSetter", MQTT_USE_SETTER);
  383. _mqtt_getter = getSetting("mqttGetter", MQTT_USE_GETTER);
  384. _mqtt_forward = !_mqtt_getter.equals(_mqtt_setter);
  385. // MQTT options
  386. _mqtt_qos = getSetting("mqttQoS", MQTT_QOS).toInt();
  387. _mqtt_retain = getSetting("mqttRetain", MQTT_RETAIN).toInt() == 1;
  388. _mqtt_keepalive = getSetting("mqttKeep", MQTT_KEEPALIVE).toInt();
  389. // Enable
  390. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  391. mqttEnabled(false);
  392. } else {
  393. _mqtt_enabled = getSetting("mqttEnabled", MQTT_ENABLED).toInt() == 1;
  394. }
  395. _mqtt_use_json = (getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1);
  396. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  397. }
  398. void mqttSetBroker(IPAddress ip, unsigned int port) {
  399. setSetting("mqttServer", ip.toString());
  400. setSetting("mqttPort", port);
  401. mqttEnabled(MQTT_AUTOCONNECT);
  402. }
  403. void mqttSetBrokerIfNone(IPAddress ip, unsigned int port) {
  404. if (!hasSetting("mqttServer")) mqttSetBroker(ip, port);
  405. }
  406. void mqttSetup() {
  407. DEBUG_MSG_P(PSTR("[MQTT] MQTT_USE_ASYNC = %d\n"), MQTT_USE_ASYNC);
  408. DEBUG_MSG_P(PSTR("[MQTT] MQTT_AUTOCONNECT = %d\n"), MQTT_AUTOCONNECT);
  409. #if MQTT_USE_ASYNC
  410. _mqtt.onConnect([](bool sessionPresent) {
  411. _mqttOnConnect();
  412. });
  413. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  414. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  415. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  416. }
  417. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  418. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  419. }
  420. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  421. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  422. }
  423. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  424. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  425. }
  426. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  427. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  428. }
  429. #if ASYNC_TCP_SSL_ENABLED
  430. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  431. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  432. }
  433. #endif
  434. _mqttOnDisconnect();
  435. });
  436. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  437. _mqttOnMessage(topic, payload, len);
  438. });
  439. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  440. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  441. });
  442. _mqtt.onPublish([](uint16_t packetId) {
  443. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  444. });
  445. #else // not MQTT_USE_ASYNC
  446. DEBUG_MSG_P(PSTR("[MQTT] Using SYNC MQTT library\n"));
  447. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  448. _mqttOnMessage(topic, (char *) payload, length);
  449. });
  450. #endif // MQTT_USE_ASYNC
  451. mqttConfigure();
  452. mqttRegister(_mqttCallback);
  453. #if WEB_SUPPORT
  454. wsOnSendRegister(_mqttWebSocketOnSend);
  455. #endif
  456. }
  457. void mqttLoop() {
  458. if (WiFi.status() != WL_CONNECTED) return;
  459. #if MQTT_USE_ASYNC
  460. mqttConnect();
  461. #else // not MQTT_USE_ASYNC
  462. if (_mqtt.connected()) {
  463. _mqtt.loop();
  464. } else {
  465. if (_mqtt_connected) {
  466. _mqttOnDisconnect();
  467. _mqtt_connected = false;
  468. }
  469. mqttConnect();
  470. }
  471. #endif
  472. }
  473. #endif // MQTT_SUPPORT