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
7 years ago
7 years ago
7 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. */
  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 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. unsigned long _mqtt_disconnected_at = 0;
  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. if (millis() - _mqtt_disconnected_at < _mqtt_reconnect_delay) return;
  61. // Increase the reconnect delay
  62. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  63. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  64. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  65. }
  66. String h = getSetting("mqttServer", MQTT_SERVER);
  67. #if MDNS_CLIENT_SUPPORT
  68. h = mdnsResolve(h);
  69. #endif
  70. char * host = strdup(h.c_str());
  71. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  72. if (_mqtt_user) free(_mqtt_user);
  73. if (_mqtt_pass) free(_mqtt_pass);
  74. if (_mqtt_will) free(_mqtt_will);
  75. if (_mqtt_clientid) free(_mqtt_clientid);
  76. String user = getSetting("mqttUser", MQTT_USER);
  77. _mqttPlaceholders(&user);
  78. _mqtt_user = strdup(user.c_str());
  79. _mqtt_pass = strdup(getSetting("mqttPassword", MQTT_PASS).c_str());
  80. _mqtt_will = strdup(mqttTopic(MQTT_TOPIC_STATUS, false).c_str());
  81. String clientid = getSetting("mqttClientID", getIdentifier());
  82. _mqttPlaceholders(&clientid);
  83. _mqtt_clientid = strdup(clientid.c_str());
  84. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d\n"), host, port);
  85. #if MQTT_USE_ASYNC
  86. _mqtt.setServer(host, port);
  87. _mqtt.setClientId(_mqtt_clientid);
  88. _mqtt.setKeepAlive(_mqtt_keepalive);
  89. _mqtt.setCleanSession(false);
  90. _mqtt.setWill(_mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  91. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  92. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  93. _mqtt.setCredentials(_mqtt_user, _mqtt_pass);
  94. }
  95. #if ASYNC_TCP_SSL_ENABLED
  96. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  97. _mqtt.setSecure(secure);
  98. if (secure) {
  99. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  100. unsigned char fp[20] = {0};
  101. if (sslFingerPrintArray(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  102. _mqtt.addServerFingerprint(fp);
  103. } else {
  104. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  105. }
  106. }
  107. #endif // ASYNC_TCP_SSL_ENABLED
  108. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid);
  109. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  110. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  111. DEBUG_MSG_P(PSTR("[MQTT] Keepalive time: %ds\n"), _mqtt_keepalive);
  112. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  113. _mqtt.connect();
  114. #else // not MQTT_USE_ASYNC
  115. bool response = true;
  116. #if ASYNC_TCP_SSL_ENABLED
  117. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  118. if (secure) {
  119. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  120. if (_mqtt_client_secure.connect(host, port)) {
  121. char fp[60] = {0};
  122. if (sslFingerPrintChar(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  123. if (_mqtt_client_secure.verify(fp, host)) {
  124. _mqtt.setClient(_mqtt_client_secure);
  125. } else {
  126. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  127. response = false;
  128. }
  129. _mqtt_client_secure.stop();
  130. yield();
  131. } else {
  132. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  133. response = false;
  134. }
  135. } else {
  136. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  137. response = false;
  138. }
  139. } else {
  140. _mqtt.setClient(_mqtt_client);
  141. }
  142. #else // not ASYNC_TCP_SSL_ENABLED
  143. _mqtt.setClient(_mqtt_client);
  144. #endif // ASYNC_TCP_SSL_ENABLED
  145. if (response) {
  146. _mqtt.setServer(host, port);
  147. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  148. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  149. response = _mqtt.connect(_mqtt_clientid, _mqtt_user, _mqtt_pass, _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  150. } else {
  151. response = _mqtt.connect(_mqtt_clientid, _mqtt_will, _mqtt_qos, _mqtt_retain, "0");
  152. }
  153. DEBUG_MSG_P(PSTR("[MQTT] Client ID: %s\n"), _mqtt_clientid);
  154. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), _mqtt_qos);
  155. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), _mqtt_retain ? 1 : 0);
  156. DEBUG_MSG_P(PSTR("[MQTT] Keepalive time: %ds\n"), _mqtt_keepalive);
  157. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  158. }
  159. if (response) {
  160. _mqttOnConnect();
  161. } else {
  162. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  163. }
  164. #endif // MQTT_USE_ASYNC
  165. free(host);
  166. }
  167. void _mqttPlaceholders(String *text) {
  168. text->replace("{hostname}", getSetting("hostname"));
  169. text->replace("{magnitude}", "#");
  170. String mac = WiFi.macAddress();
  171. mac.replace(":", "");
  172. text->replace("{mac}", mac);
  173. }
  174. void _mqttConfigure() {
  175. // Get base topic
  176. _mqtt_topic = getSetting("mqttTopic", MQTT_TOPIC);
  177. if (_mqtt_topic.endsWith("/")) _mqtt_topic.remove(_mqtt_topic.length()-1);
  178. // Placeholders
  179. _mqttPlaceholders(&_mqtt_topic);
  180. if (_mqtt_topic.indexOf("#") == -1) _mqtt_topic = _mqtt_topic + "/#";
  181. // Getters and setters
  182. _mqtt_setter = getSetting("mqttSetter", MQTT_SETTER);
  183. _mqtt_getter = getSetting("mqttGetter", MQTT_GETTER);
  184. _mqtt_forward = !_mqtt_getter.equals(_mqtt_setter);
  185. // MQTT options
  186. _mqtt_qos = getSetting("mqttQoS", MQTT_QOS).toInt();
  187. _mqtt_retain = getSetting("mqttRetain", MQTT_RETAIN).toInt() == 1;
  188. _mqtt_keepalive = getSetting("mqttKeep", MQTT_KEEPALIVE).toInt();
  189. if (getSetting("mqttClientID").length() == 0) delSetting("mqttClientID");
  190. // Enable
  191. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  192. mqttEnabled(false);
  193. } else {
  194. _mqtt_enabled = getSetting("mqttEnabled", MQTT_ENABLED).toInt() == 1;
  195. }
  196. _mqtt_use_json = (getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1);
  197. mqttQueueTopic(MQTT_TOPIC_JSON);
  198. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  199. }
  200. void _mqttBackwards() {
  201. String mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  202. if (mqttTopic.indexOf("{identifier}") > 0) {
  203. mqttTopic.replace("{identifier}", "{hostname}");
  204. setSetting("mqttTopic", mqttTopic);
  205. }
  206. }
  207. unsigned long _mqttNextMessageId() {
  208. static unsigned long id = 0;
  209. // just reboot, get last count from EEPROM
  210. if (id == 0) {
  211. // read id from EEPROM and shift it
  212. id = EEPROMr.read(EEPROM_MESSAGE_ID);
  213. if (id == 0xFF) {
  214. // There was nothing in EEPROM,
  215. // next message is first message
  216. id = 0;
  217. } else {
  218. id = (id << 8) + EEPROMr.read(EEPROM_MESSAGE_ID + 1);
  219. id = (id << 8) + EEPROMr.read(EEPROM_MESSAGE_ID + 2);
  220. id = (id << 8) + EEPROMr.read(EEPROM_MESSAGE_ID + 3);
  221. // Calculate next block and start from there
  222. id = MQTT_MESSAGE_ID_SHIFT * (1 + (id / MQTT_MESSAGE_ID_SHIFT));
  223. }
  224. }
  225. // Save to EEPROM every MQTT_MESSAGE_ID_SHIFT
  226. if (id % MQTT_MESSAGE_ID_SHIFT == 0) {
  227. EEPROMr.write(EEPROM_MESSAGE_ID + 0, (id >> 24) & 0xFF);
  228. EEPROMr.write(EEPROM_MESSAGE_ID + 1, (id >> 16) & 0xFF);
  229. EEPROMr.write(EEPROM_MESSAGE_ID + 2, (id >> 8) & 0xFF);
  230. EEPROMr.write(EEPROM_MESSAGE_ID + 3, (id >> 0) & 0xFF);
  231. eepromCommit();
  232. }
  233. id++;
  234. return id;
  235. }
  236. // -----------------------------------------------------------------------------
  237. // WEB
  238. // -----------------------------------------------------------------------------
  239. #if WEB_SUPPORT
  240. bool _mqttWebSocketOnReceive(const char * key, JsonVariant& value) {
  241. if (strncmp(key, "mqtt", 3) == 0) return true;
  242. if (strncmp(key, "hb", 2) == 0) return true;
  243. return false;
  244. }
  245. void _mqttWebSocketOnSend(JsonObject& root) {
  246. root["mqttVisible"] = 1;
  247. root["mqttStatus"] = mqttConnected();
  248. root["mqttEnabled"] = mqttEnabled();
  249. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  250. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  251. root["mqttUser"] = getSetting("mqttUser", MQTT_USER);
  252. root["mqttClientID"] = getSetting("mqttClientID");
  253. root["mqttPassword"] = getSetting("mqttPassword", MQTT_PASS);
  254. root["mqttKeep"] = _mqtt_keepalive;
  255. root["mqttRetain"] = _mqtt_retain;
  256. root["mqttQoS"] = _mqtt_qos;
  257. #if ASYNC_TCP_SSL_ENABLED
  258. root["mqttsslVisible"] = 1;
  259. root["mqttUseSSL"] = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  260. root["mqttFP"] = getSetting("mqttFP", MQTT_SSL_FINGERPRINT);
  261. #endif
  262. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  263. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  264. }
  265. #endif
  266. // -----------------------------------------------------------------------------
  267. // SETTINGS
  268. // -----------------------------------------------------------------------------
  269. #if TERMINAL_SUPPORT
  270. void _mqttInitCommands() {
  271. terminalRegisterCommand(F("MQTT.RESET"), [](Embedis* e) {
  272. _mqttConfigure();
  273. mqttDisconnect();
  274. terminalOK();
  275. });
  276. }
  277. #endif // TERMINAL_SUPPORT
  278. // -----------------------------------------------------------------------------
  279. // MQTT Callbacks
  280. // -----------------------------------------------------------------------------
  281. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  282. if (type == MQTT_CONNECT_EVENT) {
  283. // Subscribe to internal action topics
  284. mqttSubscribe(MQTT_TOPIC_ACTION);
  285. // Flag system to send heartbeat
  286. systemSendHeartbeat();
  287. }
  288. if (type == MQTT_MESSAGE_EVENT) {
  289. // Match topic
  290. String t = mqttMagnitude((char *) topic);
  291. // Actions
  292. if (t.equals(MQTT_TOPIC_ACTION)) {
  293. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  294. deferredReset(100, CUSTOM_RESET_MQTT);
  295. }
  296. }
  297. }
  298. }
  299. void _mqttOnConnect() {
  300. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  301. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  302. #if MQTT_SKIP_RETAINED
  303. _mqtt_connected_at = millis();
  304. #endif
  305. // Clean subscriptions
  306. mqttUnsubscribeRaw("#");
  307. // Send connect event to subscribers
  308. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  309. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  310. }
  311. }
  312. void _mqttOnDisconnect() {
  313. _mqtt_disconnected_at = millis();
  314. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  315. // Send disconnect event to subscribers
  316. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  317. (_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  318. }
  319. }
  320. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  321. if (len == 0) return;
  322. char message[len + 1];
  323. strlcpy(message, (char *) payload, len + 1);
  324. #if MQTT_SKIP_RETAINED
  325. if (millis() - _mqtt_connected_at < MQTT_SKIP_TIME) {
  326. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  327. return;
  328. }
  329. #endif
  330. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  331. // Send message event to subscribers
  332. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  333. (_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  334. }
  335. }
  336. // -----------------------------------------------------------------------------
  337. // Public API
  338. // -----------------------------------------------------------------------------
  339. /**
  340. Returns the magnitude part of a topic
  341. @param topic the full MQTT topic
  342. @return String object with the magnitude part.
  343. */
  344. String mqttMagnitude(char * topic) {
  345. String pattern = _mqtt_topic + _mqtt_setter;
  346. int position = pattern.indexOf("#");
  347. if (position == -1) return String();
  348. String start = pattern.substring(0, position);
  349. String end = pattern.substring(position + 1);
  350. String magnitude = String(topic);
  351. if (magnitude.startsWith(start) && magnitude.endsWith(end)) {
  352. magnitude.replace(start, "");
  353. magnitude.replace(end, "");
  354. } else {
  355. magnitude = String();
  356. }
  357. return magnitude;
  358. }
  359. /**
  360. Returns a full MQTT topic from the magnitude
  361. @param magnitude the magnitude part of the topic.
  362. @param is_set whether to build a command topic (true)
  363. or a state topic (false).
  364. @return String full MQTT topic.
  365. */
  366. String mqttTopic(const char * magnitude, bool is_set) {
  367. String output = _mqtt_topic;
  368. output.replace("#", magnitude);
  369. output += is_set ? _mqtt_setter : _mqtt_getter;
  370. return output;
  371. }
  372. /**
  373. Returns a full MQTT topic from the magnitude
  374. @param magnitude the magnitude part of the topic.
  375. @param index index of the magnitude when more than one such magnitudes.
  376. @param is_set whether to build a command topic (true)
  377. or a state topic (false).
  378. @return String full MQTT topic.
  379. */
  380. String mqttTopic(const char * magnitude, unsigned int index, bool is_set) {
  381. char buffer[strlen(magnitude)+5];
  382. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), magnitude, index);
  383. return mqttTopic(buffer, is_set);
  384. }
  385. // -----------------------------------------------------------------------------
  386. void mqttSendRaw(const char * topic, const char * message, bool retain) {
  387. if (_mqtt.connected()) {
  388. #if MQTT_USE_ASYNC
  389. unsigned int packetId = _mqtt.publish(topic, _mqtt_qos, retain, message);
  390. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %d)\n"), topic, message, packetId);
  391. #else
  392. _mqtt.publish(topic, message, retain);
  393. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  394. #endif
  395. }
  396. }
  397. void mqttSendRaw(const char * topic, const char * message) {
  398. mqttSendRaw (topic, message, _mqtt_retain);
  399. }
  400. void mqttSend(const char * topic, const char * message, bool force, bool retain) {
  401. bool useJson = force ? false : _mqtt_use_json;
  402. // Equeue message
  403. if (useJson) {
  404. // Set default queue topic
  405. mqttQueueTopic(MQTT_TOPIC_JSON);
  406. // Enqueue new message
  407. mqttEnqueue(topic, message);
  408. // Reset flush timer
  409. _mqtt_flush_ticker.once_ms(MQTT_USE_JSON_DELAY, mqttFlush);
  410. // Send it right away
  411. } else {
  412. mqttSendRaw(mqttTopic(topic, false).c_str(), message, retain);
  413. }
  414. }
  415. void mqttSend(const char * topic, const char * message, bool force) {
  416. mqttSend(topic, message, force, _mqtt_retain);
  417. }
  418. void mqttSend(const char * topic, const char * message) {
  419. mqttSend(topic, message, false);
  420. }
  421. void mqttSend(const char * topic, unsigned int index, const char * message, bool force, bool retain) {
  422. char buffer[strlen(topic)+5];
  423. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  424. mqttSend(buffer, message, force, retain);
  425. }
  426. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  427. mqttSend(topic, index, message, force, _mqtt_retain);
  428. }
  429. void mqttSend(const char * topic, unsigned int index, const char * message) {
  430. mqttSend(topic, index, message, false);
  431. }
  432. // -----------------------------------------------------------------------------
  433. unsigned char _mqttBuildTree(JsonObject& root, char parent) {
  434. unsigned char count = 0;
  435. // Add enqueued messages
  436. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  437. mqtt_message_t element = _mqtt_queue[i];
  438. if (element.parent == parent) {
  439. ++count;
  440. JsonObject& elements = root.createNestedObject(element.topic);
  441. unsigned char num = _mqttBuildTree(elements, i);
  442. if (0 == num) {
  443. if (isNumber(element.message)) {
  444. double value = atof(element.message);
  445. if (value == int(value)) {
  446. root.set(element.topic, int(value));
  447. } else {
  448. root.set(element.topic, value);
  449. }
  450. } else {
  451. root.set(element.topic, element.message);
  452. }
  453. }
  454. }
  455. }
  456. return count;
  457. }
  458. void mqttFlush() {
  459. if (!_mqtt.connected()) return;
  460. if (_mqtt_queue.size() == 0) return;
  461. // Build tree recursively
  462. DynamicJsonBuffer jsonBuffer;
  463. JsonObject& root = jsonBuffer.createObject();
  464. _mqttBuildTree(root, 255);
  465. // Add extra propeties
  466. #if NTP_SUPPORT && MQTT_ENQUEUE_DATETIME
  467. if (ntpSynced()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  468. #endif
  469. #if MQTT_ENQUEUE_MAC
  470. root[MQTT_TOPIC_MAC] = WiFi.macAddress();
  471. #endif
  472. #if MQTT_ENQUEUE_HOSTNAME
  473. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  474. #endif
  475. #if MQTT_ENQUEUE_IP
  476. root[MQTT_TOPIC_IP] = getIP();
  477. #endif
  478. #if MQTT_ENQUEUE_MESSAGE_ID
  479. root[MQTT_TOPIC_MESSAGE_ID] = _mqttNextMessageId();
  480. #endif
  481. // Send
  482. String output;
  483. root.printTo(output);
  484. jsonBuffer.clear();
  485. mqttSendRaw(_mqtt_topic_json.c_str(), output.c_str(), false);
  486. // Clear queue
  487. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  488. mqtt_message_t element = _mqtt_queue[i];
  489. free(element.topic);
  490. if (element.message) {
  491. free(element.message);
  492. }
  493. }
  494. _mqtt_queue.clear();
  495. }
  496. void mqttQueueTopic(const char * topic) {
  497. String t = mqttTopic(topic, false);
  498. if (!t.equals(_mqtt_topic_json)) {
  499. mqttFlush();
  500. _mqtt_topic_json = t;
  501. }
  502. }
  503. int8_t mqttEnqueue(const char * topic, const char * message, unsigned char parent) {
  504. // Queue is not meant to send message "offline"
  505. // We must prevent the queue does not get full while offline
  506. if (!_mqtt.connected()) return -1;
  507. // Force flusing the queue if the MQTT_QUEUE_MAX_SIZE has been reached
  508. if (_mqtt_queue.size() >= MQTT_QUEUE_MAX_SIZE) mqttFlush();
  509. int8_t index = _mqtt_queue.size();
  510. // Enqueue new message
  511. mqtt_message_t element;
  512. element.parent = parent;
  513. element.topic = strdup(topic);
  514. if (NULL != message) {
  515. element.message = strdup(message);
  516. }
  517. _mqtt_queue.push_back(element);
  518. return index;
  519. }
  520. int8_t mqttEnqueue(const char * topic, const char * message) {
  521. return mqttEnqueue(topic, message, 255);
  522. }
  523. // -----------------------------------------------------------------------------
  524. void mqttSubscribeRaw(const char * topic) {
  525. if (_mqtt.connected() && (strlen(topic) > 0)) {
  526. #if MQTT_USE_ASYNC
  527. unsigned int packetId = _mqtt.subscribe(topic, _mqtt_qos);
  528. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  529. #else
  530. _mqtt.subscribe(topic, _mqtt_qos);
  531. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  532. #endif
  533. }
  534. }
  535. void mqttSubscribe(const char * topic) {
  536. mqttSubscribeRaw(mqttTopic(topic, true).c_str());
  537. }
  538. void mqttUnsubscribeRaw(const char * topic) {
  539. if (_mqtt.connected() && (strlen(topic) > 0)) {
  540. #if MQTT_USE_ASYNC
  541. unsigned int packetId = _mqtt.unsubscribe(topic);
  542. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  543. #else
  544. _mqtt.unsubscribe(topic);
  545. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  546. #endif
  547. }
  548. }
  549. void mqttUnsubscribe(const char * topic) {
  550. mqttUnsubscribeRaw(mqttTopic(topic, true).c_str());
  551. }
  552. // -----------------------------------------------------------------------------
  553. void mqttEnabled(bool status) {
  554. _mqtt_enabled = status;
  555. }
  556. bool mqttEnabled() {
  557. return _mqtt_enabled;
  558. }
  559. bool mqttConnected() {
  560. return _mqtt.connected();
  561. }
  562. void mqttDisconnect() {
  563. if (_mqtt.connected()) {
  564. DEBUG_MSG_P(PSTR("[MQTT] Disconnecting\n"));
  565. _mqtt.disconnect();
  566. }
  567. }
  568. bool mqttForward() {
  569. return _mqtt_forward;
  570. }
  571. void mqttRegister(mqtt_callback_f callback) {
  572. _mqtt_callbacks.push_back(callback);
  573. }
  574. void mqttSetBroker(IPAddress ip, unsigned int port) {
  575. setSetting("mqttServer", ip.toString());
  576. setSetting("mqttPort", port);
  577. mqttEnabled(MQTT_AUTOCONNECT);
  578. }
  579. void mqttSetBrokerIfNone(IPAddress ip, unsigned int port) {
  580. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) mqttSetBroker(ip, port);
  581. }
  582. void mqttReset() {
  583. _mqttConfigure();
  584. mqttDisconnect();
  585. }
  586. // -----------------------------------------------------------------------------
  587. // Initialization
  588. // -----------------------------------------------------------------------------
  589. void mqttSetup() {
  590. _mqttBackwards();
  591. DEBUG_MSG_P(PSTR("[MQTT] Async %s, SSL %s, Autoconnect %s\n"),
  592. MQTT_USE_ASYNC ? "ENABLED" : "DISABLED",
  593. ASYNC_TCP_SSL_ENABLED ? "ENABLED" : "DISABLED",
  594. MQTT_AUTOCONNECT ? "ENABLED" : "DISABLED"
  595. );
  596. #if MQTT_USE_ASYNC
  597. _mqtt.onConnect([](bool sessionPresent) {
  598. _mqttOnConnect();
  599. });
  600. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  601. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  602. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  603. }
  604. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  605. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  606. }
  607. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  608. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  609. }
  610. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  611. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  612. }
  613. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  614. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  615. }
  616. #if ASYNC_TCP_SSL_ENABLED
  617. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  618. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  619. }
  620. #endif
  621. _mqttOnDisconnect();
  622. });
  623. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  624. _mqttOnMessage(topic, payload, len);
  625. });
  626. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  627. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  628. });
  629. _mqtt.onPublish([](uint16_t packetId) {
  630. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  631. });
  632. #else // not MQTT_USE_ASYNC
  633. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  634. _mqttOnMessage(topic, (char *) payload, length);
  635. });
  636. #endif // MQTT_USE_ASYNC
  637. _mqttConfigure();
  638. mqttRegister(_mqttCallback);
  639. #if WEB_SUPPORT
  640. wsOnSendRegister(_mqttWebSocketOnSend);
  641. wsOnReceiveRegister(_mqttWebSocketOnReceive);
  642. #endif
  643. #if TERMINAL_SUPPORT
  644. _mqttInitCommands();
  645. #endif
  646. // Main callbacks
  647. espurnaRegisterLoop(mqttLoop);
  648. espurnaRegisterReload(_mqttConfigure);
  649. }
  650. void mqttLoop() {
  651. if (WiFi.status() != WL_CONNECTED) return;
  652. #if MQTT_USE_ASYNC
  653. _mqttConnect();
  654. #else // not MQTT_USE_ASYNC
  655. if (_mqtt.connected()) {
  656. _mqtt.loop();
  657. } else {
  658. if (_mqtt_connected) {
  659. _mqttOnDisconnect();
  660. _mqtt_connected = false;
  661. }
  662. _mqttConnect();
  663. }
  664. #endif
  665. }
  666. #endif // MQTT_SUPPORT