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.

873 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-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. }
  163. #endif // MQTT_USE_ASYNC
  164. free(host);
  165. }
  166. void _mqttPlaceholders(String *text) {
  167. text->replace("{hostname}", getSetting("hostname"));
  168. text->replace("{magnitude}", "#");
  169. String mac = WiFi.macAddress();
  170. mac.replace(":", "");
  171. text->replace("{mac}", mac);
  172. }
  173. void _mqttConfigure() {
  174. // Get base topic
  175. _mqtt_topic = getSetting("mqttTopic", MQTT_TOPIC);
  176. if (_mqtt_topic.endsWith("/")) _mqtt_topic.remove(_mqtt_topic.length()-1);
  177. // Placeholders
  178. _mqttPlaceholders(&_mqtt_topic);
  179. if (_mqtt_topic.indexOf("#") == -1) _mqtt_topic = _mqtt_topic + "/#";
  180. // Getters and setters
  181. _mqtt_setter = getSetting("mqttSetter", MQTT_SETTER);
  182. _mqtt_getter = getSetting("mqttGetter", MQTT_GETTER);
  183. _mqtt_forward = !_mqtt_getter.equals(_mqtt_setter);
  184. // MQTT options
  185. _mqtt_qos = getSetting("mqttQoS", MQTT_QOS).toInt();
  186. _mqtt_retain = getSetting("mqttRetain", MQTT_RETAIN).toInt() == 1;
  187. _mqtt_keepalive = getSetting("mqttKeep", MQTT_KEEPALIVE).toInt();
  188. if (getSetting("mqttClientID").length() == 0) delSetting("mqttClientID");
  189. // Enable
  190. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  191. mqttEnabled(false);
  192. } else {
  193. _mqtt_enabled = getSetting("mqttEnabled", MQTT_ENABLED).toInt() == 1;
  194. }
  195. _mqtt_use_json = (getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1);
  196. mqttQueueTopic(MQTT_TOPIC_JSON);
  197. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  198. }
  199. void _mqttBackwards() {
  200. String mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  201. if (mqttTopic.indexOf("{identifier}") > 0) {
  202. mqttTopic.replace("{identifier}", "{hostname}");
  203. setSetting("mqttTopic", mqttTopic);
  204. }
  205. }
  206. unsigned long _mqttNextMessageId() {
  207. static unsigned long id = 0;
  208. // just reboot, get last count from EEPROM
  209. if (id == 0) {
  210. // read id from EEPROM and shift it
  211. id = EEPROMr.read(EEPROM_MESSAGE_ID);
  212. if (id == 0xFF) {
  213. // There was nothing in EEPROM,
  214. // next message is first message
  215. id = 0;
  216. } else {
  217. id = (id << 8) + EEPROMr.read(EEPROM_MESSAGE_ID + 1);
  218. id = (id << 8) + EEPROMr.read(EEPROM_MESSAGE_ID + 2);
  219. id = (id << 8) + EEPROMr.read(EEPROM_MESSAGE_ID + 3);
  220. // Calculate next block and start from there
  221. id = MQTT_MESSAGE_ID_SHIFT * (1 + (id / MQTT_MESSAGE_ID_SHIFT));
  222. }
  223. }
  224. // Save to EEPROM every MQTT_MESSAGE_ID_SHIFT
  225. if (id % MQTT_MESSAGE_ID_SHIFT == 0) {
  226. EEPROMr.write(EEPROM_MESSAGE_ID + 0, (id >> 24) & 0xFF);
  227. EEPROMr.write(EEPROM_MESSAGE_ID + 1, (id >> 16) & 0xFF);
  228. EEPROMr.write(EEPROM_MESSAGE_ID + 2, (id >> 8) & 0xFF);
  229. EEPROMr.write(EEPROM_MESSAGE_ID + 3, (id >> 0) & 0xFF);
  230. eepromCommit();
  231. }
  232. id++;
  233. return id;
  234. }
  235. // -----------------------------------------------------------------------------
  236. // WEB
  237. // -----------------------------------------------------------------------------
  238. #if WEB_SUPPORT
  239. bool _mqttWebSocketOnReceive(const char * key, JsonVariant& value) {
  240. return (strncmp(key, "mqtt", 3) == 0);
  241. }
  242. void _mqttWebSocketOnSend(JsonObject& root) {
  243. root["mqttVisible"] = 1;
  244. root["mqttStatus"] = mqttConnected();
  245. root["mqttEnabled"] = mqttEnabled();
  246. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  247. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  248. root["mqttUser"] = getSetting("mqttUser", MQTT_USER);
  249. root["mqttClientID"] = getSetting("mqttClientID");
  250. root["mqttPassword"] = getSetting("mqttPassword", MQTT_PASS);
  251. root["mqttKeep"] = _mqtt_keepalive;
  252. root["mqttRetain"] = _mqtt_retain;
  253. root["mqttQoS"] = _mqtt_qos;
  254. #if ASYNC_TCP_SSL_ENABLED
  255. root["mqttsslVisible"] = 1;
  256. root["mqttUseSSL"] = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  257. root["mqttFP"] = getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  258. #endif
  259. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  260. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  261. }
  262. #endif
  263. // -----------------------------------------------------------------------------
  264. // SETTINGS
  265. // -----------------------------------------------------------------------------
  266. #if TERMINAL_SUPPORT
  267. void _mqttInitCommands() {
  268. terminalRegisterCommand(F("MQTT.RESET"), [](Embedis* e) {
  269. _mqttConfigure();
  270. mqttDisconnect();
  271. terminalOK();
  272. });
  273. }
  274. #endif // TERMINAL_SUPPORT
  275. // -----------------------------------------------------------------------------
  276. // MQTT Callbacks
  277. // -----------------------------------------------------------------------------
  278. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  279. if (type == MQTT_CONNECT_EVENT) {
  280. // Subscribe to internal action topics
  281. mqttSubscribe(MQTT_TOPIC_ACTION);
  282. // Flag system to send heartbeat
  283. systemSendHeartbeat();
  284. }
  285. if (type == MQTT_MESSAGE_EVENT) {
  286. // Match topic
  287. String t = mqttMagnitude((char *) topic);
  288. // Actions
  289. if (t.equals(MQTT_TOPIC_ACTION)) {
  290. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  291. deferredReset(100, CUSTOM_RESET_MQTT);
  292. }
  293. }
  294. }
  295. }
  296. void _mqttOnConnect() {
  297. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  298. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  299. _mqtt_last_connection = millis();
  300. // Clean subscriptions
  301. mqttUnsubscribeRaw("#");
  302. // Send connect event to subscribers
  303. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  304. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  305. }
  306. }
  307. void _mqttOnDisconnect() {
  308. // Reset reconnection delay
  309. _mqtt_last_connection = millis();
  310. _mqtt_connecting = false;
  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_last_connection < 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] = getSetting("hostname");
  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. _mqttBackwards();
  588. DEBUG_MSG_P(PSTR("[MQTT] Async %s, SSL %s, Autoconnect %s\n"),
  589. MQTT_USE_ASYNC ? "ENABLED" : "DISABLED",
  590. ASYNC_TCP_SSL_ENABLED ? "ENABLED" : "DISABLED",
  591. MQTT_AUTOCONNECT ? "ENABLED" : "DISABLED"
  592. );
  593. #if MQTT_USE_ASYNC
  594. _mqtt.onConnect([](bool sessionPresent) {
  595. _mqttOnConnect();
  596. });
  597. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  598. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  599. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  600. }
  601. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  602. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  603. }
  604. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  605. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  606. }
  607. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  608. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  609. }
  610. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  611. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  612. }
  613. #if ASYNC_TCP_SSL_ENABLED
  614. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  615. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  616. }
  617. #endif
  618. _mqttOnDisconnect();
  619. });
  620. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  621. _mqttOnMessage(topic, payload, len);
  622. });
  623. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  624. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  625. });
  626. _mqtt.onPublish([](uint16_t packetId) {
  627. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  628. });
  629. #else // not MQTT_USE_ASYNC
  630. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  631. _mqttOnMessage(topic, (char *) payload, length);
  632. });
  633. #endif // MQTT_USE_ASYNC
  634. _mqttConfigure();
  635. mqttRegister(_mqttCallback);
  636. #if WEB_SUPPORT
  637. wsOnSendRegister(_mqttWebSocketOnSend);
  638. wsOnReceiveRegister(_mqttWebSocketOnReceive);
  639. #endif
  640. #if TERMINAL_SUPPORT
  641. _mqttInitCommands();
  642. #endif
  643. // Main callbacks
  644. espurnaRegisterLoop(mqttLoop);
  645. espurnaRegisterReload(_mqttConfigure);
  646. }
  647. void mqttLoop() {
  648. if (WiFi.status() != WL_CONNECTED) return;
  649. #if MQTT_USE_ASYNC
  650. _mqttConnect();
  651. #else // not MQTT_USE_ASYNC
  652. if (_mqtt.connected()) {
  653. _mqtt.loop();
  654. } else {
  655. if (_mqtt_connected) {
  656. _mqttOnDisconnect();
  657. _mqtt_connected = false;
  658. }
  659. _mqttConnect();
  660. }
  661. #endif
  662. }
  663. #endif // MQTT_SUPPORT