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.

857 lines
25 KiB

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