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.

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