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.

1169 lines
34 KiB

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