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