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.

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