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.

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