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.

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