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.

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