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.

862 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-2018 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 char _mqtt_qos = MQTT_QOS;
  28. bool _mqtt_retain = MQTT_RETAIN;
  29. unsigned long _mqtt_keepalive = MQTT_KEEPALIVE;
  30. String _mqtt_topic;
  31. String _mqtt_topic_json;
  32. String _mqtt_setter;
  33. String _mqtt_getter;
  34. bool _mqtt_forward;
  35. char *_mqtt_user = 0;
  36. char *_mqtt_pass = 0;
  37. char *_mqtt_will;
  38. char *_mqtt_clientid;
  39. #if MQTT_SKIP_RETAINED
  40. unsigned long _mqtt_connected_at = 0;
  41. #endif
  42. std::vector<mqtt_callback_f> _mqtt_callbacks;
  43. typedef struct {
  44. unsigned char parent = 255;
  45. char * topic;
  46. char * message = NULL;
  47. } mqtt_message_t;
  48. std::vector<mqtt_message_t> _mqtt_queue;
  49. Ticker _mqtt_flush_ticker;
  50. // -----------------------------------------------------------------------------
  51. // Private
  52. // -----------------------------------------------------------------------------
  53. void _mqttConnect() {
  54. // Do not connect if disabled
  55. if (!_mqtt_enabled) return;
  56. // Do not connect if already connected
  57. if (_mqtt.connected()) return;
  58. // Check reconnect interval
  59. static unsigned long last = 0;
  60. if (millis() - last < _mqtt_reconnect_delay) return;
  61. last = millis();
  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. String h = getSetting("mqttServer", MQTT_SERVER);
  68. #if MDNS_CLIENT_SUPPORT
  69. h = mdnsResolve(h);
  70. #endif
  71. char * host = strdup(h.c_str());
  72. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  73. if (_mqtt_user) free(_mqtt_user);
  74. if (_mqtt_pass) free(_mqtt_pass);
  75. if (_mqtt_will) free(_mqtt_will);
  76. if (_mqtt_clientid) free(_mqtt_clientid);
  77. _mqtt_user = strdup(getSetting("mqttUser", MQTT_USER).c_str());
  78. _mqtt_pass = strdup(getSetting("mqttPassword", MQTT_PASS).c_str());
  79. _mqtt_will = strdup(mqttTopic(MQTT_TOPIC_STATUS, false).c_str());
  80. _mqtt_clientid = strdup(getSetting("mqttClientID", getIdentifier()).c_str());
  81. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d\n"), host, port);
  82. #if MQTT_USE_ASYNC
  83. _mqtt.setServer(host, port);
  84. _mqtt.setClientId(_mqtt_clientid);
  85. _mqtt.setKeepAlive(_mqtt_keepalive);
  86. _mqtt.setCleanSession(false);
  87. _mqtt.setWill(_mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  88. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  89. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  90. _mqtt.setCredentials(_mqtt_user, _mqtt_pass);
  91. }
  92. #if ASYNC_TCP_SSL_ENABLED
  93. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  94. _mqtt.setSecure(secure);
  95. if (secure) {
  96. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  97. unsigned char fp[20] = {0};
  98. if (sslFingerPrintArray(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  99. _mqtt.addServerFingerprint(fp);
  100. } else {
  101. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  102. }
  103. }
  104. #endif // ASYNC_TCP_SSL_ENABLED
  105. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid);
  106. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  107. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  108. DEBUG_MSG_P(PSTR("[MQTT] Keepalive time: %ds\n"), _mqtt_keepalive);
  109. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  110. _mqtt.connect();
  111. #else // not MQTT_USE_ASYNC
  112. bool response = true;
  113. #if ASYNC_TCP_SSL_ENABLED
  114. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  115. if (secure) {
  116. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  117. if (_mqtt_client_secure.connect(host, port)) {
  118. char fp[60] = {0};
  119. if (sslFingerPrintChar(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  120. if (_mqtt_client_secure.verify(fp, host)) {
  121. _mqtt.setClient(_mqtt_client_secure);
  122. } else {
  123. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  124. response = false;
  125. }
  126. _mqtt_client_secure.stop();
  127. yield();
  128. } else {
  129. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  130. response = false;
  131. }
  132. } else {
  133. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  134. response = false;
  135. }
  136. } else {
  137. _mqtt.setClient(_mqtt_client);
  138. }
  139. #else // not ASYNC_TCP_SSL_ENABLED
  140. _mqtt.setClient(_mqtt_client);
  141. #endif // ASYNC_TCP_SSL_ENABLED
  142. if (response) {
  143. _mqtt.setServer(host, port);
  144. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  145. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  146. response = _mqtt.connect(_mqtt_clientid, _mqtt_user, _mqtt_pass, _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  147. } else {
  148. response = _mqtt.connect(_mqtt_clientid, _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  149. }
  150. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid);
  151. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  152. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  153. DEBUG_MSG_P(PSTR("[MQTT] Keepalive time: %ds\n"), _mqtt_keepalive);
  154. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  155. }
  156. if (response) {
  157. _mqttOnConnect();
  158. } else {
  159. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  160. }
  161. #endif // MQTT_USE_ASYNC
  162. free(host);
  163. }
  164. void _mqttConfigure() {
  165. // Get base topic
  166. _mqtt_topic = getSetting("mqttTopic", MQTT_TOPIC);
  167. if (_mqtt_topic.endsWith("/")) _mqtt_topic.remove(_mqtt_topic.length()-1);
  168. // Placeholders
  169. _mqtt_topic.replace("{hostname}", getSetting("hostname"));
  170. _mqtt_topic.replace("{magnitude}", "#");
  171. if (_mqtt_topic.indexOf("#") == -1) _mqtt_topic = _mqtt_topic + "/#";
  172. String mac = WiFi.macAddress();
  173. mac.replace(":", "");
  174. _mqtt_topic.replace("{mac}", mac);
  175. // Getters and setters
  176. _mqtt_setter = getSetting("mqttSetter", MQTT_SETTER);
  177. _mqtt_getter = getSetting("mqttGetter", MQTT_GETTER);
  178. _mqtt_forward = !_mqtt_getter.equals(_mqtt_setter);
  179. // MQTT options
  180. _mqtt_qos = getSetting("mqttQoS", MQTT_QOS).toInt();
  181. _mqtt_retain = getSetting("mqttRetain", MQTT_RETAIN).toInt() == 1;
  182. _mqtt_keepalive = getSetting("mqttKeep", MQTT_KEEPALIVE).toInt();
  183. if (getSetting("mqttClientID").length() == 0) delSetting("mqttClientID");
  184. // Enable
  185. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  186. mqttEnabled(false);
  187. } else {
  188. _mqtt_enabled = getSetting("mqttEnabled", MQTT_ENABLED).toInt() == 1;
  189. }
  190. _mqtt_use_json = (getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1);
  191. mqttQueueTopic(MQTT_TOPIC_JSON);
  192. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  193. }
  194. void _mqttBackwards() {
  195. String mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  196. if (mqttTopic.indexOf("{identifier}") > 0) {
  197. mqttTopic.replace("{identifier}", "{hostname}");
  198. setSetting("mqttTopic", mqttTopic);
  199. }
  200. }
  201. unsigned long _mqttNextMessageId() {
  202. static unsigned long id = 0;
  203. // just reboot, get last count from EEPROM
  204. if (id == 0) {
  205. // read id from EEPROM and shift it
  206. id = EEPROMr.read(EEPROM_MESSAGE_ID);
  207. if (id == 0xFF) {
  208. // There was nothing in EEPROM,
  209. // next message is first message
  210. id = 0;
  211. } else {
  212. id = (id << 8) + EEPROMr.read(EEPROM_MESSAGE_ID + 1);
  213. id = (id << 8) + EEPROMr.read(EEPROM_MESSAGE_ID + 2);
  214. id = (id << 8) + EEPROMr.read(EEPROM_MESSAGE_ID + 3);
  215. // Calculate next block and start from there
  216. id = MQTT_MESSAGE_ID_SHIFT * (1 + (id / MQTT_MESSAGE_ID_SHIFT));
  217. }
  218. }
  219. // Save to EEPROM every MQTT_MESSAGE_ID_SHIFT
  220. if (id % MQTT_MESSAGE_ID_SHIFT == 0) {
  221. EEPROMr.write(EEPROM_MESSAGE_ID + 0, (id >> 24) & 0xFF);
  222. EEPROMr.write(EEPROM_MESSAGE_ID + 1, (id >> 16) & 0xFF);
  223. EEPROMr.write(EEPROM_MESSAGE_ID + 2, (id >> 8) & 0xFF);
  224. EEPROMr.write(EEPROM_MESSAGE_ID + 3, (id >> 0) & 0xFF);
  225. eepromCommit();
  226. }
  227. id++;
  228. return id;
  229. }
  230. // -----------------------------------------------------------------------------
  231. // WEB
  232. // -----------------------------------------------------------------------------
  233. #if WEB_SUPPORT
  234. bool _mqttWebSocketOnReceive(const char * key, JsonVariant& value) {
  235. return (strncmp(key, "mqtt", 3) == 0);
  236. }
  237. void _mqttWebSocketOnSend(JsonObject& root) {
  238. root["mqttVisible"] = 1;
  239. root["mqttStatus"] = mqttConnected();
  240. root["mqttEnabled"] = mqttEnabled();
  241. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  242. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  243. root["mqttUser"] = getSetting("mqttUser", MQTT_USER);
  244. root["mqttClientID"] = getSetting("mqttClientID");
  245. root["mqttPassword"] = getSetting("mqttPassword", MQTT_PASS);
  246. root["mqttKeep"] = _mqtt_keepalive;
  247. root["mqttRetain"] = _mqtt_retain;
  248. root["mqttQoS"] = _mqtt_qos;
  249. #if ASYNC_TCP_SSL_ENABLED
  250. root["mqttsslVisible"] = 1;
  251. root["mqttUseSSL"] = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  252. root["mqttFP"] = getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  253. #endif
  254. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  255. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  256. }
  257. #endif
  258. // -----------------------------------------------------------------------------
  259. // SETTINGS
  260. // -----------------------------------------------------------------------------
  261. #if TERMINAL_SUPPORT
  262. void _mqttInitCommands() {
  263. settingsRegisterCommand(F("MQTT.RESET"), [](Embedis* e) {
  264. _mqttConfigure();
  265. mqttDisconnect();
  266. DEBUG_MSG_P(PSTR("+OK\n"));
  267. });
  268. }
  269. #endif // TERMINAL_SUPPORT
  270. // -----------------------------------------------------------------------------
  271. // MQTT Callbacks
  272. // -----------------------------------------------------------------------------
  273. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  274. if (type == MQTT_CONNECT_EVENT) {
  275. // Subscribe to internal action topics
  276. mqttSubscribe(MQTT_TOPIC_ACTION);
  277. // Flag system to send heartbeat
  278. systemSendHeartbeat();
  279. }
  280. if (type == MQTT_MESSAGE_EVENT) {
  281. // Match topic
  282. String t = mqttMagnitude((char *) topic);
  283. // Actions
  284. if (t.equals(MQTT_TOPIC_ACTION)) {
  285. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  286. deferredReset(100, CUSTOM_RESET_MQTT);
  287. }
  288. }
  289. }
  290. }
  291. void _mqttOnConnect() {
  292. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  293. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  294. #if MQTT_SKIP_RETAINED
  295. _mqtt_connected_at = millis();
  296. #endif
  297. // Clean subscriptions
  298. mqttUnsubscribeRaw("#");
  299. // Send connect event to subscribers
  300. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  301. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  302. }
  303. }
  304. void _mqttOnDisconnect() {
  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_connected_at < 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] = _mqttNextMessageId();
  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. DEBUG_MSG_P(PSTR("[MQTT] Async %s, SSL %s, Autoconnect %s\n"),
  583. MQTT_USE_ASYNC ? "ENABLED" : "DISABLED",
  584. ASYNC_TCP_SSL_ENABLED ? "ENABLED" : "DISABLED",
  585. MQTT_AUTOCONNECT ? "ENABLED" : "DISABLED"
  586. );
  587. #if MQTT_USE_ASYNC
  588. _mqtt.onConnect([](bool sessionPresent) {
  589. _mqttOnConnect();
  590. });
  591. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  592. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  593. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  594. }
  595. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  596. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  597. }
  598. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  599. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  600. }
  601. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  602. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  603. }
  604. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  605. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  606. }
  607. #if ASYNC_TCP_SSL_ENABLED
  608. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  609. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  610. }
  611. #endif
  612. _mqttOnDisconnect();
  613. });
  614. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  615. _mqttOnMessage(topic, payload, len);
  616. });
  617. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  618. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  619. });
  620. _mqtt.onPublish([](uint16_t packetId) {
  621. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  622. });
  623. #else // not MQTT_USE_ASYNC
  624. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  625. _mqttOnMessage(topic, (char *) payload, length);
  626. });
  627. #endif // MQTT_USE_ASYNC
  628. _mqttConfigure();
  629. mqttRegister(_mqttCallback);
  630. #if WEB_SUPPORT
  631. wsOnSendRegister(_mqttWebSocketOnSend);
  632. wsOnReceiveRegister(_mqttWebSocketOnReceive);
  633. #endif
  634. #if TERMINAL_SUPPORT
  635. _mqttInitCommands();
  636. #endif
  637. // Main callbacks
  638. espurnaRegisterLoop(mqttLoop);
  639. espurnaRegisterReload(_mqttConfigure);
  640. }
  641. void mqttLoop() {
  642. if (WiFi.status() != WL_CONNECTED) return;
  643. #if MQTT_USE_ASYNC
  644. _mqttConnect();
  645. #else // not MQTT_USE_ASYNC
  646. if (_mqtt.connected()) {
  647. _mqtt.loop();
  648. } else {
  649. if (_mqtt_connected) {
  650. _mqttOnDisconnect();
  651. _mqtt_connected = false;
  652. }
  653. _mqttConnect();
  654. }
  655. #endif
  656. }
  657. #endif // MQTT_SUPPORT