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.

767 lines
22 KiB

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