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.

1061 lines
30 KiB

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