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.

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