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