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.

866 lines
25 KiB

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