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.

1053 lines
30 KiB

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