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.

875 lines
25 KiB

8 years ago
8 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. MQTT MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if MQTT_SUPPORT
  6. #include <EEPROM_Rotate.h>
  7. #include <ESP8266WiFi.h>
  8. #include <ESP8266mDNS.h>
  9. #include <ArduinoJson.h>
  10. #include <vector>
  11. #include <utility>
  12. #include <Ticker.h>
  13. #if MQTT_USE_ASYNC // Using AsyncMqttClient
  14. #include <AsyncMqttClient.h>
  15. AsyncMqttClient _mqtt;
  16. #else // Using PubSubClient
  17. #include <PubSubClient.h>
  18. PubSubClient _mqtt;
  19. bool _mqtt_connected = false;
  20. WiFiClient _mqtt_client;
  21. #if ASYNC_TCP_SSL_ENABLED
  22. WiFiClientSecure _mqtt_client_secure;
  23. #endif // ASYNC_TCP_SSL_ENABLED
  24. #endif // MQTT_USE_ASYNC
  25. bool _mqtt_enabled = MQTT_ENABLED;
  26. bool _mqtt_use_json = false;
  27. unsigned long _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  28. unsigned long _mqtt_last_connection = 0;
  29. bool _mqtt_connecting = false;
  30. unsigned char _mqtt_qos = MQTT_QOS;
  31. bool _mqtt_retain = MQTT_RETAIN;
  32. unsigned long _mqtt_keepalive = MQTT_KEEPALIVE;
  33. String _mqtt_topic;
  34. String _mqtt_topic_json;
  35. String _mqtt_setter;
  36. String _mqtt_getter;
  37. bool _mqtt_forward;
  38. String _mqtt_user;
  39. String _mqtt_pass;
  40. String _mqtt_will;
  41. String _mqtt_server;
  42. uint16_t _mqtt_port;
  43. String _mqtt_clientid;
  44. std::vector<mqtt_callback_f> _mqtt_callbacks;
  45. typedef struct {
  46. unsigned char parent = 255;
  47. char * topic;
  48. char * message = NULL;
  49. } mqtt_message_t;
  50. std::vector<mqtt_message_t> _mqtt_queue;
  51. Ticker _mqtt_flush_ticker;
  52. // -----------------------------------------------------------------------------
  53. // Private
  54. // -----------------------------------------------------------------------------
  55. void _mqttConnect() {
  56. // Do not connect if disabled
  57. if (!_mqtt_enabled) return;
  58. // Do not connect if already connected or still trying to connect
  59. if (_mqtt.connected() || _mqtt_connecting) return;
  60. // Check reconnect interval
  61. if (millis() - _mqtt_last_connection < _mqtt_reconnect_delay) return;
  62. // Increase the reconnect delay
  63. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  64. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  65. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  66. }
  67. #if MDNS_CLIENT_SUPPORT
  68. _mqtt_server = mdnsResolve(_mqtt_server);
  69. #endif
  70. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%u\n"), _mqtt_server.c_str(), _mqtt_port);
  71. #if MQTT_USE_ASYNC
  72. _mqtt_connecting = true;
  73. _mqtt.setServer(_mqtt_server.c_str(), _mqtt_port);
  74. _mqtt.setClientId(_mqtt_clientid.c_str());
  75. _mqtt.setKeepAlive(_mqtt_keepalive);
  76. _mqtt.setCleanSession(false);
  77. _mqtt.setWill(_mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, "0");
  78. if (_mqtt_user.length() && _mqtt_pass.length()) {
  79. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user.c_str());
  80. _mqtt.setCredentials(_mqtt_user.c_str(), _mqtt_pass.c_str());
  81. }
  82. #if ASYNC_TCP_SSL_ENABLED
  83. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  84. _mqtt.setSecure(secure);
  85. if (secure) {
  86. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  87. unsigned char fp[20] = {0};
  88. if (sslFingerPrintArray(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  89. _mqtt.addServerFingerprint(fp);
  90. } else {
  91. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  92. }
  93. }
  94. #endif // ASYNC_TCP_SSL_ENABLED
  95. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid.c_str());
  96. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  97. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  98. DEBUG_MSG_P(PSTR("[MQTT] Keepalive time: %ds\n"), _mqtt_keepalive);
  99. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will.c_str());
  100. _mqtt.connect();
  101. #else // not MQTT_USE_ASYNC
  102. bool response = true;
  103. #if ASYNC_TCP_SSL_ENABLED
  104. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  105. if (secure) {
  106. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  107. if (_mqtt_client_secure.connect(_mqtt_server.c_str(), _mqtt_port)) {
  108. char fp[60] = {0};
  109. if (sslFingerPrintChar(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  110. if (_mqtt_client_secure.verify(fp, _mqtt_server.c_str())) {
  111. _mqtt.setClient(_mqtt_client_secure);
  112. } else {
  113. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  114. response = false;
  115. }
  116. _mqtt_client_secure.stop();
  117. yield();
  118. } else {
  119. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  120. response = false;
  121. }
  122. } else {
  123. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  124. response = false;
  125. }
  126. } else {
  127. _mqtt.setClient(_mqtt_client);
  128. }
  129. #else // not ASYNC_TCP_SSL_ENABLED
  130. _mqtt.setClient(_mqtt_client);
  131. #endif // ASYNC_TCP_SSL_ENABLED
  132. if (response) {
  133. _mqtt.setServer(_mqtt_server.c_str(), _mqtt_port);
  134. if (_mqtt_user.length() && _mqtt_pass.length()) {
  135. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user.c_str());
  136. response = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_user.c_str(), _mqtt_pass.c_str(), _mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, "0");
  137. } else {
  138. response = _mqtt.connect(_mqtt_clientid.c_str(), _mqtt_will.c_str(), _mqtt_qos, _mqtt_retain, "0");
  139. }
  140. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid.c_str());
  141. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  142. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  143. DEBUG_MSG_P(PSTR("[MQTT] Keepalive time: %ds\n"), _mqtt_keepalive);
  144. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will.c_str());
  145. }
  146. if (response) {
  147. _mqttOnConnect();
  148. } else {
  149. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  150. _mqtt_last_connection = millis();
  151. }
  152. #endif // MQTT_USE_ASYNC
  153. }
  154. void _mqttPlaceholders(String& text) {
  155. text.replace("{hostname}", getSetting("hostname"));
  156. text.replace("{magnitude}", "#");
  157. String mac = WiFi.macAddress();
  158. mac.replace(":", "");
  159. text.replace("{mac}", mac);
  160. }
  161. template<typename T>
  162. void _mqttApplySetting(T& current, T& updated) {
  163. if (current != updated) {
  164. current = std::move(updated);
  165. mqttDisconnect();
  166. }
  167. }
  168. template<typename T>
  169. void _mqttApplySetting(T& current, const T& updated) {
  170. if (current != updated) {
  171. current = updated;
  172. mqttDisconnect();
  173. }
  174. }
  175. template<typename T>
  176. void _mqttApplyTopic(T& current, const char* magnitude) {
  177. String updated = mqttTopic(magnitude, false);
  178. if (current != updated) {
  179. mqttFlush();
  180. current = std::move(updated);
  181. }
  182. }
  183. void _mqttConfigure() {
  184. // Enable only when server is set
  185. {
  186. String server = getSetting("mqttServer", MQTT_SERVER);
  187. uint16_t port = getSetting("mqttPort", MQTT_PORT).toInt();
  188. bool enabled = false;
  189. if (server.length()) {
  190. enabled = getSetting("mqttEnabled", MQTT_ENABLED).toInt() == 1;
  191. }
  192. _mqttApplySetting(_mqtt_server, server);
  193. _mqttApplySetting(_mqtt_enabled, enabled);
  194. _mqttApplySetting(_mqtt_port, port);
  195. if (!enabled) return;
  196. }
  197. // Get base topic and apply placeholders
  198. {
  199. String topic = getSetting("mqttTopic", MQTT_TOPIC);
  200. if (topic.endsWith("/")) topic.remove(_mqtt_topic.length()-1);
  201. // Replace things inside curly braces (like {hostname}, {mac} etc.)
  202. _mqttPlaceholders(topic);
  203. if (topic.indexOf("#") == -1) topic.concat("/#");
  204. _mqttApplySetting(_mqtt_topic, topic);
  205. _mqttApplyTopic(_mqtt_will, MQTT_TOPIC_STATUS);
  206. }
  207. // Getter and setter
  208. {
  209. String setter = getSetting("mqttSetter", MQTT_SETTER);
  210. String getter = getSetting("mqttGetter", MQTT_GETTER);
  211. bool forward = !setter.equals(getter) && RELAY_REPORT_STATUS;
  212. _mqttApplySetting(_mqtt_setter, setter);
  213. _mqttApplySetting(_mqtt_getter, getter);
  214. _mqttApplySetting(_mqtt_forward, forward);
  215. }
  216. // MQTT options
  217. {
  218. String user = getSetting("mqttUser", MQTT_USER);
  219. _mqttPlaceholders(user);
  220. String pass = getSetting("mqttPassword", MQTT_PASS);
  221. unsigned char qos = getSetting("mqttQoS", MQTT_QOS).toInt();
  222. bool retain = getSetting("mqttRetain", MQTT_RETAIN).toInt() == 1;
  223. unsigned long keepalive = getSetting("mqttKeep", MQTT_KEEPALIVE).toInt();
  224. String id = getSetting("mqttClientID", getIdentifier());
  225. _mqttPlaceholders(id);
  226. _mqttApplySetting(_mqtt_user, user);
  227. _mqttApplySetting(_mqtt_pass, pass);
  228. _mqttApplySetting(_mqtt_qos, qos);
  229. _mqttApplySetting(_mqtt_retain, retain);
  230. _mqttApplySetting(_mqtt_keepalive, keepalive);
  231. _mqttApplySetting(_mqtt_clientid, id);
  232. }
  233. // MQTT JSON
  234. {
  235. _mqttApplySetting(_mqtt_use_json, getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1);
  236. _mqttApplyTopic(_mqtt_topic_json, MQTT_TOPIC_JSON);
  237. }
  238. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  239. }
  240. void _mqttBackwards() {
  241. String mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  242. if (mqttTopic.indexOf("{identifier}") > 0) {
  243. mqttTopic.replace("{identifier}", "{hostname}");
  244. setSetting("mqttTopic", mqttTopic);
  245. }
  246. }
  247. // -----------------------------------------------------------------------------
  248. // WEB
  249. // -----------------------------------------------------------------------------
  250. #if WEB_SUPPORT
  251. bool _mqttWebSocketOnReceive(const char * key, JsonVariant& value) {
  252. return (strncmp(key, "mqtt", 3) == 0);
  253. }
  254. void _mqttWebSocketOnSend(JsonObject& root) {
  255. root["mqttVisible"] = 1;
  256. root["mqttStatus"] = mqttConnected();
  257. root["mqttEnabled"] = mqttEnabled();
  258. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  259. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  260. root["mqttUser"] = getSetting("mqttUser", MQTT_USER);
  261. root["mqttClientID"] = getSetting("mqttClientID");
  262. root["mqttPassword"] = getSetting("mqttPassword", MQTT_PASS);
  263. root["mqttKeep"] = _mqtt_keepalive;
  264. root["mqttRetain"] = _mqtt_retain;
  265. root["mqttQoS"] = _mqtt_qos;
  266. #if ASYNC_TCP_SSL_ENABLED
  267. root["mqttsslVisible"] = 1;
  268. root["mqttUseSSL"] = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  269. root["mqttFP"] = getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  270. #endif
  271. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  272. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  273. }
  274. #endif
  275. // -----------------------------------------------------------------------------
  276. // SETTINGS
  277. // -----------------------------------------------------------------------------
  278. #if TERMINAL_SUPPORT
  279. void _mqttInitCommands() {
  280. terminalRegisterCommand(F("MQTT.RESET"), [](Embedis* e) {
  281. _mqttConfigure();
  282. mqttDisconnect();
  283. terminalOK();
  284. });
  285. }
  286. #endif // TERMINAL_SUPPORT
  287. // -----------------------------------------------------------------------------
  288. // MQTT Callbacks
  289. // -----------------------------------------------------------------------------
  290. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  291. if (type == MQTT_CONNECT_EVENT) {
  292. // Subscribe to internal action topics
  293. mqttSubscribe(MQTT_TOPIC_ACTION);
  294. // Flag system to send heartbeat
  295. systemSendHeartbeat();
  296. }
  297. if (type == MQTT_MESSAGE_EVENT) {
  298. // Match topic
  299. String t = mqttMagnitude((char *) topic);
  300. // Actions
  301. if (t.equals(MQTT_TOPIC_ACTION)) {
  302. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  303. deferredReset(100, CUSTOM_RESET_MQTT);
  304. }
  305. }
  306. }
  307. }
  308. void _mqttOnConnect() {
  309. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  310. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  311. _mqtt_last_connection = millis();
  312. // Clean subscriptions
  313. mqttUnsubscribeRaw("#");
  314. // Send connect event to subscribers
  315. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  316. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  317. }
  318. }
  319. void _mqttOnDisconnect() {
  320. // Reset reconnection delay
  321. _mqtt_last_connection = millis();
  322. _mqtt_connecting = false;
  323. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  324. // Send disconnect event to subscribers
  325. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  326. (_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  327. }
  328. }
  329. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  330. if (len == 0) return;
  331. char message[len + 1];
  332. strlcpy(message, (char *) payload, len + 1);
  333. #if MQTT_SKIP_RETAINED
  334. if (millis() - _mqtt_last_connection < MQTT_SKIP_TIME) {
  335. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  336. return;
  337. }
  338. #endif
  339. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  340. // Send message event to subscribers
  341. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  342. (_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  343. }
  344. }
  345. // -----------------------------------------------------------------------------
  346. // Public API
  347. // -----------------------------------------------------------------------------
  348. /**
  349. Returns the magnitude part of a topic
  350. @param topic the full MQTT topic
  351. @return String object with the magnitude part.
  352. */
  353. String mqttMagnitude(char * topic) {
  354. String pattern = _mqtt_topic + _mqtt_setter;
  355. int position = pattern.indexOf("#");
  356. if (position == -1) return String();
  357. String start = pattern.substring(0, position);
  358. String end = pattern.substring(position + 1);
  359. String magnitude = String(topic);
  360. if (magnitude.startsWith(start) && magnitude.endsWith(end)) {
  361. magnitude.replace(start, "");
  362. magnitude.replace(end, "");
  363. } else {
  364. magnitude = String();
  365. }
  366. return magnitude;
  367. }
  368. /**
  369. Returns a full MQTT topic from the magnitude
  370. @param magnitude the magnitude part of the topic.
  371. @param is_set whether to build a command topic (true)
  372. or a state topic (false).
  373. @return String full MQTT topic.
  374. */
  375. String mqttTopic(const char * magnitude, bool is_set) {
  376. String output = _mqtt_topic;
  377. output.replace("#", magnitude);
  378. output += is_set ? _mqtt_setter : _mqtt_getter;
  379. return output;
  380. }
  381. /**
  382. Returns a full MQTT topic from the magnitude
  383. @param magnitude the magnitude part of the topic.
  384. @param index index of the magnitude when more than one such magnitudes.
  385. @param is_set whether to build a command topic (true)
  386. or a state topic (false).
  387. @return String full MQTT topic.
  388. */
  389. String mqttTopic(const char * magnitude, unsigned int index, bool is_set) {
  390. char buffer[strlen(magnitude)+5];
  391. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), magnitude, index);
  392. return mqttTopic(buffer, is_set);
  393. }
  394. // -----------------------------------------------------------------------------
  395. void mqttSendRaw(const char * topic, const char * message, bool retain) {
  396. if (_mqtt.connected()) {
  397. #if MQTT_USE_ASYNC
  398. unsigned int packetId = _mqtt.publish(topic, _mqtt_qos, retain, message);
  399. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %d)\n"), topic, message, packetId);
  400. #else
  401. _mqtt.publish(topic, message, retain);
  402. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  403. #endif
  404. }
  405. }
  406. void mqttSendRaw(const char * topic, const char * message) {
  407. mqttSendRaw (topic, message, _mqtt_retain);
  408. }
  409. void mqttSend(const char * topic, const char * message, bool force, bool retain) {
  410. bool useJson = force ? false : _mqtt_use_json;
  411. // Equeue message
  412. if (useJson) {
  413. // Enqueue new message
  414. mqttEnqueue(topic, message);
  415. // Reset flush timer
  416. _mqtt_flush_ticker.once_ms(MQTT_USE_JSON_DELAY, mqttFlush);
  417. // Send it right away
  418. } else {
  419. mqttSendRaw(mqttTopic(topic, false).c_str(), message, retain);
  420. }
  421. }
  422. void mqttSend(const char * topic, const char * message, bool force) {
  423. mqttSend(topic, message, force, _mqtt_retain);
  424. }
  425. void mqttSend(const char * topic, const char * message) {
  426. mqttSend(topic, message, false);
  427. }
  428. void mqttSend(const char * topic, unsigned int index, const char * message, bool force, bool retain) {
  429. char buffer[strlen(topic)+5];
  430. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  431. mqttSend(buffer, message, force, retain);
  432. }
  433. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  434. mqttSend(topic, index, message, force, _mqtt_retain);
  435. }
  436. void mqttSend(const char * topic, unsigned int index, const char * message) {
  437. mqttSend(topic, index, message, false);
  438. }
  439. // -----------------------------------------------------------------------------
  440. unsigned char _mqttBuildTree(JsonObject& root, char parent) {
  441. unsigned char count = 0;
  442. // Add enqueued messages
  443. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  444. mqtt_message_t element = _mqtt_queue[i];
  445. if (element.parent == parent) {
  446. ++count;
  447. JsonObject& elements = root.createNestedObject(element.topic);
  448. unsigned char num = _mqttBuildTree(elements, i);
  449. if (0 == num) {
  450. if (isNumber(element.message)) {
  451. double value = atof(element.message);
  452. if (value == int(value)) {
  453. root.set(element.topic, int(value));
  454. } else {
  455. root.set(element.topic, value);
  456. }
  457. } else {
  458. root.set(element.topic, element.message);
  459. }
  460. }
  461. }
  462. }
  463. return count;
  464. }
  465. void mqttFlush() {
  466. if (!_mqtt.connected()) return;
  467. if (_mqtt_queue.size() == 0) return;
  468. // Build tree recursively
  469. DynamicJsonBuffer jsonBuffer;
  470. JsonObject& root = jsonBuffer.createObject();
  471. _mqttBuildTree(root, 255);
  472. // Add extra propeties
  473. #if NTP_SUPPORT && MQTT_ENQUEUE_DATETIME
  474. if (ntpSynced()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  475. #endif
  476. #if MQTT_ENQUEUE_MAC
  477. root[MQTT_TOPIC_MAC] = WiFi.macAddress();
  478. #endif
  479. #if MQTT_ENQUEUE_HOSTNAME
  480. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  481. #endif
  482. #if MQTT_ENQUEUE_IP
  483. root[MQTT_TOPIC_IP] = getIP();
  484. #endif
  485. #if MQTT_ENQUEUE_MESSAGE_ID
  486. root[MQTT_TOPIC_MESSAGE_ID] = (Rtcmem->mqtt)++;
  487. #endif
  488. // Send
  489. String output;
  490. root.printTo(output);
  491. jsonBuffer.clear();
  492. mqttSendRaw(_mqtt_topic_json.c_str(), output.c_str(), false);
  493. // Clear queue
  494. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  495. mqtt_message_t element = _mqtt_queue[i];
  496. free(element.topic);
  497. if (element.message) {
  498. free(element.message);
  499. }
  500. }
  501. _mqtt_queue.clear();
  502. }
  503. int8_t mqttEnqueue(const char * topic, const char * message, unsigned char parent) {
  504. // Queue is not meant to send message "offline"
  505. // We must prevent the queue does not get full while offline
  506. if (!_mqtt.connected()) return -1;
  507. // Force flusing the queue if the MQTT_QUEUE_MAX_SIZE has been reached
  508. if (_mqtt_queue.size() >= MQTT_QUEUE_MAX_SIZE) mqttFlush();
  509. int8_t index = _mqtt_queue.size();
  510. // Enqueue new message
  511. mqtt_message_t element;
  512. element.parent = parent;
  513. element.topic = strdup(topic);
  514. if (NULL != message) {
  515. element.message = strdup(message);
  516. }
  517. _mqtt_queue.push_back(element);
  518. return index;
  519. }
  520. int8_t mqttEnqueue(const char * topic, const char * message) {
  521. return mqttEnqueue(topic, message, 255);
  522. }
  523. // -----------------------------------------------------------------------------
  524. void mqttSubscribeRaw(const char * topic) {
  525. if (_mqtt.connected() && (strlen(topic) > 0)) {
  526. #if MQTT_USE_ASYNC
  527. unsigned int packetId = _mqtt.subscribe(topic, _mqtt_qos);
  528. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  529. #else
  530. _mqtt.subscribe(topic, _mqtt_qos);
  531. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  532. #endif
  533. }
  534. }
  535. void mqttSubscribe(const char * topic) {
  536. mqttSubscribeRaw(mqttTopic(topic, true).c_str());
  537. }
  538. void mqttUnsubscribeRaw(const char * topic) {
  539. if (_mqtt.connected() && (strlen(topic) > 0)) {
  540. #if MQTT_USE_ASYNC
  541. unsigned int packetId = _mqtt.unsubscribe(topic);
  542. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  543. #else
  544. _mqtt.unsubscribe(topic);
  545. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  546. #endif
  547. }
  548. }
  549. void mqttUnsubscribe(const char * topic) {
  550. mqttUnsubscribeRaw(mqttTopic(topic, true).c_str());
  551. }
  552. // -----------------------------------------------------------------------------
  553. void mqttEnabled(bool status) {
  554. _mqtt_enabled = status;
  555. }
  556. bool mqttEnabled() {
  557. return _mqtt_enabled;
  558. }
  559. bool mqttConnected() {
  560. return _mqtt.connected();
  561. }
  562. void mqttDisconnect() {
  563. if (_mqtt.connected()) {
  564. DEBUG_MSG_P(PSTR("[MQTT] Disconnecting\n"));
  565. _mqtt.disconnect();
  566. }
  567. }
  568. bool mqttForward() {
  569. return _mqtt_forward;
  570. }
  571. void mqttRegister(mqtt_callback_f callback) {
  572. _mqtt_callbacks.push_back(callback);
  573. }
  574. void mqttSetBroker(IPAddress ip, unsigned int port) {
  575. setSetting("mqttServer", ip.toString());
  576. _mqtt_server = ip.toString();
  577. setSetting("mqttPort", port);
  578. _mqtt_port = port;
  579. mqttEnabled(MQTT_AUTOCONNECT);
  580. }
  581. void mqttSetBrokerIfNone(IPAddress ip, unsigned int port) {
  582. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) mqttSetBroker(ip, port);
  583. }
  584. // -----------------------------------------------------------------------------
  585. // Initialization
  586. // -----------------------------------------------------------------------------
  587. void mqttSetup() {
  588. _mqttBackwards();
  589. DEBUG_MSG_P(PSTR("[MQTT] Async %s, SSL %s, Autoconnect %s\n"),
  590. MQTT_USE_ASYNC ? "ENABLED" : "DISABLED",
  591. ASYNC_TCP_SSL_ENABLED ? "ENABLED" : "DISABLED",
  592. MQTT_AUTOCONNECT ? "ENABLED" : "DISABLED"
  593. );
  594. #if MQTT_USE_ASYNC
  595. _mqtt.onConnect([](bool sessionPresent) {
  596. _mqttOnConnect();
  597. });
  598. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  599. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  600. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  601. }
  602. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  603. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  604. }
  605. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  606. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  607. }
  608. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  609. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  610. }
  611. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  612. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  613. }
  614. #if ASYNC_TCP_SSL_ENABLED
  615. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  616. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  617. }
  618. #endif
  619. _mqttOnDisconnect();
  620. });
  621. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  622. _mqttOnMessage(topic, payload, len);
  623. });
  624. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  625. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  626. });
  627. _mqtt.onPublish([](uint16_t packetId) {
  628. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  629. });
  630. #else // not MQTT_USE_ASYNC
  631. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  632. _mqttOnMessage(topic, (char *) payload, length);
  633. });
  634. #endif // MQTT_USE_ASYNC
  635. _mqttConfigure();
  636. mqttRegister(_mqttCallback);
  637. #if WEB_SUPPORT
  638. wsOnSendRegister(_mqttWebSocketOnSend);
  639. wsOnReceiveRegister(_mqttWebSocketOnReceive);
  640. #endif
  641. #if TERMINAL_SUPPORT
  642. _mqttInitCommands();
  643. #endif
  644. // Main callbacks
  645. espurnaRegisterLoop(mqttLoop);
  646. espurnaRegisterReload(_mqttConfigure);
  647. }
  648. void mqttLoop() {
  649. if (WiFi.status() != WL_CONNECTED) return;
  650. #if MQTT_USE_ASYNC
  651. _mqttConnect();
  652. #else // not MQTT_USE_ASYNC
  653. if (_mqtt.connected()) {
  654. _mqtt.loop();
  655. } else {
  656. if (_mqtt_connected) {
  657. _mqttOnDisconnect();
  658. _mqtt_connected = false;
  659. }
  660. _mqttConnect();
  661. }
  662. #endif
  663. }
  664. #else
  665. bool mqttForward() {
  666. return false;
  667. }
  668. #endif // MQTT_SUPPORT