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