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
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/SecureClientHelpers.h"
  17. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  18. AsyncMqttClient _mqtt;
  19. #else // MQTT_LIBRARY_ARDUINOMQTT / MQTT_LIBRARY_PUBSUBCLIENT
  20. WiFiClient _mqtt_client;
  21. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  22. std::unique_ptr<SecureClient> _mqtt_client_secure = nullptr;
  23. #if MQTT_SECURE_CLIENT_INCLUDE_CA
  24. #include "static/mqtt_client_trusted_root_ca.h" // Assumes this header file defines a _mqtt_client_trusted_root_ca[] PROGMEM = "...PEM data..."
  25. #else
  26. #include "static/letsencrypt_isrgroot_pem.h" // Default to LetsEncrypt X3 certificate
  27. #define _mqtt_client_trusted_root_ca _ssl_letsencrypt_isrg_x3_ca
  28. #endif // MQTT_SECURE_CLIENT_INCLUDE_CA
  29. #endif // SECURE_CLIENT != SECURE_CLIENT_NONE
  30. #if MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  31. #ifdef MQTT_MAX_PACKET_SIZE
  32. MQTTClient _mqtt(MQTT_MAX_PACKET_SIZE);
  33. #else
  34. MQTTClient _mqtt;
  35. #endif
  36. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  37. PubSubClient _mqtt;
  38. #endif
  39. #endif // MQTT_LIBRARY == MQTT_ASYNCMQTTCLIENT
  40. bool _mqtt_enabled = MQTT_ENABLED;
  41. bool _mqtt_use_json = false;
  42. unsigned long _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  43. unsigned long _mqtt_last_connection = 0;
  44. bool _mqtt_connected = false;
  45. bool _mqtt_connecting = false;
  46. bool _mqtt_retain = MQTT_RETAIN;
  47. int _mqtt_qos = MQTT_QOS;
  48. int _mqtt_keepalive = MQTT_KEEPALIVE;
  49. String _mqtt_topic;
  50. String _mqtt_topic_json;
  51. String _mqtt_setter;
  52. String _mqtt_getter;
  53. bool _mqtt_forward;
  54. String _mqtt_user;
  55. String _mqtt_pass;
  56. String _mqtt_will;
  57. String _mqtt_server;
  58. uint16_t _mqtt_port;
  59. String _mqtt_clientid;
  60. String _mqtt_payload_online;
  61. String _mqtt_payload_offline;
  62. std::vector<mqtt_callback_f> _mqtt_callbacks;
  63. struct mqtt_message_t {
  64. static const unsigned char END = 255;
  65. unsigned char parent = END;
  66. char * topic;
  67. char * message = NULL;
  68. };
  69. std::vector<mqtt_message_t> _mqtt_queue;
  70. Ticker _mqtt_flush_ticker;
  71. // -----------------------------------------------------------------------------
  72. // Private
  73. // -----------------------------------------------------------------------------
  74. #if SECURE_CLIENT == SECURE_CLIENT_AXTLS
  75. SecureClientConfig _mqtt_sc_config {
  76. "MQTT",
  77. []() -> String {
  78. return _mqtt_server;
  79. },
  80. []() -> int {
  81. return getSetting("mqttScCheck", MQTT_SECURE_CLIENT_CHECK);
  82. },
  83. []() -> String {
  84. return getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  85. },
  86. true
  87. };
  88. #endif
  89. #if SECURE_CLIENT == SECURE_CLIENT_BEARSSL
  90. SecureClientConfig _mqtt_sc_config {
  91. "MQTT",
  92. []() -> int {
  93. return getSetting("mqttScCheck", MQTT_SECURE_CLIENT_CHECK);
  94. },
  95. []() -> PGM_P {
  96. return _mqtt_client_trusted_root_ca;
  97. },
  98. []() -> String {
  99. return getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  100. },
  101. []() -> uint16_t {
  102. return getSetting<uint16_t>("mqttScMFLN", MQTT_SECURE_CLIENT_MFLN);
  103. },
  104. true
  105. };
  106. #endif
  107. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  108. void _mqttSetupAsyncClient(bool secure = false) {
  109. _mqtt.setServer(_mqtt_server.c_str(), _mqtt_port);
  110. _mqtt.setClientId(_mqtt_clientid.c_str());
  111. _mqtt.setKeepAlive(_mqtt_keepalive);
  112. _mqtt.setCleanSession(false);
  113. _mqtt.setWill(_mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, _mqtt_payload_offline.c_str());
  114. if (_mqtt_user.length() && _mqtt_pass.length()) {
  115. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user.c_str());
  116. _mqtt.setCredentials(_mqtt_user.c_str(), _mqtt_pass.c_str());
  117. }
  118. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  119. if (secure) {
  120. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  121. _mqtt.setSecure(secure);
  122. }
  123. #endif // SECURE_CLIENT != SECURE_CLIENT_NONE
  124. _mqtt.connect();
  125. }
  126. #endif // MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  127. #if (MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT) || (MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT)
  128. WiFiClient& _mqttGetClient(bool secure) {
  129. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  130. return (secure ? _mqtt_client_secure->get() : _mqtt_client);
  131. #else
  132. return _mqtt_client;
  133. #endif
  134. }
  135. bool _mqttSetupSyncClient(bool secure = false) {
  136. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  137. if (secure) {
  138. if (!_mqtt_client_secure) _mqtt_client_secure = std::make_unique<SecureClient>(_mqtt_sc_config);
  139. return _mqtt_client_secure->beforeConnected();
  140. }
  141. #endif
  142. return true;
  143. }
  144. bool _mqttConnectSyncClient(bool secure = false) {
  145. bool result = false;
  146. #if MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  147. _mqtt.begin(_mqtt_server.c_str(), _mqtt_port, _mqttGetClient(secure));
  148. _mqtt.setWill(_mqtt_will.c_str(), _mqtt_payload_offline.c_str(), _mqtt_retain, _mqtt_qos);
  149. _mqtt.setKeepAlive(_mqtt_keepalive);
  150. result = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_user.c_str(), _mqtt_pass.c_str());
  151. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  152. _mqtt.setClient(_mqttGetClient(secure));
  153. _mqtt.setServer(_mqtt_server.c_str(), _mqtt_port);
  154. if (_mqtt_user.length() && _mqtt_pass.length()) {
  155. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user.c_str());
  156. result = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_user.c_str(), _mqtt_pass.c_str(), _mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, _mqtt_payload_offline.c_str());
  157. } else {
  158. result = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, _mqtt_payload_offline.c_str());
  159. }
  160. #endif
  161. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  162. if (result && secure) {
  163. result = _mqtt_client_secure->afterConnected();
  164. }
  165. #endif
  166. return result;
  167. }
  168. #endif // (MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT) || (MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT)
  169. void _mqttConnect() {
  170. // Do not connect if disabled
  171. if (!_mqtt_enabled) return;
  172. // Do not connect if already connected or still trying to connect
  173. if (_mqtt.connected() || _mqtt_connecting) return;
  174. // Check reconnect interval
  175. if (millis() - _mqtt_last_connection < _mqtt_reconnect_delay) return;
  176. // Increase the reconnect delay
  177. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  178. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  179. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  180. }
  181. #if MDNS_CLIENT_SUPPORT
  182. _mqtt_server = mdnsResolve(_mqtt_server);
  183. #endif
  184. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%u\n"), _mqtt_server.c_str(), _mqtt_port);
  185. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid.c_str());
  186. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  187. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  188. DEBUG_MSG_P(PSTR("[MQTT] Keepalive time: %ds\n"), _mqtt_keepalive);
  189. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will.c_str());
  190. _mqtt_connecting = true;
  191. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  192. const bool secure = getSetting("mqttUseSSL", 1 == MQTT_SSL_ENABLED);
  193. #else
  194. const bool secure = false;
  195. #endif
  196. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  197. _mqttSetupAsyncClient(secure);
  198. #elif (MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT) || (MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT)
  199. if (_mqttSetupSyncClient(secure) && _mqttConnectSyncClient(secure)) {
  200. _mqttOnConnect();
  201. } else {
  202. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  203. _mqttOnDisconnect();
  204. }
  205. #else
  206. #error "please check that MQTT_LIBRARY is valid"
  207. #endif
  208. }
  209. void _mqttPlaceholders(String& text) {
  210. text.replace("{hostname}", getSetting("hostname"));
  211. text.replace("{magnitude}", "#");
  212. String mac = WiFi.macAddress();
  213. mac.replace(":", "");
  214. text.replace("{mac}", mac);
  215. }
  216. template<typename T>
  217. void _mqttApplySetting(T& current, T& updated) {
  218. if (current != updated) {
  219. current = std::move(updated);
  220. mqttDisconnect();
  221. }
  222. }
  223. template<typename T>
  224. void _mqttApplySetting(T& current, const T& updated) {
  225. if (current != updated) {
  226. current = updated;
  227. mqttDisconnect();
  228. }
  229. }
  230. template<typename T>
  231. void _mqttApplyTopic(T& current, const char* magnitude) {
  232. String updated = mqttTopic(magnitude, false);
  233. if (current != updated) {
  234. mqttFlush();
  235. current = std::move(updated);
  236. }
  237. }
  238. void _mqttConfigure() {
  239. // Enable only when server is set
  240. {
  241. const String server = getSetting("mqttServer", MQTT_SERVER);
  242. const auto port = getSetting<uint16_t>("mqttPort", MQTT_PORT);
  243. bool enabled = false;
  244. if (server.length()) {
  245. enabled = getSetting("mqttEnabled", 1 == MQTT_ENABLED);
  246. }
  247. _mqttApplySetting(_mqtt_server, server);
  248. _mqttApplySetting(_mqtt_enabled, enabled);
  249. _mqttApplySetting(_mqtt_port, port);
  250. if (!enabled) return;
  251. }
  252. // Get base topic and apply placeholders
  253. {
  254. String topic = getSetting("mqttTopic", MQTT_TOPIC);
  255. if (topic.endsWith("/")) topic.remove(topic.length()-1);
  256. // Replace things inside curly braces (like {hostname}, {mac} etc.)
  257. _mqttPlaceholders(topic);
  258. if (topic.indexOf("#") == -1) topic.concat("/#");
  259. _mqttApplySetting(_mqtt_topic, topic);
  260. }
  261. // Getter and setter
  262. {
  263. String setter = getSetting("mqttSetter", MQTT_SETTER);
  264. String getter = getSetting("mqttGetter", MQTT_GETTER);
  265. bool forward = !setter.equals(getter) && RELAY_REPORT_STATUS;
  266. _mqttApplySetting(_mqtt_setter, setter);
  267. _mqttApplySetting(_mqtt_getter, getter);
  268. _mqttApplySetting(_mqtt_forward, forward);
  269. }
  270. // MQTT options
  271. {
  272. String user = getSetting("mqttUser", MQTT_USER);
  273. _mqttPlaceholders(user);
  274. String pass = getSetting("mqttPassword", MQTT_PASS);
  275. const auto qos = getSetting("mqttQoS", MQTT_QOS);
  276. const bool retain = getSetting("mqttRetain", 1 == MQTT_RETAIN);
  277. // Note: MQTT spec defines this as 2 bytes
  278. const auto keepalive = constrain(
  279. getSetting("mqttKeep", MQTT_KEEPALIVE),
  280. 0, std::numeric_limits<uint16_t>::max()
  281. );
  282. String id = getSetting("mqttClientID", getIdentifier());
  283. _mqttPlaceholders(id);
  284. _mqttApplySetting(_mqtt_user, user);
  285. _mqttApplySetting(_mqtt_pass, pass);
  286. _mqttApplySetting(_mqtt_qos, qos);
  287. _mqttApplySetting(_mqtt_retain, retain);
  288. _mqttApplySetting(_mqtt_keepalive, keepalive);
  289. _mqttApplySetting(_mqtt_clientid, id);
  290. }
  291. // MQTT WILL
  292. {
  293. _mqttApplyTopic(_mqtt_will, MQTT_TOPIC_STATUS);
  294. }
  295. // MQTT JSON
  296. {
  297. _mqttApplySetting(_mqtt_use_json, getSetting("mqttUseJson", 1 == MQTT_USE_JSON));
  298. _mqttApplyTopic(_mqtt_topic_json, MQTT_TOPIC_JSON);
  299. }
  300. // Custom payload strings
  301. settingsProcessConfig({
  302. {_mqtt_payload_online, "mqttPayloadOnline", MQTT_STATUS_ONLINE},
  303. {_mqtt_payload_offline, "mqttPayloadOffline", MQTT_STATUS_OFFLINE}
  304. });
  305. // Reset reconnect delay to reconnect sooner
  306. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  307. }
  308. void _mqttBackwards() {
  309. String mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  310. if (mqttTopic.indexOf("{identifier}") > 0) {
  311. mqttTopic.replace("{identifier}", "{hostname}");
  312. setSetting("mqttTopic", mqttTopic);
  313. }
  314. }
  315. void _mqttInfo() {
  316. DEBUG_MSG_P(PSTR(
  317. "[MQTT] "
  318. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  319. "AsyncMqttClient"
  320. #elif MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  321. "Arduino-MQTT"
  322. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  323. "PubSubClient"
  324. #endif
  325. ", SSL "
  326. #if SECURE_CLIENT != SEURE_CLIENT_NONE
  327. "ENABLED"
  328. #else
  329. "DISABLED"
  330. #endif
  331. ", Autoconnect "
  332. #if MQTT_AUTOCONNECT
  333. "ENABLED"
  334. #else
  335. "DISABLED"
  336. #endif
  337. "\n"
  338. ));
  339. DEBUG_MSG_P(PSTR("[MQTT] Client %s, %s\n"),
  340. _mqtt_enabled ? "ENABLED" : "DISABLED",
  341. _mqtt.connected() ? "CONNECTED" : "DISCONNECTED"
  342. );
  343. DEBUG_MSG_P(PSTR("[MQTT] Retry %s (Now %u, Last %u, Delay %u, Step %u)\n"),
  344. _mqtt_connecting ? "CONNECTING" : "WAITING",
  345. millis(),
  346. _mqtt_last_connection,
  347. _mqtt_reconnect_delay,
  348. MQTT_RECONNECT_DELAY_STEP
  349. );
  350. }
  351. // -----------------------------------------------------------------------------
  352. // WEB
  353. // -----------------------------------------------------------------------------
  354. #if WEB_SUPPORT
  355. bool _mqttWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  356. return (strncmp(key, "mqtt", 3) == 0);
  357. }
  358. void _mqttWebSocketOnVisible(JsonObject& root) {
  359. root["mqttVisible"] = 1;
  360. #if ASYNC_TCP_SSL_ENABLED
  361. root["mqttsslVisible"] = 1;
  362. #endif
  363. }
  364. void _mqttWebSocketOnData(JsonObject& root) {
  365. root["mqttStatus"] = mqttConnected();
  366. }
  367. void _mqttWebSocketOnConnected(JsonObject& root) {
  368. root["mqttEnabled"] = mqttEnabled();
  369. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  370. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  371. root["mqttUser"] = getSetting("mqttUser", MQTT_USER);
  372. root["mqttClientID"] = getSetting("mqttClientID");
  373. root["mqttPassword"] = getSetting("mqttPassword", MQTT_PASS);
  374. root["mqttKeep"] = _mqtt_keepalive;
  375. root["mqttRetain"] = _mqtt_retain;
  376. root["mqttQoS"] = _mqtt_qos;
  377. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  378. root["mqttUseSSL"] = getSetting("mqttUseSSL", 1 == MQTT_SSL_ENABLED);
  379. root["mqttFP"] = getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  380. #endif
  381. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  382. root["mqttUseJson"] = getSetting("mqttUseJson", 1 == MQTT_USE_JSON);
  383. }
  384. #endif
  385. // -----------------------------------------------------------------------------
  386. // SETTINGS
  387. // -----------------------------------------------------------------------------
  388. #if TERMINAL_SUPPORT
  389. void _mqttInitCommands() {
  390. terminalRegisterCommand(F("MQTT.RESET"), [](Embedis* e) {
  391. _mqttConfigure();
  392. mqttDisconnect();
  393. terminalOK();
  394. });
  395. terminalRegisterCommand(F("MQTT.INFO"), [](Embedis* e) {
  396. _mqttInfo();
  397. terminalOK();
  398. });
  399. }
  400. #endif // TERMINAL_SUPPORT
  401. // -----------------------------------------------------------------------------
  402. // MQTT Callbacks
  403. // -----------------------------------------------------------------------------
  404. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  405. if (type == MQTT_CONNECT_EVENT) {
  406. // Subscribe to internal action topics
  407. mqttSubscribe(MQTT_TOPIC_ACTION);
  408. // Flag system to send heartbeat
  409. systemSendHeartbeat();
  410. }
  411. if (type == MQTT_MESSAGE_EVENT) {
  412. // Match topic
  413. String t = mqttMagnitude((char *) topic);
  414. // Actions
  415. if (t.equals(MQTT_TOPIC_ACTION)) {
  416. rpcHandleAction(payload);
  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