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.

1050 lines
30 KiB

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