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