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.

843 lines
24 KiB

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