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.

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