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.

1060 lines
30 KiB

8 years ago
8 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. MQTT MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. Updated secure client support by Niek van der Maas < mail at niekvandermaas dot nl>
  5. */
  6. #if MQTT_SUPPORT
  7. #include <EEPROM_Rotate.h>
  8. #include <ESP8266WiFi.h>
  9. #include <ESP8266mDNS.h>
  10. #include <ArduinoJson.h>
  11. #include <vector>
  12. #include <utility>
  13. #include <Ticker.h>
  14. #include <TimeLib.h>
  15. #include "system.h"
  16. #include "libs/SecureClientHelpers.h"
  17. #include "ws.h"
  18. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  19. AsyncMqttClient _mqtt;
  20. #else // MQTT_LIBRARY_ARDUINOMQTT / MQTT_LIBRARY_PUBSUBCLIENT
  21. WiFiClient _mqtt_client;
  22. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  23. std::unique_ptr<SecureClient> _mqtt_client_secure = nullptr;
  24. #if MQTT_SECURE_CLIENT_INCLUDE_CA
  25. #include "static/mqtt_client_trusted_root_ca.h" // Assumes this header file defines a _mqtt_client_trusted_root_ca[] PROGMEM = "...PEM data..."
  26. #else
  27. #include "static/letsencrypt_isrgroot_pem.h" // Default to LetsEncrypt X3 certificate
  28. #define _mqtt_client_trusted_root_ca _ssl_letsencrypt_isrg_x3_ca
  29. #endif // MQTT_SECURE_CLIENT_INCLUDE_CA
  30. #endif // SECURE_CLIENT != SECURE_CLIENT_NONE
  31. #if MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  32. #ifdef MQTT_MAX_PACKET_SIZE
  33. MQTTClient _mqtt(MQTT_MAX_PACKET_SIZE);
  34. #else
  35. MQTTClient _mqtt;
  36. #endif
  37. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  38. PubSubClient _mqtt;
  39. #endif
  40. #endif // MQTT_LIBRARY == MQTT_ASYNCMQTTCLIENT
  41. bool _mqtt_enabled = MQTT_ENABLED;
  42. bool _mqtt_use_json = false;
  43. unsigned long _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  44. unsigned long _mqtt_last_connection = 0;
  45. bool _mqtt_connected = false;
  46. bool _mqtt_connecting = false;
  47. bool _mqtt_retain = MQTT_RETAIN;
  48. int _mqtt_qos = MQTT_QOS;
  49. int _mqtt_keepalive = MQTT_KEEPALIVE;
  50. String _mqtt_topic;
  51. String _mqtt_topic_json;
  52. String _mqtt_setter;
  53. String _mqtt_getter;
  54. bool _mqtt_forward;
  55. String _mqtt_user;
  56. String _mqtt_pass;
  57. String _mqtt_will;
  58. String _mqtt_server;
  59. uint16_t _mqtt_port;
  60. String _mqtt_clientid;
  61. String _mqtt_payload_online;
  62. String _mqtt_payload_offline;
  63. std::vector<mqtt_callback_f> _mqtt_callbacks;
  64. struct mqtt_message_t {
  65. static const unsigned char END = 255;
  66. unsigned char parent = END;
  67. char * topic;
  68. char * message = NULL;
  69. };
  70. std::vector<mqtt_message_t> _mqtt_queue;
  71. Ticker _mqtt_flush_ticker;
  72. // -----------------------------------------------------------------------------
  73. // Private
  74. // -----------------------------------------------------------------------------
  75. #if SECURE_CLIENT == SECURE_CLIENT_AXTLS
  76. SecureClientConfig _mqtt_sc_config {
  77. "MQTT",
  78. []() -> String {
  79. return _mqtt_server;
  80. },
  81. []() -> int {
  82. return getSetting("mqttScCheck", MQTT_SECURE_CLIENT_CHECK);
  83. },
  84. []() -> String {
  85. return getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  86. },
  87. true
  88. };
  89. #endif
  90. #if SECURE_CLIENT == SECURE_CLIENT_BEARSSL
  91. SecureClientConfig _mqtt_sc_config {
  92. "MQTT",
  93. []() -> int {
  94. return getSetting("mqttScCheck", MQTT_SECURE_CLIENT_CHECK);
  95. },
  96. []() -> PGM_P {
  97. return _mqtt_client_trusted_root_ca;
  98. },
  99. []() -> String {
  100. return getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  101. },
  102. []() -> uint16_t {
  103. return getSetting<uint16_t>("mqttScMFLN", MQTT_SECURE_CLIENT_MFLN);
  104. },
  105. true
  106. };
  107. #endif
  108. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  109. void _mqttSetupAsyncClient(bool secure = false) {
  110. _mqtt.setServer(_mqtt_server.c_str(), _mqtt_port);
  111. _mqtt.setClientId(_mqtt_clientid.c_str());
  112. _mqtt.setKeepAlive(_mqtt_keepalive);
  113. _mqtt.setCleanSession(false);
  114. _mqtt.setWill(_mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, _mqtt_payload_offline.c_str());
  115. if (_mqtt_user.length() && _mqtt_pass.length()) {
  116. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user.c_str());
  117. _mqtt.setCredentials(_mqtt_user.c_str(), _mqtt_pass.c_str());
  118. }
  119. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  120. if (secure) {
  121. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  122. _mqtt.setSecure(secure);
  123. }
  124. #endif // SECURE_CLIENT != SECURE_CLIENT_NONE
  125. _mqtt.connect();
  126. }
  127. #endif // MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  128. #if (MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT) || (MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT)
  129. WiFiClient& _mqttGetClient(bool secure) {
  130. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  131. return (secure ? _mqtt_client_secure->get() : _mqtt_client);
  132. #else
  133. return _mqtt_client;
  134. #endif
  135. }
  136. bool _mqttSetupSyncClient(bool secure = false) {
  137. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  138. if (secure) {
  139. if (!_mqtt_client_secure) _mqtt_client_secure = std::make_unique<SecureClient>(_mqtt_sc_config);
  140. return _mqtt_client_secure->beforeConnected();
  141. }
  142. #endif
  143. return true;
  144. }
  145. bool _mqttConnectSyncClient(bool secure = false) {
  146. bool result = false;
  147. #if MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  148. _mqtt.begin(_mqtt_server.c_str(), _mqtt_port, _mqttGetClient(secure));
  149. _mqtt.setWill(_mqtt_will.c_str(), _mqtt_payload_offline.c_str(), _mqtt_retain, _mqtt_qos);
  150. result = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_user.c_str(), _mqtt_pass.c_str());
  151. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  152. _mqtt.setClient(_mqttGetClient(secure));
  153. _mqtt.setServer(_mqtt_server.c_str(), _mqtt_port);
  154. if (_mqtt_user.length() && _mqtt_pass.length()) {
  155. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user.c_str());
  156. result = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_user.c_str(), _mqtt_pass.c_str(), _mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, _mqtt_payload_offline.c_str());
  157. } else {
  158. result = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, _mqtt_payload_offline.c_str());
  159. }
  160. #endif
  161. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  162. if (result && secure) {
  163. result = _mqtt_client_secure->afterConnected();
  164. }
  165. #endif
  166. return result;
  167. }
  168. #endif // (MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT) || (MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT)
  169. void _mqttConnect() {
  170. // Do not connect if disabled
  171. if (!_mqtt_enabled) return;
  172. // Do not connect if already connected or still trying to connect
  173. if (_mqtt.connected() || _mqtt_connecting) return;
  174. // Check reconnect interval
  175. if (millis() - _mqtt_last_connection < _mqtt_reconnect_delay) return;
  176. // Increase the reconnect delay
  177. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  178. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  179. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  180. }
  181. #if MDNS_CLIENT_SUPPORT
  182. _mqtt_server = mdnsResolve(_mqtt_server);
  183. #endif
  184. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%u\n"), _mqtt_server.c_str(), _mqtt_port);
  185. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid.c_str());
  186. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  187. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  188. DEBUG_MSG_P(PSTR("[MQTT] Keepalive time: %ds\n"), _mqtt_keepalive);
  189. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will.c_str());
  190. _mqtt_connecting = true;
  191. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  192. const bool secure = getSetting("mqttUseSSL", 1 == MQTT_SSL_ENABLED);
  193. #else
  194. const bool secure = false;
  195. #endif
  196. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  197. _mqttSetupAsyncClient(secure);
  198. #elif (MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT) || (MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT)
  199. if (_mqttSetupSyncClient(secure) && _mqttConnectSyncClient(secure)) {
  200. _mqttOnConnect();
  201. } else {
  202. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  203. _mqttOnDisconnect();
  204. }
  205. #else
  206. #error "please check that MQTT_LIBRARY is valid"
  207. #endif
  208. }
  209. void _mqttPlaceholders(String& text) {
  210. text.replace("{hostname}", getSetting("hostname"));
  211. text.replace("{magnitude}", "#");
  212. String mac = WiFi.macAddress();
  213. mac.replace(":", "");
  214. text.replace("{mac}", mac);
  215. }
  216. template<typename T>
  217. void _mqttApplySetting(T& current, T& updated) {
  218. if (current != updated) {
  219. current = std::move(updated);
  220. mqttDisconnect();
  221. }
  222. }
  223. template<typename T>
  224. void _mqttApplySetting(T& current, const T& updated) {
  225. if (current != updated) {
  226. current = updated;
  227. mqttDisconnect();
  228. }
  229. }
  230. template<typename T>
  231. void _mqttApplyTopic(T& current, const char* magnitude) {
  232. String updated = mqttTopic(magnitude, false);
  233. if (current != updated) {
  234. mqttFlush();
  235. current = std::move(updated);
  236. }
  237. }
  238. void _mqttConfigure() {
  239. // Enable only when server is set
  240. {
  241. const String server = getSetting("mqttServer", MQTT_SERVER);
  242. const auto port = getSetting<uint16_t>("mqttPort", MQTT_PORT);
  243. bool enabled = false;
  244. if (server.length()) {
  245. enabled = getSetting("mqttEnabled", 1 == MQTT_ENABLED);
  246. }
  247. _mqttApplySetting(_mqtt_server, server);
  248. _mqttApplySetting(_mqtt_enabled, enabled);
  249. _mqttApplySetting(_mqtt_port, port);
  250. if (!enabled) return;
  251. }
  252. // Get base topic and apply placeholders
  253. {
  254. String topic = getSetting("mqttTopic", MQTT_TOPIC);
  255. if (topic.endsWith("/")) topic.remove(topic.length()-1);
  256. // Replace things inside curly braces (like {hostname}, {mac} etc.)
  257. _mqttPlaceholders(topic);
  258. if (topic.indexOf("#") == -1) topic.concat("/#");
  259. _mqttApplySetting(_mqtt_topic, topic);
  260. }
  261. // Getter and setter
  262. {
  263. String setter = getSetting("mqttSetter", MQTT_SETTER);
  264. String getter = getSetting("mqttGetter", MQTT_GETTER);
  265. bool forward = !setter.equals(getter) && RELAY_REPORT_STATUS;
  266. _mqttApplySetting(_mqtt_setter, setter);
  267. _mqttApplySetting(_mqtt_getter, getter);
  268. _mqttApplySetting(_mqtt_forward, forward);
  269. }
  270. // MQTT options
  271. {
  272. String user = getSetting("mqttUser", MQTT_USER);
  273. _mqttPlaceholders(user);
  274. String pass = getSetting("mqttPassword", MQTT_PASS);
  275. const auto qos = getSetting("mqttQoS", MQTT_QOS);
  276. const bool retain = getSetting("mqttRetain", 1 == MQTT_RETAIN);
  277. // Note: MQTT spec defines this as 2 bytes
  278. const auto keepalive = constrain(
  279. getSetting("mqttKeep", MQTT_KEEPALIVE),
  280. 0, std::numeric_limits<uint16_t>::max()
  281. );
  282. String id = getSetting("mqttClientID", getIdentifier());
  283. _mqttPlaceholders(id);
  284. _mqttApplySetting(_mqtt_user, user);
  285. _mqttApplySetting(_mqtt_pass, pass);
  286. _mqttApplySetting(_mqtt_qos, qos);
  287. _mqttApplySetting(_mqtt_retain, retain);
  288. _mqttApplySetting(_mqtt_keepalive, keepalive);
  289. _mqttApplySetting(_mqtt_clientid, id);
  290. }
  291. // MQTT WILL
  292. {
  293. _mqttApplyTopic(_mqtt_will, MQTT_TOPIC_STATUS);
  294. }
  295. // MQTT JSON
  296. {
  297. _mqttApplySetting(_mqtt_use_json, getSetting("mqttUseJson", 1 == MQTT_USE_JSON));
  298. _mqttApplyTopic(_mqtt_topic_json, MQTT_TOPIC_JSON);
  299. }
  300. // Custom payload strings
  301. settingsProcessConfig({
  302. {_mqtt_payload_online, "mqttPayloadOnline", MQTT_STATUS_ONLINE},
  303. {_mqtt_payload_offline, "mqttPayloadOffline", MQTT_STATUS_OFFLINE}
  304. });
  305. // Reset reconnect delay to reconnect sooner
  306. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  307. }
  308. void _mqttBackwards() {
  309. String mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  310. if (mqttTopic.indexOf("{identifier}") > 0) {
  311. mqttTopic.replace("{identifier}", "{hostname}");
  312. setSetting("mqttTopic", mqttTopic);
  313. }
  314. }
  315. void _mqttInfo() {
  316. DEBUG_MSG_P(PSTR(
  317. "[MQTT] "
  318. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  319. "AsyncMqttClient"
  320. #elif MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  321. "Arduino-MQTT"
  322. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  323. "PubSubClient"
  324. #endif
  325. ", SSL "
  326. #if SECURE_CLIENT != SEURE_CLIENT_NONE
  327. "ENABLED"
  328. #else
  329. "DISABLED"
  330. #endif
  331. ", Autoconnect "
  332. #if MQTT_AUTOCONNECT
  333. "ENABLED"
  334. #else
  335. "DISABLED"
  336. #endif
  337. "\n"
  338. ));
  339. DEBUG_MSG_P(PSTR("[MQTT] Client %s, %s\n"),
  340. _mqtt_enabled ? "ENABLED" : "DISABLED",
  341. _mqtt.connected() ? "CONNECTED" : "DISCONNECTED"
  342. );
  343. DEBUG_MSG_P(PSTR("[MQTT] Retry %s (Now %u, Last %u, Delay %u, Step %u)\n"),
  344. _mqtt_connecting ? "CONNECTING" : "WAITING",
  345. millis(),
  346. _mqtt_last_connection,
  347. _mqtt_reconnect_delay,
  348. MQTT_RECONNECT_DELAY_STEP
  349. );
  350. }
  351. // -----------------------------------------------------------------------------
  352. // WEB
  353. // -----------------------------------------------------------------------------
  354. #if WEB_SUPPORT
  355. bool _mqttWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  356. return (strncmp(key, "mqtt", 3) == 0);
  357. }
  358. void _mqttWebSocketOnVisible(JsonObject& root) {
  359. root["mqttVisible"] = 1;
  360. #if ASYNC_TCP_SSL_ENABLED
  361. root["mqttsslVisible"] = 1;
  362. #endif
  363. }
  364. void _mqttWebSocketOnData(JsonObject& root) {
  365. root["mqttStatus"] = mqttConnected();
  366. }
  367. void _mqttWebSocketOnConnected(JsonObject& root) {
  368. root["mqttEnabled"] = mqttEnabled();
  369. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  370. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  371. root["mqttUser"] = getSetting("mqttUser", MQTT_USER);
  372. root["mqttClientID"] = getSetting("mqttClientID");
  373. root["mqttPassword"] = getSetting("mqttPassword", MQTT_PASS);
  374. root["mqttKeep"] = _mqtt_keepalive;
  375. root["mqttRetain"] = _mqtt_retain;
  376. root["mqttQoS"] = _mqtt_qos;
  377. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  378. root["mqttUseSSL"] = getSetting("mqttUseSSL", 1 == MQTT_SSL_ENABLED);
  379. root["mqttFP"] = getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  380. #endif
  381. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  382. root["mqttUseJson"] = getSetting("mqttUseJson", 1 == MQTT_USE_JSON);
  383. }
  384. #endif
  385. // -----------------------------------------------------------------------------
  386. // SETTINGS
  387. // -----------------------------------------------------------------------------
  388. #if TERMINAL_SUPPORT
  389. void _mqttInitCommands() {
  390. terminalRegisterCommand(F("MQTT.RESET"), [](Embedis* e) {
  391. _mqttConfigure();
  392. mqttDisconnect();
  393. terminalOK();
  394. });
  395. terminalRegisterCommand(F("MQTT.INFO"), [](Embedis* e) {
  396. _mqttInfo();
  397. terminalOK();
  398. });
  399. }
  400. #endif // TERMINAL_SUPPORT
  401. // -----------------------------------------------------------------------------
  402. // MQTT Callbacks
  403. // -----------------------------------------------------------------------------
  404. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  405. if (type == MQTT_CONNECT_EVENT) {
  406. // Subscribe to internal action topics
  407. mqttSubscribe(MQTT_TOPIC_ACTION);
  408. // Flag system to send heartbeat
  409. systemSendHeartbeat();
  410. }
  411. if (type == MQTT_MESSAGE_EVENT) {
  412. // Match topic
  413. String t = mqttMagnitude((char *) topic);
  414. // Actions
  415. if (t.equals(MQTT_TOPIC_ACTION)) {
  416. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  417. deferredReset(100, CUSTOM_RESET_MQTT);
  418. }
  419. }
  420. }
  421. }
  422. void _mqttOnConnect() {
  423. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  424. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  425. _mqtt_last_connection = millis();
  426. _mqtt_connecting = false;
  427. _mqtt_connected = true;
  428. // Clean subscriptions
  429. mqttUnsubscribeRaw("#");
  430. // Send connect event to subscribers
  431. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  432. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  433. }
  434. }
  435. void _mqttOnDisconnect() {
  436. // Reset reconnection delay
  437. _mqtt_last_connection = millis();
  438. _mqtt_connecting = false;
  439. _mqtt_connected = false;
  440. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  441. // Send disconnect event to subscribers
  442. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  443. (_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  444. }
  445. }
  446. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  447. if (len == 0) return;
  448. char message[len + 1];
  449. strlcpy(message, (char *) payload, len + 1);
  450. #if MQTT_SKIP_RETAINED
  451. if (millis() - _mqtt_last_connection < MQTT_SKIP_TIME) {
  452. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  453. return;
  454. }
  455. #endif
  456. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  457. // Send message event to subscribers
  458. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  459. (_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  460. }
  461. }
  462. // -----------------------------------------------------------------------------
  463. // Public API
  464. // -----------------------------------------------------------------------------
  465. /**
  466. Returns the magnitude part of a topic
  467. @param topic the full MQTT topic
  468. @return String object with the magnitude part.
  469. */
  470. String mqttMagnitude(char * topic) {
  471. String pattern = _mqtt_topic + _mqtt_setter;
  472. int position = pattern.indexOf("#");
  473. if (position == -1) return String();
  474. String start = pattern.substring(0, position);
  475. String end = pattern.substring(position + 1);
  476. String magnitude = String(topic);
  477. if (magnitude.startsWith(start) && magnitude.endsWith(end)) {
  478. magnitude.replace(start, "");
  479. magnitude.replace(end, "");
  480. } else {
  481. magnitude = String();
  482. }
  483. return magnitude;
  484. }
  485. /**
  486. Returns a full MQTT topic from the magnitude
  487. @param magnitude the magnitude part of the topic.
  488. @param is_set whether to build a command topic (true)
  489. or a state topic (false).
  490. @return String full MQTT topic.
  491. */
  492. String mqttTopic(const char * magnitude, bool is_set) {
  493. String output = _mqtt_topic;
  494. output.replace("#", magnitude);
  495. output += is_set ? _mqtt_setter : _mqtt_getter;
  496. return output;
  497. }
  498. /**
  499. Returns a full MQTT topic from the magnitude
  500. @param magnitude the magnitude part of the topic.
  501. @param index index of the magnitude when more than one such magnitudes.
  502. @param is_set whether to build a command topic (true)
  503. or a state topic (false).
  504. @return String full MQTT topic.
  505. */
  506. String mqttTopic(const char * magnitude, unsigned int index, bool is_set) {
  507. char buffer[strlen(magnitude)+5];
  508. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), magnitude, index);
  509. return mqttTopic(buffer, is_set);
  510. }
  511. // -----------------------------------------------------------------------------
  512. bool mqttSendRaw(const char * topic, const char * message, bool retain) {
  513. if (!_mqtt.connected()) return false;
  514. const unsigned int packetId(
  515. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  516. _mqtt.publish(topic, _mqtt_qos, retain, message)
  517. #elif MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  518. _mqtt.publish(topic, message, retain, _mqtt_qos)
  519. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  520. _mqtt.publish(topic, message, retain)
  521. #endif
  522. );
  523. const size_t message_len = strlen(message);
  524. if (message_len > 128) {
  525. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => (%u bytes) (PID %u)\n"), topic, message_len, packetId);
  526. } else {
  527. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %u)\n"), topic, message, packetId);
  528. }
  529. return (packetId > 0);
  530. }
  531. bool mqttSendRaw(const char * topic, const char * message) {
  532. return mqttSendRaw (topic, message, _mqtt_retain);
  533. }
  534. void mqttSend(const char * topic, const char * message, bool force, bool retain) {
  535. bool useJson = force ? false : _mqtt_use_json;
  536. // Equeue message
  537. if (useJson) {
  538. // Enqueue new message
  539. mqttEnqueue(topic, message);
  540. // Reset flush timer
  541. _mqtt_flush_ticker.once_ms(MQTT_USE_JSON_DELAY, mqttFlush);
  542. // Send it right away
  543. } else {
  544. mqttSendRaw(mqttTopic(topic, false).c_str(), message, retain);
  545. }
  546. }
  547. void mqttSend(const char * topic, const char * message, bool force) {
  548. mqttSend(topic, message, force, _mqtt_retain);
  549. }
  550. void mqttSend(const char * topic, const char * message) {
  551. mqttSend(topic, message, false);
  552. }
  553. void mqttSend(const char * topic, unsigned int index, const char * message, bool force, bool retain) {
  554. char buffer[strlen(topic)+5];
  555. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  556. mqttSend(buffer, message, force, retain);
  557. }
  558. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  559. mqttSend(topic, index, message, force, _mqtt_retain);
  560. }
  561. void mqttSend(const char * topic, unsigned int index, const char * message) {
  562. mqttSend(topic, index, message, false);
  563. }
  564. // -----------------------------------------------------------------------------
  565. unsigned char _mqttBuildTree(JsonObject& root, char parent) {
  566. unsigned char count = 0;
  567. // Add enqueued messages
  568. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  569. mqtt_message_t element = _mqtt_queue[i];
  570. if (element.parent == parent) {
  571. ++count;
  572. JsonObject& elements = root.createNestedObject(element.topic);
  573. unsigned char num = _mqttBuildTree(elements, i);
  574. if (0 == num) {
  575. if (isNumber(element.message)) {
  576. double value = atof(element.message);
  577. if (value == int(value)) {
  578. root.set(element.topic, int(value));
  579. } else {
  580. root.set(element.topic, value);
  581. }
  582. } else {
  583. root.set(element.topic, element.message);
  584. }
  585. }
  586. }
  587. }
  588. return count;
  589. }
  590. void mqttFlush() {
  591. if (!_mqtt.connected()) return;
  592. if (_mqtt_queue.size() == 0) return;
  593. // Build tree recursively
  594. DynamicJsonBuffer jsonBuffer(1024);
  595. JsonObject& root = jsonBuffer.createObject();
  596. _mqttBuildTree(root, mqtt_message_t::END);
  597. // Add extra propeties
  598. #if NTP_SUPPORT && MQTT_ENQUEUE_DATETIME
  599. if (ntpSynced()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  600. #endif
  601. #if MQTT_ENQUEUE_MAC
  602. root[MQTT_TOPIC_MAC] = WiFi.macAddress();
  603. #endif
  604. #if MQTT_ENQUEUE_HOSTNAME
  605. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  606. #endif
  607. #if MQTT_ENQUEUE_IP
  608. root[MQTT_TOPIC_IP] = getIP();
  609. #endif
  610. #if MQTT_ENQUEUE_MESSAGE_ID
  611. root[MQTT_TOPIC_MESSAGE_ID] = (Rtcmem->mqtt)++;
  612. #endif
  613. // Send
  614. String output;
  615. root.printTo(output);
  616. jsonBuffer.clear();
  617. mqttSendRaw(_mqtt_topic_json.c_str(), output.c_str(), false);
  618. // Clear queue
  619. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  620. mqtt_message_t element = _mqtt_queue[i];
  621. free(element.topic);
  622. if (element.message) {
  623. free(element.message);
  624. }
  625. }
  626. _mqtt_queue.clear();
  627. }
  628. int8_t mqttEnqueue(const char * topic, const char * message, unsigned char parent) {
  629. // Queue is not meant to send message "offline"
  630. // We must prevent the queue does not get full while offline
  631. if (!_mqtt.connected()) return -1;
  632. // Force flusing the queue if the MQTT_QUEUE_MAX_SIZE has been reached
  633. if (_mqtt_queue.size() >= MQTT_QUEUE_MAX_SIZE) mqttFlush();
  634. int8_t index = _mqtt_queue.size();
  635. // Enqueue new message
  636. mqtt_message_t element;
  637. element.parent = parent;
  638. element.topic = strdup(topic);
  639. if (NULL != message) {
  640. element.message = strdup(message);
  641. }
  642. _mqtt_queue.push_back(element);
  643. return index;
  644. }
  645. int8_t mqttEnqueue(const char * topic, const char * message) {
  646. return mqttEnqueue(topic, message, mqtt_message_t::END);
  647. }
  648. // -----------------------------------------------------------------------------
  649. void mqttSubscribeRaw(const char * topic) {
  650. if (_mqtt.connected() && (strlen(topic) > 0)) {
  651. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  652. unsigned int packetId = _mqtt.subscribe(topic, _mqtt_qos);
  653. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  654. #else // Arduino-MQTT or PubSubClient
  655. _mqtt.subscribe(topic, _mqtt_qos);
  656. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  657. #endif
  658. }
  659. }
  660. void mqttSubscribe(const char * topic) {
  661. mqttSubscribeRaw(mqttTopic(topic, true).c_str());
  662. }
  663. void mqttUnsubscribeRaw(const char * topic) {
  664. if (_mqtt.connected() && (strlen(topic) > 0)) {
  665. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  666. unsigned int packetId = _mqtt.unsubscribe(topic);
  667. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  668. #else // Arduino-MQTT or PubSubClient
  669. _mqtt.unsubscribe(topic);
  670. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  671. #endif
  672. }
  673. }
  674. void mqttUnsubscribe(const char * topic) {
  675. mqttUnsubscribeRaw(mqttTopic(topic, true).c_str());
  676. }
  677. // -----------------------------------------------------------------------------
  678. void mqttEnabled(bool status) {
  679. _mqtt_enabled = status;
  680. }
  681. bool mqttEnabled() {
  682. return _mqtt_enabled;
  683. }
  684. bool mqttConnected() {
  685. return _mqtt.connected();
  686. }
  687. void mqttDisconnect() {
  688. if (_mqtt.connected()) {
  689. DEBUG_MSG_P(PSTR("[MQTT] Disconnecting\n"));
  690. _mqtt.disconnect();
  691. }
  692. }
  693. bool mqttForward() {
  694. return _mqtt_forward;
  695. }
  696. void mqttRegister(mqtt_callback_f callback) {
  697. _mqtt_callbacks.push_back(callback);
  698. }
  699. void mqttSetBroker(IPAddress ip, uint16_t port) {
  700. setSetting("mqttServer", ip.toString());
  701. _mqtt_server = ip.toString();
  702. setSetting("mqttPort", port);
  703. _mqtt_port = port;
  704. mqttEnabled(1 == MQTT_AUTOCONNECT);
  705. }
  706. void mqttSetBrokerIfNone(IPAddress ip, uint16_t port) {
  707. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  708. mqttSetBroker(ip, port);
  709. }
  710. }
  711. const String& mqttPayloadOnline() {
  712. return _mqtt_payload_online;
  713. }
  714. const String& mqttPayloadOffline() {
  715. return _mqtt_payload_offline;
  716. }
  717. const char* mqttPayloadStatus(bool status) {
  718. return status ? _mqtt_payload_online.c_str() : _mqtt_payload_offline.c_str();
  719. }
  720. void mqttSendStatus() {
  721. mqttSend(MQTT_TOPIC_STATUS, _mqtt_payload_online.c_str(), true);
  722. }
  723. // -----------------------------------------------------------------------------
  724. // Initialization
  725. // -----------------------------------------------------------------------------
  726. void mqttSetup() {
  727. _mqttBackwards();
  728. _mqttInfo();
  729. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  730. // XXX: should not place this in config, addServerFingerprint does not check for duplicates
  731. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  732. {
  733. if (_mqtt_sc_config.on_fingerprint) {
  734. const String fingerprint = _mqtt_sc_config.on_fingerprint();
  735. uint8_t buffer[20] = {0};
  736. if (sslFingerPrintArray(fingerprint.c_str(), buffer)) {
  737. _mqtt.addServerFingerprint(buffer);
  738. }
  739. }
  740. }
  741. #endif // SECURE_CLIENT != SECURE_CLIENT_NONE
  742. _mqtt.onConnect([](bool sessionPresent) {
  743. _mqttOnConnect();
  744. });
  745. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  746. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  747. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  748. }
  749. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  750. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  751. }
  752. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  753. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  754. }
  755. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  756. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  757. }
  758. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  759. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  760. }
  761. #if SECURE_CLIENT == SECURE_CLIENT_AXTLS
  762. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  763. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  764. }
  765. #endif
  766. _mqttOnDisconnect();
  767. });
  768. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  769. _mqttOnMessage(topic, payload, len);
  770. });
  771. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  772. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  773. });
  774. _mqtt.onPublish([](uint16_t packetId) {
  775. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  776. });
  777. #elif MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  778. _mqtt.onMessageAdvanced([](MQTTClient *client, char topic[], char payload[], int length) {
  779. _mqttOnMessage(topic, payload, length);
  780. });
  781. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  782. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  783. _mqttOnMessage(topic, (char *) payload, length);
  784. });
  785. #endif // MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  786. _mqttConfigure();
  787. mqttRegister(_mqttCallback);
  788. #if WEB_SUPPORT
  789. wsRegister()
  790. .onVisible(_mqttWebSocketOnVisible)
  791. .onData(_mqttWebSocketOnData)
  792. .onConnected(_mqttWebSocketOnConnected)
  793. .onKeyCheck(_mqttWebSocketOnKeyCheck);
  794. mqttRegister([](unsigned int type, const char*, const char*) {
  795. if ((type == MQTT_CONNECT_EVENT) || (type == MQTT_DISCONNECT_EVENT)) wsPost(_mqttWebSocketOnData);
  796. });
  797. #endif
  798. #if TERMINAL_SUPPORT
  799. _mqttInitCommands();
  800. #endif
  801. // Main callbacks
  802. espurnaRegisterLoop(mqttLoop);
  803. espurnaRegisterReload(_mqttConfigure);
  804. }
  805. void mqttLoop() {
  806. if (WiFi.status() != WL_CONNECTED) return;
  807. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  808. _mqttConnect();
  809. #else // MQTT_LIBRARY != MQTT_LIBRARY_ASYNCMQTTCLIENT
  810. if (_mqtt.connected()) {
  811. _mqtt.loop();
  812. } else {
  813. if (_mqtt_connected) {
  814. _mqttOnDisconnect();
  815. }
  816. _mqttConnect();
  817. }
  818. #endif // MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  819. }
  820. #else
  821. bool mqttForward() {
  822. return false;
  823. }
  824. #endif // MQTT_SUPPORT