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.

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