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.

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