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.

876 lines
25 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
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /*
  2. MQTT MODULE
  3. Copyright (C) 2016-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. Module key prefix: mqtt
  5. */
  6. #if MQTT_SUPPORT
  7. #include <EEPROM_Rotate.h>
  8. #include <ESP8266WiFi.h>
  9. #include <ESP8266mDNS.h>
  10. #include <ArduinoJson.h>
  11. #include <vector>
  12. #include <Ticker.h>
  13. #if MQTT_USE_ASYNC // Using AsyncMqttClient
  14. #include <AsyncMqttClient.h>
  15. AsyncMqttClient _mqtt;
  16. #else // Using PubSubClient
  17. #include <PubSubClient.h>
  18. PubSubClient _mqtt;
  19. bool _mqtt_connected = false;
  20. WiFiClient _mqtt_client;
  21. #if ASYNC_TCP_SSL_ENABLED
  22. WiFiClientSecure _mqtt_client_secure;
  23. #endif // ASYNC_TCP_SSL_ENABLED
  24. #endif // MQTT_USE_ASYNC
  25. bool _mqtt_enabled = MQTT_ENABLED;
  26. bool _mqtt_use_json = false;
  27. unsigned long _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  28. unsigned char _mqtt_qos = MQTT_QOS;
  29. bool _mqtt_retain = MQTT_RETAIN;
  30. unsigned long _mqtt_keepalive = MQTT_KEEPALIVE;
  31. String _mqtt_topic;
  32. String _mqtt_topic_json;
  33. String _mqtt_setter;
  34. String _mqtt_getter;
  35. bool _mqtt_forward;
  36. char *_mqtt_user = 0;
  37. char *_mqtt_pass = 0;
  38. char *_mqtt_will;
  39. char *_mqtt_clientid;
  40. #if MQTT_SKIP_RETAINED
  41. unsigned long _mqtt_connected_at = 0;
  42. #endif
  43. std::vector<mqtt_callback_f> _mqtt_callbacks;
  44. typedef struct {
  45. unsigned char parent = 255;
  46. char * topic;
  47. char * message = NULL;
  48. } mqtt_message_t;
  49. std::vector<mqtt_message_t> _mqtt_queue;
  50. Ticker _mqtt_flush_ticker;
  51. // -----------------------------------------------------------------------------
  52. // Private
  53. // -----------------------------------------------------------------------------
  54. void _mqttConnect() {
  55. // Do not connect if disabled
  56. if (!_mqtt_enabled) return;
  57. // Do not connect if already connected
  58. if (_mqtt.connected()) return;
  59. // Check reconnect interval
  60. static unsigned long last = 0;
  61. if (millis() - last < _mqtt_reconnect_delay) return;
  62. last = millis();
  63. // Increase the reconnect delay
  64. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  65. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  66. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  67. }
  68. String h = getSetting("mqttServer", MQTT_SERVER);
  69. #if MDNS_CLIENT_SUPPORT
  70. h = mdnsResolve(h);
  71. #endif
  72. char * host = strdup(h.c_str());
  73. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  74. if (_mqtt_user) free(_mqtt_user);
  75. if (_mqtt_pass) free(_mqtt_pass);
  76. if (_mqtt_will) free(_mqtt_will);
  77. if (_mqtt_clientid) free(_mqtt_clientid);
  78. _mqtt_user = strdup(getSetting("mqttUser", MQTT_USER).c_str());
  79. _mqtt_pass = strdup(getSetting("mqttPass", MQTT_PASS).c_str());
  80. _mqtt_will = strdup(mqttTopic(MQTT_TOPIC_STATUS, false).c_str());
  81. _mqtt_clientid = strdup(getSetting("mqttClientID", getIdentifier()).c_str());
  82. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d\n"), host, port);
  83. #if MQTT_USE_ASYNC
  84. _mqtt.setServer(host, port);
  85. _mqtt.setClientId(_mqtt_clientid);
  86. _mqtt.setKeepAlive(_mqtt_keepalive);
  87. _mqtt.setCleanSession(false);
  88. _mqtt.setWill(_mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  89. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  90. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  91. _mqtt.setCredentials(_mqtt_user, _mqtt_pass);
  92. }
  93. #if ASYNC_TCP_SSL_ENABLED
  94. bool secure = getSetting("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. if (isNumber(element.message)) {
  441. double value = atof(element.message);
  442. if (value == int(value)) {
  443. root.set(element.topic, int(value));
  444. } else {
  445. root.set(element.topic, value);
  446. }
  447. } else {
  448. root.set(element.topic, element.message);
  449. }
  450. }
  451. }
  452. }
  453. return count;
  454. }
  455. void mqttFlush() {
  456. if (!_mqtt.connected()) return;
  457. if (_mqtt_queue.size() == 0) return;
  458. // Build tree recursively
  459. DynamicJsonBuffer jsonBuffer;
  460. JsonObject& root = jsonBuffer.createObject();
  461. _mqttBuildTree(root, 255);
  462. // Add extra propeties
  463. #if NTP_SUPPORT && MQTT_ENQUEUE_DATETIME
  464. if (ntpSynced()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  465. #endif
  466. #if MQTT_ENQUEUE_MAC
  467. root[MQTT_TOPIC_MAC] = WiFi.macAddress();
  468. #endif
  469. #if MQTT_ENQUEUE_HOSTNAME
  470. root[MQTT_TOPIC_HOSTNAME] = getHostname();
  471. #endif
  472. #if MQTT_ENQUEUE_IP
  473. root[MQTT_TOPIC_IP] = getIP();
  474. #endif
  475. #if MQTT_ENQUEUE_MESSAGE_ID
  476. root[MQTT_TOPIC_MESSAGE_ID] = _mqttNextMessageId();
  477. #endif
  478. // Send
  479. String output;
  480. root.printTo(output);
  481. jsonBuffer.clear();
  482. mqttSendRaw(_mqtt_topic_json.c_str(), output.c_str(), false);
  483. // Clear queue
  484. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  485. mqtt_message_t element = _mqtt_queue[i];
  486. free(element.topic);
  487. if (element.message) {
  488. free(element.message);
  489. }
  490. }
  491. _mqtt_queue.clear();
  492. }
  493. void mqttQueueTopic(const char * topic) {
  494. String t = mqttTopic(topic, false);
  495. if (!t.equals(_mqtt_topic_json)) {
  496. mqttFlush();
  497. _mqtt_topic_json = t;
  498. }
  499. }
  500. int8_t mqttEnqueue(const char * topic, const char * message, unsigned char parent) {
  501. // Queue is not meant to send message "offline"
  502. // We must prevent the queue does not get full while offline
  503. if (!_mqtt.connected()) return -1;
  504. // Force flusing the queue if the MQTT_QUEUE_MAX_SIZE has been reached
  505. if (_mqtt_queue.size() >= MQTT_QUEUE_MAX_SIZE) mqttFlush();
  506. int8_t index = _mqtt_queue.size();
  507. // Enqueue new message
  508. mqtt_message_t element;
  509. element.parent = parent;
  510. element.topic = strdup(topic);
  511. if (NULL != message) {
  512. element.message = strdup(message);
  513. }
  514. _mqtt_queue.push_back(element);
  515. return index;
  516. }
  517. int8_t mqttEnqueue(const char * topic, const char * message) {
  518. return mqttEnqueue(topic, message, 255);
  519. }
  520. // -----------------------------------------------------------------------------
  521. void mqttSubscribeRaw(const char * topic) {
  522. if (_mqtt.connected() && (strlen(topic) > 0)) {
  523. #if MQTT_USE_ASYNC
  524. unsigned int packetId = _mqtt.subscribe(topic, _mqtt_qos);
  525. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  526. #else
  527. _mqtt.subscribe(topic, _mqtt_qos);
  528. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  529. #endif
  530. }
  531. }
  532. void mqttSubscribe(const char * topic) {
  533. mqttSubscribeRaw(mqttTopic(topic, true).c_str());
  534. }
  535. void mqttUnsubscribeRaw(const char * topic) {
  536. if (_mqtt.connected() && (strlen(topic) > 0)) {
  537. #if MQTT_USE_ASYNC
  538. unsigned int packetId = _mqtt.unsubscribe(topic);
  539. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  540. #else
  541. _mqtt.unsubscribe(topic);
  542. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  543. #endif
  544. }
  545. }
  546. void mqttUnsubscribe(const char * topic) {
  547. mqttUnsubscribeRaw(mqttTopic(topic, true).c_str());
  548. }
  549. // -----------------------------------------------------------------------------
  550. void mqttEnabled(bool status) {
  551. _mqtt_enabled = status;
  552. }
  553. bool mqttEnabled() {
  554. return _mqtt_enabled;
  555. }
  556. bool mqttConnected() {
  557. return _mqtt.connected();
  558. }
  559. void mqttDisconnect() {
  560. if (_mqtt.connected()) {
  561. DEBUG_MSG_P(PSTR("[MQTT] Disconnecting\n"));
  562. _mqtt.disconnect();
  563. }
  564. }
  565. bool mqttForward() {
  566. return _mqtt_forward;
  567. }
  568. void mqttRegister(mqtt_callback_f callback) {
  569. _mqtt_callbacks.push_back(callback);
  570. }
  571. void mqttSetBroker(IPAddress ip, unsigned int port) {
  572. setSetting("mqttServer", ip.toString());
  573. setSetting("mqttPort", port);
  574. mqttEnabled(MQTT_AUTOCONNECT);
  575. }
  576. void mqttSetBrokerIfNone(IPAddress ip, unsigned int port) {
  577. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) mqttSetBroker(ip, port);
  578. }
  579. void mqttReset() {
  580. _mqttConfigure();
  581. mqttDisconnect();
  582. }
  583. // -----------------------------------------------------------------------------
  584. // Initialization
  585. // -----------------------------------------------------------------------------
  586. void mqttSetup() {
  587. // Check backwards compatibility
  588. _mqttBackwards();
  589. DEBUG_MSG_P(PSTR("[MQTT] Async %s, SSL %s, Autoconnect %s\n"),
  590. MQTT_USE_ASYNC ? "ENABLED" : "DISABLED",
  591. ASYNC_TCP_SSL_ENABLED ? "ENABLED" : "DISABLED",
  592. MQTT_AUTOCONNECT ? "ENABLED" : "DISABLED"
  593. );
  594. #if MQTT_USE_ASYNC
  595. _mqtt.onConnect([](bool sessionPresent) {
  596. _mqttOnConnect();
  597. });
  598. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  599. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  600. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  601. }
  602. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  603. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  604. }
  605. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  606. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  607. }
  608. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  609. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  610. }
  611. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  612. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  613. }
  614. #if ASYNC_TCP_SSL_ENABLED
  615. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  616. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  617. }
  618. #endif
  619. _mqttOnDisconnect();
  620. });
  621. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  622. _mqttOnMessage(topic, payload, len);
  623. });
  624. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  625. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  626. });
  627. _mqtt.onPublish([](uint16_t packetId) {
  628. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  629. });
  630. #else // not MQTT_USE_ASYNC
  631. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  632. _mqttOnMessage(topic, (char *) payload, length);
  633. });
  634. #endif // MQTT_USE_ASYNC
  635. _mqttConfigure();
  636. mqttRegister(_mqttCallback);
  637. #if WEB_SUPPORT
  638. wsOnSendRegister(_mqttWebSocketOnSend);
  639. #endif
  640. #if TERMINAL_SUPPORT
  641. _mqttInitCommands();
  642. #endif
  643. // Register
  644. settingsRegisterKeyCheck(_mqttKeyCheck);
  645. // Main callbacks
  646. espurnaRegisterLoop(mqttLoop);
  647. espurnaRegisterReload(_mqttConfigure);
  648. }
  649. void mqttLoop() {
  650. if (WiFi.status() != WL_CONNECTED) return;
  651. #if MQTT_USE_ASYNC
  652. _mqttConnect();
  653. #else // not MQTT_USE_ASYNC
  654. if (_mqtt.connected()) {
  655. _mqtt.loop();
  656. } else {
  657. if (_mqtt_connected) {
  658. _mqttOnDisconnect();
  659. _mqtt_connected = false;
  660. }
  661. _mqttConnect();
  662. }
  663. #endif
  664. }
  665. #endif // MQTT_SUPPORT