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.

642 lines
19 KiB

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