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.

838 lines
24 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. */
  5. #if MQTT_SUPPORT
  6. #include <EEPROM.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("{identifier}", getSetting("hostname"));
  170. _mqtt_topic.replace("{hostname}", getSetting("hostname"));
  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. unsigned long _mqttNextMessageId() {
  196. static unsigned long id = 0;
  197. // just reboot, get last count from EEPROM
  198. if (id == 0) {
  199. // read id from EEPROM and shift it
  200. id = EEPROM.read(EEPROM_MESSAGE_ID);
  201. if (id == 0xFF) {
  202. // There was nothing in EEPROM,
  203. // next message is first message
  204. id = 0;
  205. } else {
  206. id = (id << 8) + EEPROM.read(EEPROM_MESSAGE_ID + 1);
  207. id = (id << 8) + EEPROM.read(EEPROM_MESSAGE_ID + 2);
  208. id = (id << 8) + EEPROM.read(EEPROM_MESSAGE_ID + 3);
  209. // Calculate next block and start from there
  210. id = MQTT_MESSAGE_ID_SHIFT * (1 + (id / MQTT_MESSAGE_ID_SHIFT));
  211. }
  212. }
  213. // Save to EEPROM every MQTT_MESSAGE_ID_SHIFT
  214. if (id % MQTT_MESSAGE_ID_SHIFT == 0) {
  215. EEPROM.write(EEPROM_MESSAGE_ID + 0, (id >> 24) & 0xFF);
  216. EEPROM.write(EEPROM_MESSAGE_ID + 1, (id >> 16) & 0xFF);
  217. EEPROM.write(EEPROM_MESSAGE_ID + 2, (id >> 8) & 0xFF);
  218. EEPROM.write(EEPROM_MESSAGE_ID + 3, (id >> 0) & 0xFF);
  219. EEPROM.commit();
  220. }
  221. id++;
  222. return id;
  223. }
  224. // -----------------------------------------------------------------------------
  225. // WEB
  226. // -----------------------------------------------------------------------------
  227. #if WEB_SUPPORT
  228. void _mqttWebSocketOnSend(JsonObject& root) {
  229. root["mqttVisible"] = 1;
  230. root["mqttStatus"] = mqttConnected();
  231. root["mqttEnabled"] = mqttEnabled();
  232. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  233. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  234. root["mqttUser"] = getSetting("mqttUser", MQTT_USER);
  235. root["mqttClientID"] = getSetting("mqttClientID");
  236. root["mqttPassword"] = getSetting("mqttPassword", MQTT_PASS);
  237. root["mqttKeep"] = _mqtt_keepalive;
  238. root["mqttRetain"] = _mqtt_retain;
  239. root["mqttQoS"] = _mqtt_qos;
  240. #if ASYNC_TCP_SSL_ENABLED
  241. root["mqttsslVisible"] = 1;
  242. root["mqttUseSSL"] = getSetting("mqttUseSSL", 0).toInt() == 1;
  243. root["mqttFP"] = getSetting("mqttFP");
  244. #endif
  245. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  246. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  247. }
  248. #endif
  249. // -----------------------------------------------------------------------------
  250. // SETTINGS
  251. // -----------------------------------------------------------------------------
  252. #if TERMINAL_SUPPORT
  253. void _mqttInitCommands() {
  254. settingsRegisterCommand(F("MQTT.RESET"), [](Embedis* e) {
  255. _mqttConfigure();
  256. mqttDisconnect();
  257. DEBUG_MSG_P(PSTR("+OK\n"));
  258. });
  259. }
  260. #endif // TERMINAL_SUPPORT
  261. // -----------------------------------------------------------------------------
  262. // MQTT Callbacks
  263. // -----------------------------------------------------------------------------
  264. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  265. if (type == MQTT_CONNECT_EVENT) {
  266. // Subscribe to internal action topics
  267. mqttSubscribe(MQTT_TOPIC_ACTION);
  268. // Flag system to send heartbeat
  269. systemSendHeartbeat();
  270. }
  271. if (type == MQTT_MESSAGE_EVENT) {
  272. // Match topic
  273. String t = mqttMagnitude((char *) topic);
  274. // Actions
  275. if (t.equals(MQTT_TOPIC_ACTION)) {
  276. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  277. deferredReset(100, CUSTOM_RESET_MQTT);
  278. }
  279. }
  280. }
  281. }
  282. void _mqttOnConnect() {
  283. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  284. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  285. #if MQTT_SKIP_RETAINED
  286. _mqtt_connected_at = millis();
  287. #endif
  288. // Clean subscriptions
  289. mqttUnsubscribeRaw("#");
  290. // Send connect event to subscribers
  291. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  292. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  293. }
  294. }
  295. void _mqttOnDisconnect() {
  296. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  297. // Send disconnect event to subscribers
  298. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  299. (_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  300. }
  301. }
  302. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  303. if (len == 0) return;
  304. char message[len + 1];
  305. strlcpy(message, (char *) payload, len + 1);
  306. #if MQTT_SKIP_RETAINED
  307. if (millis() - _mqtt_connected_at < MQTT_SKIP_TIME) {
  308. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  309. return;
  310. }
  311. #endif
  312. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  313. // Send message event to subscribers
  314. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  315. (_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  316. }
  317. }
  318. // -----------------------------------------------------------------------------
  319. // Public API
  320. // -----------------------------------------------------------------------------
  321. /**
  322. Returns the magnitude part of a topic
  323. @param topic the full MQTT topic
  324. @return String object with the magnitude part.
  325. */
  326. String mqttMagnitude(char * topic) {
  327. String pattern = _mqtt_topic + _mqtt_setter;
  328. int position = pattern.indexOf("#");
  329. if (position == -1) return String();
  330. String start = pattern.substring(0, position);
  331. String end = pattern.substring(position + 1);
  332. String magnitude = String(topic);
  333. if (magnitude.startsWith(start) && magnitude.endsWith(end)) {
  334. magnitude.replace(start, "");
  335. magnitude.replace(end, "");
  336. } else {
  337. magnitude = String();
  338. }
  339. return magnitude;
  340. }
  341. /**
  342. Returns a full MQTT topic from the magnitude
  343. @param magnitude the magnitude part of the topic.
  344. @param is_set whether to build a command topic (true)
  345. or a state topic (false).
  346. @return String full MQTT topic.
  347. */
  348. String mqttTopic(const char * magnitude, bool is_set) {
  349. String output = _mqtt_topic;
  350. output.replace("#", magnitude);
  351. output += is_set ? _mqtt_setter : _mqtt_getter;
  352. return output;
  353. }
  354. /**
  355. Returns a full MQTT topic from the magnitude
  356. @param magnitude the magnitude part of the topic.
  357. @param index index of the magnitude when more than one such magnitudes.
  358. @param is_set whether to build a command topic (true)
  359. or a state topic (false).
  360. @return String full MQTT topic.
  361. */
  362. String mqttTopic(const char * magnitude, unsigned int index, bool is_set) {
  363. char buffer[strlen(magnitude)+5];
  364. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), magnitude, index);
  365. return mqttTopic(buffer, is_set);
  366. }
  367. // -----------------------------------------------------------------------------
  368. void mqttSendRaw(const char * topic, const char * message, bool retain) {
  369. if (_mqtt.connected()) {
  370. #if MQTT_USE_ASYNC
  371. unsigned int packetId = _mqtt.publish(topic, _mqtt_qos, retain, message);
  372. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %d)\n"), topic, message, packetId);
  373. #else
  374. _mqtt.publish(topic, message, retain);
  375. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  376. #endif
  377. }
  378. }
  379. void mqttSendRaw(const char * topic, const char * message) {
  380. mqttSendRaw (topic, message, _mqtt_retain);
  381. }
  382. void mqttSend(const char * topic, const char * message, bool force, bool retain) {
  383. bool useJson = force ? false : _mqtt_use_json;
  384. // Equeue message
  385. if (useJson) {
  386. // Set default queue topic
  387. mqttQueueTopic(MQTT_TOPIC_JSON);
  388. // Enqueue new message
  389. mqttEnqueue(topic, message);
  390. // Reset flush timer
  391. _mqtt_flush_ticker.once_ms(MQTT_USE_JSON_DELAY, mqttFlush);
  392. // Send it right away
  393. } else {
  394. mqttSendRaw(mqttTopic(topic, false).c_str(), message, retain);
  395. }
  396. }
  397. void mqttSend(const char * topic, const char * message, bool force) {
  398. mqttSend(topic, message, force, _mqtt_retain);
  399. }
  400. void mqttSend(const char * topic, const char * message) {
  401. mqttSend(topic, message, false);
  402. }
  403. void mqttSend(const char * topic, unsigned int index, const char * message, bool force, bool retain) {
  404. char buffer[strlen(topic)+5];
  405. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  406. mqttSend(buffer, message, force, retain);
  407. }
  408. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  409. mqttSend(topic, index, message, force, _mqtt_retain);
  410. }
  411. void mqttSend(const char * topic, unsigned int index, const char * message) {
  412. mqttSend(topic, index, message, false);
  413. }
  414. // -----------------------------------------------------------------------------
  415. unsigned char _mqttBuildTree(JsonObject& root, char parent) {
  416. unsigned char count = 0;
  417. // Add enqueued messages
  418. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  419. mqtt_message_t element = _mqtt_queue[i];
  420. if (element.parent == parent) {
  421. ++count;
  422. JsonObject& elements = root.createNestedObject(element.topic);
  423. unsigned char num = _mqttBuildTree(elements, i);
  424. if (0 == num) {
  425. root.set(element.topic, element.message);
  426. }
  427. }
  428. }
  429. return count;
  430. }
  431. void mqttFlush() {
  432. if (!_mqtt.connected()) return;
  433. if (_mqtt_queue.size() == 0) return;
  434. // Build tree recursively
  435. DynamicJsonBuffer jsonBuffer;
  436. JsonObject& root = jsonBuffer.createObject();
  437. _mqttBuildTree(root, 255);
  438. // Add extra propeties
  439. #if NTP_SUPPORT && MQTT_ENQUEUE_DATETIME
  440. if (ntpSynced()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  441. #endif
  442. #if MQTT_ENQUEUE_MAC
  443. root[MQTT_TOPIC_MAC] = WiFi.macAddress();
  444. #endif
  445. #if MQTT_ENQUEUE_HOSTNAME
  446. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  447. #endif
  448. #if MQTT_ENQUEUE_IP
  449. root[MQTT_TOPIC_IP] = getIP();
  450. #endif
  451. #if MQTT_ENQUEUE_MESSAGE_ID
  452. root[MQTT_TOPIC_MESSAGE_ID] = _mqttNextMessageId();
  453. #endif
  454. // Send
  455. String output;
  456. root.printTo(output);
  457. mqttSendRaw(_mqtt_topic_json.c_str(), output.c_str(), false);
  458. // Clear queue
  459. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  460. mqtt_message_t element = _mqtt_queue[i];
  461. free(element.topic);
  462. if (element.message) {
  463. free(element.message);
  464. }
  465. }
  466. _mqtt_queue.clear();
  467. }
  468. void mqttQueueTopic(const char * topic) {
  469. String t = mqttTopic(topic, false);
  470. if (!t.equals(_mqtt_topic_json)) {
  471. mqttFlush();
  472. _mqtt_topic_json = t;
  473. }
  474. }
  475. int8_t mqttEnqueue(const char * topic, const char * message, unsigned char parent) {
  476. // Queue is not meant to send message "offline"
  477. // We must prevent the queue does not get full while offline
  478. if (!_mqtt.connected()) return -1;
  479. // Force flusing the queue if the MQTT_QUEUE_MAX_SIZE has been reached
  480. if (_mqtt_queue.size() >= MQTT_QUEUE_MAX_SIZE) mqttFlush();
  481. int8_t index = _mqtt_queue.size();
  482. // Enqueue new message
  483. mqtt_message_t element;
  484. element.parent = parent;
  485. element.topic = strdup(topic);
  486. if (NULL != message) {
  487. element.message = strdup(message);
  488. }
  489. _mqtt_queue.push_back(element);
  490. return index;
  491. }
  492. int8_t mqttEnqueue(const char * topic, const char * message) {
  493. return mqttEnqueue(topic, message, 255);
  494. }
  495. // -----------------------------------------------------------------------------
  496. void mqttSubscribeRaw(const char * topic) {
  497. if (_mqtt.connected() && (strlen(topic) > 0)) {
  498. #if MQTT_USE_ASYNC
  499. unsigned int packetId = _mqtt.subscribe(topic, _mqtt_qos);
  500. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  501. #else
  502. _mqtt.subscribe(topic, _mqtt_qos);
  503. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  504. #endif
  505. }
  506. }
  507. void mqttSubscribe(const char * topic) {
  508. mqttSubscribeRaw(mqttTopic(topic, true).c_str());
  509. }
  510. void mqttUnsubscribeRaw(const char * topic) {
  511. if (_mqtt.connected() && (strlen(topic) > 0)) {
  512. #if MQTT_USE_ASYNC
  513. unsigned int packetId = _mqtt.unsubscribe(topic);
  514. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  515. #else
  516. _mqtt.unsubscribe(topic);
  517. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  518. #endif
  519. }
  520. }
  521. void mqttUnsubscribe(const char * topic) {
  522. mqttUnsubscribeRaw(mqttTopic(topic, true).c_str());
  523. }
  524. // -----------------------------------------------------------------------------
  525. void mqttEnabled(bool status) {
  526. _mqtt_enabled = status;
  527. setSetting("mqttEnabled", status ? 1 : 0);
  528. }
  529. bool mqttEnabled() {
  530. return _mqtt_enabled;
  531. }
  532. bool mqttConnected() {
  533. return _mqtt.connected();
  534. }
  535. void mqttDisconnect() {
  536. if (_mqtt.connected()) {
  537. DEBUG_MSG_P(PSTR("[MQTT] Disconnecting\n"));
  538. _mqtt.disconnect();
  539. }
  540. }
  541. bool mqttForward() {
  542. return _mqtt_forward;
  543. }
  544. void mqttRegister(mqtt_callback_f callback) {
  545. _mqtt_callbacks.push_back(callback);
  546. }
  547. void mqttSetBroker(IPAddress ip, unsigned int port) {
  548. setSetting("mqttServer", ip.toString());
  549. setSetting("mqttPort", port);
  550. mqttEnabled(MQTT_AUTOCONNECT);
  551. }
  552. void mqttSetBrokerIfNone(IPAddress ip, unsigned int port) {
  553. if (!hasSetting("mqttServer")) mqttSetBroker(ip, port);
  554. }
  555. void mqttReset() {
  556. _mqttConfigure();
  557. mqttDisconnect();
  558. }
  559. // -----------------------------------------------------------------------------
  560. // Initialization
  561. // -----------------------------------------------------------------------------
  562. void mqttSetup() {
  563. DEBUG_MSG_P(PSTR("[MQTT] Async %s, SSL %s, Autoconnect %s\n"),
  564. MQTT_USE_ASYNC ? "ENABLED" : "DISABLED",
  565. ASYNC_TCP_SSL_ENABLED ? "ENABLED" : "DISABLED",
  566. MQTT_AUTOCONNECT ? "ENABLED" : "DISABLED"
  567. );
  568. #if MQTT_USE_ASYNC
  569. _mqtt.onConnect([](bool sessionPresent) {
  570. _mqttOnConnect();
  571. });
  572. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  573. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  574. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  575. }
  576. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  577. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  578. }
  579. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  580. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  581. }
  582. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  583. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  584. }
  585. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  586. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  587. }
  588. #if ASYNC_TCP_SSL_ENABLED
  589. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  590. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  591. }
  592. #endif
  593. _mqttOnDisconnect();
  594. });
  595. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  596. _mqttOnMessage(topic, payload, len);
  597. });
  598. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  599. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  600. });
  601. _mqtt.onPublish([](uint16_t packetId) {
  602. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  603. });
  604. #else // not MQTT_USE_ASYNC
  605. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  606. _mqttOnMessage(topic, (char *) payload, length);
  607. });
  608. #endif // MQTT_USE_ASYNC
  609. _mqttConfigure();
  610. mqttRegister(_mqttCallback);
  611. #if WEB_SUPPORT
  612. wsOnSendRegister(_mqttWebSocketOnSend);
  613. wsOnAfterParseRegister(_mqttConfigure);
  614. #endif
  615. #if TERMINAL_SUPPORT
  616. _mqttInitCommands();
  617. #endif
  618. // Register loop
  619. espurnaRegisterLoop(mqttLoop);
  620. }
  621. void mqttLoop() {
  622. if (WiFi.status() != WL_CONNECTED) return;
  623. #if MQTT_USE_ASYNC
  624. _mqttConnect();
  625. #else // not MQTT_USE_ASYNC
  626. if (_mqtt.connected()) {
  627. _mqtt.loop();
  628. } else {
  629. if (_mqtt_connected) {
  630. _mqttOnDisconnect();
  631. _mqtt_connected = false;
  632. }
  633. _mqttConnect();
  634. }
  635. #endif
  636. }
  637. #endif // MQTT_SUPPORT