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.

1212 lines
36 KiB

7 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
6 years ago
6 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. #include "mqtt.h"
  7. #if MQTT_SUPPORT
  8. #include <forward_list>
  9. #include <utility>
  10. #include <Ticker.h>
  11. #include "system.h"
  12. #include "mdns.h"
  13. #include "mqtt.h"
  14. #include "ntp.h"
  15. #include "rpc.h"
  16. #include "rtcmem.h"
  17. #include "ws.h"
  18. #include "libs/AsyncClientHelpers.h"
  19. #include "libs/SecureClientHelpers.h"
  20. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  21. #include <ESPAsyncTCP.h>
  22. #include <AsyncMqttClient.h>
  23. #elif MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  24. #include <MQTTClient.h>
  25. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  26. #include <PubSubClient.h>
  27. #endif
  28. // -----------------------------------------------------------------------------
  29. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  30. AsyncMqttClient _mqtt;
  31. #else // MQTT_LIBRARY_ARDUINOMQTT / MQTT_LIBRARY_PUBSUBCLIENT
  32. WiFiClient _mqtt_client;
  33. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  34. std::unique_ptr<SecureClient> _mqtt_client_secure = nullptr;
  35. #if MQTT_SECURE_CLIENT_INCLUDE_CA
  36. #include "static/mqtt_client_trusted_root_ca.h" // Assumes this header file defines a _mqtt_client_trusted_root_ca[] PROGMEM = "...PEM data..."
  37. #else
  38. #include "static/letsencrypt_isrgroot_pem.h" // Default to LetsEncrypt X3 certificate
  39. #define _mqtt_client_trusted_root_ca _ssl_letsencrypt_isrg_x3_ca
  40. #endif // MQTT_SECURE_CLIENT_INCLUDE_CA
  41. #endif // SECURE_CLIENT != SECURE_CLIENT_NONE
  42. #if MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  43. MQTTClient _mqtt(MQTT_BUFFER_MAX_SIZE);
  44. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  45. PubSubClient _mqtt;
  46. #endif
  47. #endif // MQTT_LIBRARY == MQTT_ASYNCMQTTCLIENT
  48. unsigned long _mqtt_last_connection = 0;
  49. AsyncClientState _mqtt_state = AsyncClientState::Disconnected;
  50. bool _mqtt_skip_messages = false;
  51. unsigned long _mqtt_skip_time = MQTT_SKIP_TIME;
  52. unsigned long _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  53. bool _mqtt_enabled = MQTT_ENABLED;
  54. bool _mqtt_use_json = false;
  55. bool _mqtt_retain = MQTT_RETAIN;
  56. int _mqtt_qos = MQTT_QOS;
  57. int _mqtt_keepalive = MQTT_KEEPALIVE;
  58. String _mqtt_topic;
  59. String _mqtt_topic_json;
  60. String _mqtt_setter;
  61. String _mqtt_getter;
  62. bool _mqtt_forward;
  63. String _mqtt_user;
  64. String _mqtt_pass;
  65. String _mqtt_will;
  66. String _mqtt_server;
  67. uint16_t _mqtt_port;
  68. String _mqtt_clientid;
  69. std::forward_list<heartbeat::Callback> _mqtt_heartbeat_callbacks;
  70. heartbeat::Mode _mqtt_heartbeat_mode;
  71. heartbeat::Seconds _mqtt_heartbeat_interval;
  72. String _mqtt_payload_online;
  73. String _mqtt_payload_offline;
  74. std::forward_list<mqtt_callback_f> _mqtt_callbacks;
  75. int8_t _mqtt_queue_count { 0u };
  76. std::forward_list<MqttMessage> _mqtt_queue;
  77. Ticker _mqtt_flush_ticker;
  78. // -----------------------------------------------------------------------------
  79. // Private
  80. // -----------------------------------------------------------------------------
  81. #if SECURE_CLIENT == SECURE_CLIENT_AXTLS
  82. SecureClientConfig _mqtt_sc_config {
  83. "MQTT",
  84. []() -> String {
  85. return _mqtt_server;
  86. },
  87. []() -> int {
  88. return getSetting("mqttScCheck", MQTT_SECURE_CLIENT_CHECK);
  89. },
  90. []() -> String {
  91. return getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  92. },
  93. true
  94. };
  95. #endif
  96. #if SECURE_CLIENT == SECURE_CLIENT_BEARSSL
  97. SecureClientConfig _mqtt_sc_config {
  98. "MQTT",
  99. []() -> int {
  100. return getSetting("mqttScCheck", MQTT_SECURE_CLIENT_CHECK);
  101. },
  102. []() -> PGM_P {
  103. return _mqtt_client_trusted_root_ca;
  104. },
  105. []() -> String {
  106. return getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  107. },
  108. []() -> uint16_t {
  109. return getSetting("mqttScMFLN", MQTT_SECURE_CLIENT_MFLN);
  110. },
  111. true
  112. };
  113. #endif
  114. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  115. void _mqttSetupAsyncClient(bool secure = false) {
  116. _mqtt.setServer(_mqtt_server.c_str(), _mqtt_port);
  117. _mqtt.setClientId(_mqtt_clientid.c_str());
  118. _mqtt.setKeepAlive(_mqtt_keepalive);
  119. _mqtt.setCleanSession(false);
  120. _mqtt.setWill(_mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, _mqtt_payload_offline.c_str());
  121. if (_mqtt_user.length() && _mqtt_pass.length()) {
  122. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user.c_str());
  123. _mqtt.setCredentials(_mqtt_user.c_str(), _mqtt_pass.c_str());
  124. }
  125. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  126. if (secure) {
  127. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  128. _mqtt.setSecure(secure);
  129. }
  130. #endif // SECURE_CLIENT != SECURE_CLIENT_NONE
  131. _mqtt.connect();
  132. }
  133. #endif // MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  134. #if (MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT) || (MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT)
  135. WiFiClient& _mqttGetClient(bool secure) {
  136. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  137. return (secure ? _mqtt_client_secure->get() : _mqtt_client);
  138. #else
  139. return _mqtt_client;
  140. #endif
  141. }
  142. bool _mqttSetupSyncClient(bool secure = false) {
  143. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  144. if (secure) {
  145. if (!_mqtt_client_secure) _mqtt_client_secure = std::make_unique<SecureClient>(_mqtt_sc_config);
  146. return _mqtt_client_secure->beforeConnected();
  147. }
  148. #endif
  149. return true;
  150. }
  151. bool _mqttConnectSyncClient(bool secure = false) {
  152. bool result = false;
  153. #if MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  154. _mqtt.begin(_mqtt_server.c_str(), _mqtt_port, _mqttGetClient(secure));
  155. _mqtt.setWill(_mqtt_will.c_str(), _mqtt_payload_offline.c_str(), _mqtt_retain, _mqtt_qos);
  156. _mqtt.setKeepAlive(_mqtt_keepalive);
  157. result = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_user.c_str(), _mqtt_pass.c_str());
  158. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  159. _mqtt.setClient(_mqttGetClient(secure));
  160. _mqtt.setServer(_mqtt_server.c_str(), _mqtt_port);
  161. if (_mqtt_user.length() && _mqtt_pass.length()) {
  162. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user.c_str());
  163. 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());
  164. } else {
  165. result = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, _mqtt_payload_offline.c_str());
  166. }
  167. #endif
  168. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  169. if (result && secure) {
  170. result = _mqtt_client_secure->afterConnected();
  171. }
  172. #endif
  173. return result;
  174. }
  175. #endif // (MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT) || (MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT)
  176. void _mqttPlaceholders(String& text) {
  177. text.replace("{hostname}", getSetting("hostname"));
  178. text.replace("{magnitude}", "#");
  179. String mac = WiFi.macAddress();
  180. mac.replace(":", "");
  181. text.replace("{mac}", mac);
  182. }
  183. template<typename T>
  184. void _mqttApplySetting(T& current, T& updated) {
  185. if (current != updated) {
  186. current = std::move(updated);
  187. mqttDisconnect();
  188. }
  189. }
  190. template<typename T>
  191. void _mqttApplySetting(T& current, const T& updated) {
  192. if (current != updated) {
  193. current = updated;
  194. mqttDisconnect();
  195. }
  196. }
  197. template<typename T>
  198. void _mqttApplyTopic(T& current, const char* magnitude) {
  199. String updated = mqttTopic(magnitude, false);
  200. if (current != updated) {
  201. mqttFlush();
  202. current = std::move(updated);
  203. }
  204. }
  205. void _mqttConfigure() {
  206. // Enable only when server is set
  207. {
  208. const String server = getSetting("mqttServer", MQTT_SERVER);
  209. const auto port = getSetting("mqttPort", static_cast<uint16_t>(MQTT_PORT));
  210. bool enabled = false;
  211. if (server.length()) {
  212. enabled = getSetting("mqttEnabled", 1 == MQTT_ENABLED);
  213. }
  214. _mqttApplySetting(_mqtt_server, server);
  215. _mqttApplySetting(_mqtt_enabled, enabled);
  216. _mqttApplySetting(_mqtt_port, port);
  217. if (!enabled) return;
  218. }
  219. // Get base topic and apply placeholders
  220. {
  221. String topic = getSetting("mqttTopic", MQTT_TOPIC);
  222. if (topic.endsWith("/")) topic.remove(topic.length()-1);
  223. // Replace things inside curly braces (like {hostname}, {mac} etc.)
  224. _mqttPlaceholders(topic);
  225. if (topic.indexOf("#") == -1) topic.concat("/#");
  226. _mqttApplySetting(_mqtt_topic, topic);
  227. }
  228. // Getter and setter
  229. {
  230. String setter = getSetting("mqttSetter", MQTT_SETTER);
  231. String getter = getSetting("mqttGetter", MQTT_GETTER);
  232. bool forward = !setter.equals(getter) && RELAY_REPORT_STATUS;
  233. _mqttApplySetting(_mqtt_setter, setter);
  234. _mqttApplySetting(_mqtt_getter, getter);
  235. _mqttApplySetting(_mqtt_forward, forward);
  236. }
  237. // MQTT options
  238. {
  239. String user = getSetting("mqttUser", MQTT_USER);
  240. _mqttPlaceholders(user);
  241. String pass = getSetting("mqttPassword", MQTT_PASS);
  242. const auto qos = getSetting("mqttQoS", MQTT_QOS);
  243. const bool retain = getSetting("mqttRetain", 1 == MQTT_RETAIN);
  244. // Note: MQTT spec defines this as 2 bytes
  245. const auto keepalive = constrain(
  246. getSetting("mqttKeep", MQTT_KEEPALIVE),
  247. 0, std::numeric_limits<uint16_t>::max()
  248. );
  249. String id = getSetting("mqttClientID", getIdentifier());
  250. _mqttPlaceholders(id);
  251. _mqttApplySetting(_mqtt_user, user);
  252. _mqttApplySetting(_mqtt_pass, pass);
  253. _mqttApplySetting(_mqtt_qos, qos);
  254. _mqttApplySetting(_mqtt_retain, retain);
  255. _mqttApplySetting(_mqtt_keepalive, keepalive);
  256. _mqttApplySetting(_mqtt_clientid, id);
  257. _mqttApplyTopic(_mqtt_will, MQTT_TOPIC_STATUS);
  258. }
  259. // MQTT JSON
  260. {
  261. _mqttApplySetting(_mqtt_use_json, getSetting("mqttUseJson", 1 == MQTT_USE_JSON));
  262. _mqttApplyTopic(_mqtt_topic_json, MQTT_TOPIC_JSON);
  263. }
  264. _mqttApplySetting(_mqtt_heartbeat_mode,
  265. getSetting("mqttHbMode", heartbeat::currentMode()));
  266. _mqttApplySetting(_mqtt_heartbeat_interval,
  267. getSetting("mqttHbIntvl", heartbeat::currentInterval()));
  268. // Skip messages in a small window right after the connection
  269. _mqtt_skip_time = getSetting("mqttSkipTime", MQTT_SKIP_TIME);
  270. // Custom payload strings
  271. settingsProcessConfig({
  272. {_mqtt_payload_online, "mqttPayloadOnline", MQTT_STATUS_ONLINE},
  273. {_mqtt_payload_offline, "mqttPayloadOffline", MQTT_STATUS_OFFLINE}
  274. });
  275. // Reset reconnect delay to reconnect sooner
  276. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  277. }
  278. void _mqttBackwards() {
  279. String mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  280. if (mqttTopic.indexOf("{identifier}") > 0) {
  281. mqttTopic.replace("{identifier}", "{hostname}");
  282. setSetting("mqttTopic", mqttTopic);
  283. }
  284. }
  285. void _mqttInfo() {
  286. // Build information
  287. {
  288. #define __MQTT_INFO_STR(X) #X
  289. #define _MQTT_INFO_STR(X) __MQTT_INFO_STR(X)
  290. DEBUG_MSG_P(PSTR(
  291. "[MQTT] "
  292. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  293. "AsyncMqttClient"
  294. #elif MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  295. "Arduino-MQTT"
  296. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  297. "PubSubClient"
  298. #endif
  299. ", SSL "
  300. #if SECURE_CLIENT != SEURE_CLIENT_NONE
  301. "ENABLED"
  302. #else
  303. "DISABLED"
  304. #endif
  305. ", Autoconnect "
  306. #if MQTT_AUTOCONNECT
  307. "ENABLED"
  308. #else
  309. "DISABLED"
  310. #endif
  311. ", Buffer size " _MQTT_INFO_STR(MQTT_BUFFER_MAX_SIZE) " bytes"
  312. "\n"
  313. ));
  314. #undef _MQTT_INFO_STR
  315. #undef __MQTT_INFO_STR
  316. }
  317. // Notify about the general state of the client
  318. {
  319. const __FlashStringHelper* enabled = _mqtt_enabled
  320. ? F("ENABLED")
  321. : F("DISABLED");
  322. const __FlashStringHelper* state = nullptr;
  323. switch (_mqtt_state) {
  324. case AsyncClientState::Connecting:
  325. state = F("CONNECTING");
  326. break;
  327. case AsyncClientState::Connected:
  328. state = F("CONNECTED");
  329. break;
  330. case AsyncClientState::Disconnected:
  331. state = F("DISCONNECTED");
  332. break;
  333. case AsyncClientState::Disconnecting:
  334. state = F("DISCONNECTING");
  335. break;
  336. default:
  337. state = F("WAITING");
  338. break;
  339. }
  340. DEBUG_MSG_P(PSTR("[MQTT] Client %s, %s\n"),
  341. String(enabled).c_str(),
  342. String(state).c_str()
  343. );
  344. if (_mqtt_enabled && (_mqtt_state != AsyncClientState::Connected)) {
  345. DEBUG_MSG_P(PSTR("[MQTT] Retrying, Last %u with Delay %u (Step %u)\n"),
  346. _mqtt_last_connection,
  347. _mqtt_reconnect_delay,
  348. MQTT_RECONNECT_DELAY_STEP
  349. );
  350. }
  351. }
  352. }
  353. // -----------------------------------------------------------------------------
  354. // WEB
  355. // -----------------------------------------------------------------------------
  356. #if WEB_SUPPORT
  357. bool _mqttWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  358. return (strncmp(key, "mqtt", 3) == 0);
  359. }
  360. void _mqttWebSocketOnVisible(JsonObject& root) {
  361. root["mqttVisible"] = 1;
  362. #if ASYNC_TCP_SSL_ENABLED
  363. root["mqttsslVisible"] = 1;
  364. #endif
  365. }
  366. void _mqttWebSocketOnData(JsonObject& root) {
  367. root["mqttStatus"] = mqttConnected();
  368. }
  369. void _mqttWebSocketOnConnected(JsonObject& root) {
  370. root["mqttEnabled"] = mqttEnabled();
  371. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  372. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  373. root["mqttUser"] = getSetting("mqttUser", MQTT_USER);
  374. root["mqttClientID"] = getSetting("mqttClientID");
  375. root["mqttPassword"] = getSetting("mqttPassword", MQTT_PASS);
  376. root["mqttKeep"] = _mqtt_keepalive;
  377. root["mqttRetain"] = _mqtt_retain;
  378. root["mqttQoS"] = _mqtt_qos;
  379. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  380. root["mqttUseSSL"] = getSetting("mqttUseSSL", 1 == MQTT_SSL_ENABLED);
  381. root["mqttFP"] = getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  382. #endif
  383. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  384. root["mqttUseJson"] = getSetting("mqttUseJson", 1 == MQTT_USE_JSON);
  385. }
  386. #endif
  387. // -----------------------------------------------------------------------------
  388. // SETTINGS
  389. // -----------------------------------------------------------------------------
  390. #if TERMINAL_SUPPORT
  391. void _mqttInitCommands() {
  392. terminalRegisterCommand(F("MQTT.RESET"), [](const terminal::CommandContext&) {
  393. _mqttConfigure();
  394. mqttDisconnect();
  395. terminalOK();
  396. });
  397. terminalRegisterCommand(F("MQTT.INFO"), [](const terminal::CommandContext&) {
  398. _mqttInfo();
  399. terminalOK();
  400. });
  401. }
  402. #endif // TERMINAL_SUPPORT
  403. // -----------------------------------------------------------------------------
  404. // MQTT Callbacks
  405. // -----------------------------------------------------------------------------
  406. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  407. if (type == MQTT_CONNECT_EVENT) {
  408. mqttSubscribe(MQTT_TOPIC_ACTION);
  409. }
  410. if (type == MQTT_MESSAGE_EVENT) {
  411. String t = mqttMagnitude(topic);
  412. if (t.equals(MQTT_TOPIC_ACTION)) {
  413. rpcHandleAction(payload);
  414. }
  415. }
  416. }
  417. bool _mqttHeartbeat(heartbeat::Mask mask) {
  418. // Backported from the older utils implementation.
  419. // Wait until the time is synced to avoid sending partial report *and*
  420. // as a result, wait until the next interval to actually send the datetime string.
  421. #if NTP_SUPPORT
  422. if ((mask & heartbeat::Report::Datetime) && !ntpSynced()) {
  423. return false;
  424. }
  425. #endif
  426. if (!mqttConnected()) {
  427. return false;
  428. }
  429. // TODO: rework old HEARTBEAT_REPEAT_STATUS?
  430. // for example: send full report once, send only the dynamic data after that
  431. // (interval, hostname, description, ssid, bssid, ip, mac, rssi, uptime, datetime, heap, loadavg, vcc)
  432. // otherwise, it is still possible by setting everything to 0 *but* the Report::Status bit
  433. // TODO: per-module mask?
  434. // TODO: simply send static data with onConnected, and the rest from here?
  435. if (mask & heartbeat::Report::Status)
  436. mqttSendStatus();
  437. if (mask & heartbeat::Report::Interval)
  438. mqttSend(MQTT_TOPIC_INTERVAL, String(_mqtt_heartbeat_interval.count()).c_str());
  439. if (mask & heartbeat::Report::App)
  440. mqttSend(MQTT_TOPIC_APP, APP_NAME);
  441. if (mask & heartbeat::Report::Version)
  442. mqttSend(MQTT_TOPIC_VERSION, getVersion().c_str());
  443. if (mask & heartbeat::Report::Board)
  444. mqttSend(MQTT_TOPIC_BOARD, getBoardName().c_str());
  445. if (mask & heartbeat::Report::Hostname)
  446. mqttSend(MQTT_TOPIC_HOSTNAME, getSetting("hostname", getIdentifier()).c_str());
  447. if (mask & heartbeat::Report::Description) {
  448. auto desc = getSetting("desc");
  449. if (desc.length()) {
  450. mqttSend(MQTT_TOPIC_DESCRIPTION, desc.c_str());
  451. }
  452. }
  453. if (mask & heartbeat::Report::Ssid)
  454. mqttSend(MQTT_TOPIC_SSID, WiFi.SSID().c_str());
  455. if (mask & heartbeat::Report::Bssid)
  456. mqttSend(MQTT_TOPIC_BSSID, WiFi.BSSIDstr().c_str());
  457. if (mask & heartbeat::Report::Ip)
  458. mqttSend(MQTT_TOPIC_IP, getIP().c_str());
  459. if (mask & heartbeat::Report::Mac)
  460. mqttSend(MQTT_TOPIC_MAC, WiFi.macAddress().c_str());
  461. if (mask & heartbeat::Report::Rssi)
  462. mqttSend(MQTT_TOPIC_RSSI, String(WiFi.RSSI()).c_str());
  463. if (mask & heartbeat::Report::Uptime)
  464. mqttSend(MQTT_TOPIC_UPTIME, String(systemUptime()).c_str());
  465. #if NTP_SUPPORT
  466. if (mask & heartbeat::Report::Datetime)
  467. mqttSend(MQTT_TOPIC_DATETIME, ntpDateTime().c_str());
  468. #endif
  469. if (mask & heartbeat::Report::Freeheap) {
  470. auto stats = systemHeapStats();
  471. mqttSend(MQTT_TOPIC_FREEHEAP, String(stats.available).c_str());
  472. }
  473. if (mask & heartbeat::Report::Loadavg)
  474. mqttSend(MQTT_TOPIC_LOADAVG, String(systemLoadAverage()).c_str());
  475. if ((mask & heartbeat::Report::Vcc) && (ADC_MODE_VALUE == ADC_VCC))
  476. mqttSend(MQTT_TOPIC_VCC, String(ESP.getVcc()).c_str());
  477. auto status = mqttConnected();
  478. for (auto& cb : _mqtt_heartbeat_callbacks) {
  479. status = status && cb(mask);
  480. }
  481. return status;
  482. }
  483. void _mqttOnConnect() {
  484. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  485. _mqtt_last_connection = millis();
  486. _mqtt_state = AsyncClientState::Connected;
  487. systemHeartbeat(_mqttHeartbeat, _mqtt_heartbeat_mode, _mqtt_heartbeat_interval);
  488. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  489. // Clean subscriptions
  490. mqttUnsubscribeRaw("#");
  491. // Notify all subscribers about the connection
  492. for (auto& callback : _mqtt_callbacks) {
  493. callback(MQTT_CONNECT_EVENT, nullptr, nullptr);
  494. }
  495. }
  496. void _mqttOnDisconnect() {
  497. // Reset reconnection delay
  498. _mqtt_last_connection = millis();
  499. _mqtt_state = AsyncClientState::Disconnected;
  500. systemStopHeartbeat(_mqttHeartbeat);
  501. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  502. // Notify all subscribers about the disconnect
  503. for (auto& callback : _mqtt_callbacks) {
  504. callback(MQTT_DISCONNECT_EVENT, nullptr, nullptr);
  505. }
  506. }
  507. // Force-skip everything received in a short window right after connecting to avoid syncronization issues.
  508. bool _mqttMaybeSkipRetained(char* topic) {
  509. if (_mqtt_skip_messages && (millis() - _mqtt_last_connection < _mqtt_skip_time)) {
  510. DEBUG_MSG_P(PSTR("[MQTT] Received %s - SKIPPED\n"), topic);
  511. return true;
  512. }
  513. _mqtt_skip_messages = false;
  514. return false;
  515. }
  516. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  517. // MQTT Broker can sometimes send messages in bulk. Even when message size is less than MQTT_BUFFER_MAX_SIZE, we *could*
  518. // receive a message with `len != total`, this requiring buffering of the received data. Prepare a static memory to store the
  519. // data until `(len + index) == total`.
  520. // TODO: One pending issue is streaming arbitrary data (e.g. binary, for OTA). We always set '\0' and API consumer expects C-String.
  521. // In that case, there could be MQTT_MESSAGE_RAW_EVENT and this callback only trigger on small messages.
  522. // TODO: Current callback model does not allow to pass message length. Instead, implement a topic filter and record all subscriptions. That way we don't need to filter out events and could implement per-event callbacks.
  523. void _mqttOnMessageAsync(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  524. if (!len || (len > MQTT_BUFFER_MAX_SIZE) || (total > MQTT_BUFFER_MAX_SIZE)) return;
  525. if (_mqttMaybeSkipRetained(topic)) return;
  526. static char message[((MQTT_BUFFER_MAX_SIZE + 1) + 31) & -32] = {0};
  527. memmove(message + index, (char *) payload, len);
  528. // Not done yet
  529. if (total != (len + index)) {
  530. DEBUG_MSG_P(PSTR("[MQTT] Buffered %s => %u / %u bytes\n"), topic, len, total);
  531. return;
  532. }
  533. message[len + index] = '\0';
  534. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  535. // Call subscribers with the message buffer
  536. for (auto& callback : _mqtt_callbacks) {
  537. callback(MQTT_MESSAGE_EVENT, topic, message);
  538. }
  539. }
  540. #else
  541. // Sync client already implements buffering, but we still need to add '\0' because API consumer expects C-String :/
  542. // TODO: consider reworking this (and async counterpart), giving callback func length of the message.
  543. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  544. if (!len || (len > MQTT_BUFFER_MAX_SIZE)) return;
  545. if (_mqttMaybeSkipRetained(topic)) return;
  546. static char message[((MQTT_BUFFER_MAX_SIZE + 1) + 31) & -32] = {0};
  547. memmove(message, (char *) payload, len);
  548. message[len] = '\0';
  549. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  550. // Call subscribers with the message buffer
  551. for (auto& callback : _mqtt_callbacks) {
  552. callback(MQTT_MESSAGE_EVENT, topic, message);
  553. }
  554. }
  555. #endif // MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  556. // -----------------------------------------------------------------------------
  557. // Public API
  558. // -----------------------------------------------------------------------------
  559. /**
  560. Returns the magnitude part of a topic
  561. @param topic the full MQTT topic
  562. @return String object with the magnitude part.
  563. */
  564. String mqttMagnitude(const char* topic) {
  565. String pattern = _mqtt_topic + _mqtt_setter;
  566. int position = pattern.indexOf("#");
  567. if (position == -1) return String();
  568. String start = pattern.substring(0, position);
  569. String end = pattern.substring(position + 1);
  570. String magnitude = String(topic);
  571. if (magnitude.startsWith(start) && magnitude.endsWith(end)) {
  572. magnitude.replace(start, "");
  573. magnitude.replace(end, "");
  574. } else {
  575. magnitude = String();
  576. }
  577. return magnitude;
  578. }
  579. /**
  580. Returns a full MQTT topic from the magnitude
  581. @param magnitude the magnitude part of the topic.
  582. @param is_set whether to build a command topic (true)
  583. or a state topic (false).
  584. @return String full MQTT topic.
  585. */
  586. String mqttTopic(const char * magnitude, bool is_set) {
  587. String output = _mqtt_topic;
  588. output.replace("#", magnitude);
  589. output += is_set ? _mqtt_setter : _mqtt_getter;
  590. return output;
  591. }
  592. /**
  593. Returns a full MQTT topic from the magnitude
  594. @param magnitude the magnitude part of the topic.
  595. @param index index of the magnitude when more than one such magnitudes.
  596. @param is_set whether to build a command topic (true)
  597. or a state topic (false).
  598. @return String full MQTT topic.
  599. */
  600. String mqttTopic(const char * magnitude, unsigned int index, bool is_set) {
  601. char buffer[strlen(magnitude)+5];
  602. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), magnitude, index);
  603. return mqttTopic(buffer, is_set);
  604. }
  605. // -----------------------------------------------------------------------------
  606. bool mqttSendRaw(const char * topic, const char * message, bool retain) {
  607. constexpr size_t MessageLogMax { 128ul };
  608. if (_mqtt.connected()) {
  609. const unsigned int packetId {
  610. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  611. _mqtt.publish(topic, _mqtt_qos, retain, message)
  612. #elif MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  613. _mqtt.publish(topic, message, retain, _mqtt_qos)
  614. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  615. _mqtt.publish(topic, message, retain)
  616. #endif
  617. };
  618. const size_t message_len = strlen(message);
  619. if (message_len > MessageLogMax) {
  620. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => (%u bytes) (PID %u)\n"), topic, message_len, packetId);
  621. } else {
  622. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %u)\n"), topic, message, packetId);
  623. }
  624. return (packetId > 0);
  625. }
  626. return false;
  627. }
  628. bool mqttSendRaw(const char * topic, const char * message) {
  629. return mqttSendRaw(topic, message, _mqtt_retain);
  630. }
  631. void mqttSend(const char * topic, const char * message, bool force, bool retain) {
  632. if (!force && _mqtt_use_json) {
  633. mqttEnqueue(topic, message);
  634. _mqtt_flush_ticker.once_ms(MQTT_USE_JSON_DELAY, mqttFlush);
  635. return;
  636. }
  637. mqttSendRaw(mqttTopic(topic, false).c_str(), message, retain);
  638. }
  639. void mqttSend(const char * topic, const char * message, bool force) {
  640. mqttSend(topic, message, force, _mqtt_retain);
  641. }
  642. void mqttSend(const char * topic, const char * message) {
  643. mqttSend(topic, message, false);
  644. }
  645. void mqttSend(const char * topic, unsigned int index, const char * message, bool force, bool retain) {
  646. char buffer[strlen(topic)+5];
  647. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  648. mqttSend(buffer, message, force, retain);
  649. }
  650. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  651. mqttSend(topic, index, message, force, _mqtt_retain);
  652. }
  653. void mqttSend(const char * topic, unsigned int index, const char * message) {
  654. mqttSend(topic, index, message, false);
  655. }
  656. // -----------------------------------------------------------------------------
  657. constexpr size_t MqttJsonPayloadBufferSize { 1024ul };
  658. void mqttFlush() {
  659. if (!_mqtt.connected()) {
  660. return;
  661. }
  662. if (_mqtt_queue.empty()) {
  663. return;
  664. }
  665. DynamicJsonBuffer jsonBuffer(MqttJsonPayloadBufferSize);
  666. JsonObject& root = jsonBuffer.createObject();
  667. #if NTP_SUPPORT && MQTT_ENQUEUE_DATETIME
  668. if (ntpSynced()) {
  669. root[MQTT_TOPIC_DATETIME] = ntpDateTime();
  670. }
  671. #endif
  672. #if MQTT_ENQUEUE_MAC
  673. root[MQTT_TOPIC_MAC] = WiFi.macAddress();
  674. #endif
  675. #if MQTT_ENQUEUE_HOSTNAME
  676. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname", getIdentifier());
  677. #endif
  678. #if MQTT_ENQUEUE_IP
  679. root[MQTT_TOPIC_IP] = getIP();
  680. #endif
  681. #if MQTT_ENQUEUE_MESSAGE_ID
  682. root[MQTT_TOPIC_MESSAGE_ID] = (Rtcmem->mqtt)++;
  683. #endif
  684. for (auto& element : _mqtt_queue) {
  685. root[element.topic.c_str()] = element.message.c_str();
  686. }
  687. String output;
  688. root.printTo(output);
  689. jsonBuffer.clear();
  690. _mqtt_queue.clear();
  691. _mqtt_queue_count = 0;
  692. mqttSendRaw(_mqtt_topic_json.c_str(), output.c_str(), false);
  693. }
  694. void mqttEnqueue(const char * topic, const char * message) {
  695. // Queue is not meant to send message "offline"
  696. // We must prevent the queue does not get full while offline
  697. if (_mqtt.connected()) {
  698. if (_mqtt_queue_count >= MQTT_QUEUE_MAX_SIZE) {
  699. mqttFlush();
  700. }
  701. ++_mqtt_queue_count;
  702. _mqtt_queue.push_front({
  703. topic, message
  704. });
  705. }
  706. }
  707. // -----------------------------------------------------------------------------
  708. void mqttSubscribeRaw(const char * topic) {
  709. if (_mqtt.connected() && (strlen(topic) > 0)) {
  710. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  711. unsigned int packetId = _mqtt.subscribe(topic, _mqtt_qos);
  712. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  713. #else // Arduino-MQTT or PubSubClient
  714. _mqtt.subscribe(topic, _mqtt_qos);
  715. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  716. #endif
  717. }
  718. }
  719. void mqttSubscribe(const char * topic) {
  720. mqttSubscribeRaw(mqttTopic(topic, true).c_str());
  721. }
  722. void mqttUnsubscribeRaw(const char * topic) {
  723. if (_mqtt.connected() && (strlen(topic) > 0)) {
  724. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  725. unsigned int packetId = _mqtt.unsubscribe(topic);
  726. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  727. #else // Arduino-MQTT or PubSubClient
  728. _mqtt.unsubscribe(topic);
  729. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  730. #endif
  731. }
  732. }
  733. void mqttUnsubscribe(const char * topic) {
  734. mqttUnsubscribeRaw(mqttTopic(topic, true).c_str());
  735. }
  736. // -----------------------------------------------------------------------------
  737. void mqttEnabled(bool status) {
  738. _mqtt_enabled = status;
  739. }
  740. bool mqttEnabled() {
  741. return _mqtt_enabled;
  742. }
  743. bool mqttConnected() {
  744. return _mqtt.connected();
  745. }
  746. void mqttDisconnect() {
  747. if (_mqtt.connected()) {
  748. DEBUG_MSG_P(PSTR("[MQTT] Disconnecting\n"));
  749. _mqtt.disconnect();
  750. }
  751. }
  752. bool mqttForward() {
  753. return _mqtt_forward;
  754. }
  755. void mqttRegister(mqtt_callback_f callback) {
  756. _mqtt_callbacks.push_front(callback);
  757. }
  758. void mqttSetBroker(IPAddress ip, uint16_t port) {
  759. setSetting("mqttServer", ip.toString());
  760. _mqtt_server = ip.toString();
  761. setSetting("mqttPort", port);
  762. _mqtt_port = port;
  763. mqttEnabled(1 == MQTT_AUTOCONNECT);
  764. }
  765. void mqttSetBrokerIfNone(IPAddress ip, uint16_t port) {
  766. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  767. mqttSetBroker(ip, port);
  768. }
  769. }
  770. const String& mqttPayloadOnline() {
  771. return _mqtt_payload_online;
  772. }
  773. const String& mqttPayloadOffline() {
  774. return _mqtt_payload_offline;
  775. }
  776. const char* mqttPayloadStatus(bool status) {
  777. return status ? _mqtt_payload_online.c_str() : _mqtt_payload_offline.c_str();
  778. }
  779. void mqttSendStatus() {
  780. mqttSend(MQTT_TOPIC_STATUS, _mqtt_payload_online.c_str(), true);
  781. }
  782. // -----------------------------------------------------------------------------
  783. // Initialization
  784. // -----------------------------------------------------------------------------
  785. void _mqttConnect() {
  786. // Do not connect if disabled
  787. if (!_mqtt_enabled) return;
  788. // Do not connect if already connected or still trying to connect
  789. if (_mqtt.connected() || (_mqtt_state != AsyncClientState::Disconnected)) return;
  790. // Check reconnect interval
  791. if (millis() - _mqtt_last_connection < _mqtt_reconnect_delay) return;
  792. // Increase the reconnect delay
  793. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  794. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  795. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  796. }
  797. #if MDNS_CLIENT_SUPPORT
  798. _mqtt_server = mdnsResolve(_mqtt_server);
  799. #endif
  800. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%hu\n"), _mqtt_server.c_str(), _mqtt_port);
  801. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid.c_str());
  802. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  803. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %c\n"), _mqtt_retain ? 'Y' : 'N');
  804. DEBUG_MSG_P(PSTR("[MQTT] Keepalive time: %hu (s)\n"), _mqtt_keepalive);
  805. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will.c_str());
  806. _mqtt_state = AsyncClientState::Connecting;
  807. _mqtt_skip_messages = (_mqtt_skip_time > 0);
  808. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  809. const bool secure = getSetting("mqttUseSSL", 1 == MQTT_SSL_ENABLED);
  810. #else
  811. const bool secure = false;
  812. #endif
  813. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  814. _mqttSetupAsyncClient(secure);
  815. #elif (MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT) || (MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT)
  816. if (_mqttSetupSyncClient(secure) && _mqttConnectSyncClient(secure)) {
  817. _mqttOnConnect();
  818. } else {
  819. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  820. _mqttOnDisconnect();
  821. }
  822. #else
  823. #error "please check that MQTT_LIBRARY is valid"
  824. #endif
  825. }
  826. void mqttLoop() {
  827. if (WiFi.status() != WL_CONNECTED) return;
  828. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  829. _mqttConnect();
  830. #else // MQTT_LIBRARY != MQTT_LIBRARY_ASYNCMQTTCLIENT
  831. if (_mqtt.connected()) {
  832. _mqtt.loop();
  833. } else {
  834. if (_mqtt_state != AsyncClientState::Disconnected) {
  835. _mqttOnDisconnect();
  836. }
  837. _mqttConnect();
  838. }
  839. #endif // MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  840. }
  841. void mqttHeartbeat(heartbeat::Callback callback) {
  842. _mqtt_heartbeat_callbacks.push_front(callback);
  843. }
  844. void mqttSetup() {
  845. _mqttBackwards();
  846. _mqttInfo();
  847. #if MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  848. // XXX: should not place this in config, addServerFingerprint does not check for duplicates
  849. #if SECURE_CLIENT != SECURE_CLIENT_NONE
  850. {
  851. if (_mqtt_sc_config.on_fingerprint) {
  852. const String fingerprint = _mqtt_sc_config.on_fingerprint();
  853. uint8_t buffer[20] = {0};
  854. if (sslFingerPrintArray(fingerprint.c_str(), buffer)) {
  855. _mqtt.addServerFingerprint(buffer);
  856. }
  857. }
  858. }
  859. #endif // SECURE_CLIENT != SECURE_CLIENT_NONE
  860. _mqtt.onMessage(_mqttOnMessageAsync);
  861. _mqtt.onConnect([](bool) {
  862. _mqttOnConnect();
  863. });
  864. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  865. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %u\n"), packetId);
  866. });
  867. _mqtt.onPublish([](uint16_t packetId) {
  868. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %u\n"), packetId);
  869. });
  870. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  871. switch (reason) {
  872. case AsyncMqttClientDisconnectReason::TCP_DISCONNECTED:
  873. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  874. break;
  875. case AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED:
  876. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  877. break;
  878. case AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE:
  879. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  880. break;
  881. case AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS:
  882. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  883. break;
  884. case AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED:
  885. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  886. break;
  887. case AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT:
  888. #if ASYNC_TCP_SSL_ENABLED
  889. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  890. #endif
  891. break;
  892. case AsyncMqttClientDisconnectReason::MQTT_UNACCEPTABLE_PROTOCOL_VERSION:
  893. // This is never used by the AsyncMqttClient source
  894. #if 0
  895. DEBUG_MSG_P(PSTR("[MQTT] Unacceptable protocol version\n"));
  896. #endif
  897. break;
  898. case AsyncMqttClientDisconnectReason::ESP8266_NOT_ENOUGH_SPACE:
  899. DEBUG_MSG_P(PSTR("[MQTT] Connect packet too big\n"));
  900. break;
  901. }
  902. _mqttOnDisconnect();
  903. });
  904. #elif MQTT_LIBRARY == MQTT_LIBRARY_ARDUINOMQTT
  905. _mqtt.onMessageAdvanced([](MQTTClient *client, char topic[], char payload[], int length) {
  906. _mqttOnMessage(topic, payload, length);
  907. });
  908. #elif MQTT_LIBRARY == MQTT_LIBRARY_PUBSUBCLIENT
  909. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  910. _mqttOnMessage(topic, (char *) payload, length);
  911. });
  912. #endif // MQTT_LIBRARY == MQTT_LIBRARY_ASYNCMQTTCLIENT
  913. _mqttConfigure();
  914. mqttRegister(_mqttCallback);
  915. #if WEB_SUPPORT
  916. wsRegister()
  917. .onVisible(_mqttWebSocketOnVisible)
  918. .onData(_mqttWebSocketOnData)
  919. .onConnected(_mqttWebSocketOnConnected)
  920. .onKeyCheck(_mqttWebSocketOnKeyCheck);
  921. mqttRegister([](unsigned int type, const char*, const char*) {
  922. if ((type == MQTT_CONNECT_EVENT) || (type == MQTT_DISCONNECT_EVENT)) {
  923. wsPost(_mqttWebSocketOnData);
  924. }
  925. });
  926. #endif
  927. #if TERMINAL_SUPPORT
  928. _mqttInitCommands();
  929. #endif
  930. // Main callbacks
  931. espurnaRegisterLoop(mqttLoop);
  932. espurnaRegisterReload(_mqttConfigure);
  933. }
  934. #endif // MQTT_SUPPORT