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.

895 lines
26 KiB

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