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.

609 lines
18 KiB

8 years ago
8 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-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if MQTT_SUPPORT
  6. #include <ESP8266WiFi.h>
  7. #include <ESP8266mDNS.h>
  8. #include <ArduinoJson.h>
  9. #include <vector>
  10. #include <Ticker.h>
  11. #if MQTT_USE_ASYNC // Using AsyncMqttClient
  12. #include <AsyncMqttClient.h>
  13. AsyncMqttClient _mqtt;
  14. #else // Using PubSubClient
  15. #include <PubSubClient.h>
  16. PubSubClient _mqtt;
  17. bool _mqtt_connected = false;
  18. WiFiClient _mqtt_client;
  19. #if ASYNC_TCP_SSL_ENABLED
  20. WiFiClientSecure _mqtt_client_secure;
  21. #endif // ASYNC_TCP_SSL_ENABLED
  22. #endif // MQTT_USE_ASYNC
  23. bool _mqtt_enabled = MQTT_ENABLED;
  24. bool _mqtt_use_json = false;
  25. unsigned long _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  26. String _mqtt_topic;
  27. String _mqtt_setter;
  28. String _mqtt_getter;
  29. bool _mqtt_forward;
  30. char *_mqtt_user = 0;
  31. char *_mqtt_pass = 0;
  32. char *_mqtt_will;
  33. #if MQTT_SKIP_RETAINED
  34. unsigned long _mqtt_connected_at = 0;
  35. #endif
  36. std::vector<mqtt_callback_f> _mqtt_callbacks;
  37. typedef struct {
  38. char * topic;
  39. char * message;
  40. } mqtt_message_t;
  41. std::vector<mqtt_message_t> _mqtt_queue;
  42. Ticker _mqtt_flush_ticker;
  43. // -----------------------------------------------------------------------------
  44. // Public API
  45. // -----------------------------------------------------------------------------
  46. bool mqttConnected() {
  47. return _mqtt.connected();
  48. }
  49. void mqttDisconnect() {
  50. if (_mqtt.connected()) {
  51. DEBUG_MSG_P("[MQTT] Disconnecting\n");
  52. _mqtt.disconnect();
  53. }
  54. }
  55. bool mqttForward() {
  56. return _mqtt_forward;
  57. }
  58. String mqttSubtopic(char * topic) {
  59. String response;
  60. String t = String(topic);
  61. if (t.startsWith(_mqtt_topic) && t.endsWith(_mqtt_setter)) {
  62. response = t.substring(_mqtt_topic.length(), t.length() - _mqtt_setter.length());
  63. }
  64. return response;
  65. }
  66. void mqttSendRaw(const char * topic, const char * message) {
  67. if (_mqtt.connected()) {
  68. #if MQTT_USE_ASYNC
  69. unsigned int packetId = _mqtt.publish(topic, MQTT_QOS, MQTT_RETAIN, message);
  70. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %d)\n"), topic, message, packetId);
  71. #else
  72. _mqtt.publish(topic, message, MQTT_RETAIN);
  73. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  74. #endif
  75. }
  76. }
  77. String getTopic(const char * topic, bool set) {
  78. String output = _mqtt_topic + String(topic);
  79. if (set) output += _mqtt_setter;
  80. return output;
  81. }
  82. String getTopic(const char * topic, unsigned int index, bool set) {
  83. char buffer[strlen(topic)+5];
  84. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  85. return getTopic(buffer, set);
  86. }
  87. void _mqttFlush() {
  88. if (_mqtt_queue.size() == 0) return;
  89. DynamicJsonBuffer jsonBuffer;
  90. JsonObject& root = jsonBuffer.createObject();
  91. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  92. mqtt_message_t element = _mqtt_queue[i];
  93. root[element.topic] = element.message;
  94. }
  95. #if NTP_SUPPORT
  96. if (ntpConnected()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  97. #endif
  98. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  99. root[MQTT_TOPIC_IP] = getIP();
  100. String output;
  101. root.printTo(output);
  102. String path = _mqtt_topic + String(MQTT_TOPIC_JSON);
  103. mqttSendRaw(path.c_str(), output.c_str());
  104. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  105. mqtt_message_t element = _mqtt_queue[i];
  106. free(element.topic);
  107. free(element.message);
  108. }
  109. _mqtt_queue.clear();
  110. }
  111. void mqttSend(const char * topic, const char * message, bool force) {
  112. bool useJson = force ? false : _mqtt_use_json;
  113. if (useJson) {
  114. mqtt_message_t element;
  115. element.topic = strdup(topic);
  116. element.message = strdup(message);
  117. _mqtt_queue.push_back(element);
  118. _mqtt_flush_ticker.once_ms(MQTT_USE_JSON_DELAY, _mqttFlush);
  119. } else {
  120. String path = _mqtt_topic + String(topic) + _mqtt_getter;
  121. mqttSendRaw(path.c_str(), message);
  122. }
  123. }
  124. void mqttSend(const char * topic, const char * message) {
  125. mqttSend(topic, message, false);
  126. }
  127. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  128. char buffer[strlen(topic)+5];
  129. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  130. mqttSend(buffer, message, force);
  131. }
  132. void mqttSend(const char * topic, unsigned int index, const char * message) {
  133. mqttSend(topic, index, message, false);
  134. }
  135. void mqttSubscribeRaw(const char * topic) {
  136. if (_mqtt.connected() && (strlen(topic) > 0)) {
  137. #if MQTT_USE_ASYNC
  138. unsigned int packetId = _mqtt.subscribe(topic, MQTT_QOS);
  139. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  140. #else
  141. _mqtt.subscribe(topic, MQTT_QOS);
  142. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  143. #endif
  144. }
  145. }
  146. void mqttSubscribe(const char * topic) {
  147. String path = _mqtt_topic + String(topic) + _mqtt_setter;
  148. mqttSubscribeRaw(path.c_str());
  149. }
  150. void mqttUnsubscribeRaw(const char * topic) {
  151. if (_mqtt.connected() && (strlen(topic) > 0)) {
  152. #if MQTT_USE_ASYNC
  153. unsigned int packetId = _mqtt.unsubscribe(topic);
  154. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s (PID %d)\n"), topic, packetId);
  155. #else
  156. _mqtt.unsubscribe(topic);
  157. DEBUG_MSG_P(PSTR("[MQTT] Unsubscribing to %s\n"), topic);
  158. #endif
  159. }
  160. }
  161. void mqttRegister(mqtt_callback_f callback) {
  162. _mqtt_callbacks.push_back(callback);
  163. }
  164. // -----------------------------------------------------------------------------
  165. // Callbacks
  166. // -----------------------------------------------------------------------------
  167. void _mqttWebSocketOnSend(JsonObject& root) {
  168. root["mqttVisible"] = 1;
  169. root["mqttStatus"] = mqttConnected();
  170. root["mqttEnabled"] = mqttEnabled();
  171. root["mqttServer"] = getSetting("mqttServer", MQTT_SERVER);
  172. root["mqttPort"] = getSetting("mqttPort", MQTT_PORT);
  173. root["mqttUser"] = getSetting("mqttUser");
  174. root["mqttPassword"] = getSetting("mqttPassword");
  175. #if ASYNC_TCP_SSL_ENABLED
  176. root["mqttsslVisible"] = 1;
  177. root["mqttUseSSL"] = getSetting("mqttUseSSL", 0).toInt() == 1;
  178. root["mqttFP"] = getSetting("mqttFP");
  179. #endif
  180. root["mqttTopic"] = getSetting("mqttTopic", MQTT_TOPIC);
  181. root["mqttUseJson"] = getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  182. }
  183. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  184. if (type == MQTT_CONNECT_EVENT) {
  185. mqttSubscribe(MQTT_TOPIC_ACTION);
  186. }
  187. if (type == MQTT_MESSAGE_EVENT) {
  188. // Match topic
  189. String t = mqttSubtopic((char *) topic);
  190. // Actions
  191. if (t.equals(MQTT_TOPIC_ACTION)) {
  192. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  193. deferredReset(100, CUSTOM_RESET_MQTT);
  194. }
  195. }
  196. }
  197. }
  198. void _mqttOnConnect() {
  199. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  200. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  201. #if MQTT_SKIP_RETAINED
  202. _mqtt_connected_at = millis();
  203. #endif
  204. // Send first Heartbeat
  205. heartbeat();
  206. // Clean subscriptions
  207. mqttUnsubscribeRaw("#");
  208. // Send connect event to subscribers
  209. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  210. (_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  211. }
  212. }
  213. void _mqttOnDisconnect() {
  214. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  215. // Send disconnect event to subscribers
  216. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  217. (_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  218. }
  219. }
  220. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  221. if (len == 0) return;
  222. char message[len + 1];
  223. strlcpy(message, (char *) payload, len + 1);
  224. #if MQTT_SKIP_RETAINED
  225. if (millis() - _mqtt_connected_at < MQTT_SKIP_TIME) {
  226. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  227. return;
  228. }
  229. #endif
  230. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  231. // Send message event to subscribers
  232. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  233. (_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  234. }
  235. }
  236. #if MQTT_USE_ASYNC
  237. bool mqttFormatFP(const char * fingerprint, unsigned char * bytearray) {
  238. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  239. if (strlen(fingerprint) != 59) return false;
  240. DEBUG_MSG_P(PSTR("[MQTT] Fingerprint %s\n"), fingerprint);
  241. // walk the fingerprint
  242. for (unsigned int i=0; i<20; i++) {
  243. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  244. }
  245. return true;
  246. }
  247. #else
  248. bool mqttFormatFP(const char * fingerprint, char * destination) {
  249. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  250. if (strlen(fingerprint) != 59) return false;
  251. DEBUG_MSG_P(PSTR("[MQTT] Fingerprint %s\n"), fingerprint);
  252. // copy it
  253. strncpy(destination, fingerprint, 59);
  254. // walk the fingerprint replacing ':' for ' '
  255. for (unsigned char i = 0; i<59; i++) {
  256. if (destination[i] == ':') destination[i] = ' ';
  257. }
  258. return true;
  259. }
  260. #endif
  261. void mqttEnabled(bool status) {
  262. _mqtt_enabled = status;
  263. setSetting("mqttEnabled", status ? 1 : 0);
  264. }
  265. bool mqttEnabled() {
  266. return _mqtt_enabled;
  267. }
  268. void mqttConnect() {
  269. // Do not connect if disabled
  270. if (!_mqtt_enabled) return;
  271. // Do not connect if already connected
  272. if (_mqtt.connected()) return;
  273. // Check reconnect interval
  274. static unsigned long last = 0;
  275. if (millis() - last < _mqtt_reconnect_delay) return;
  276. last = millis();
  277. // Increase the reconnect delay
  278. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  279. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  280. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  281. }
  282. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  283. if (strlen(host) == 0) return;
  284. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  285. if (_mqtt_user) free(_mqtt_user);
  286. if (_mqtt_pass) free(_mqtt_pass);
  287. if (_mqtt_will) free(_mqtt_will);
  288. _mqtt_user = strdup(getSetting("mqttUser", MQTT_USER).c_str());
  289. _mqtt_pass = strdup(getSetting("mqttPassword", MQTT_PASS).c_str());
  290. _mqtt_will = strdup((_mqtt_topic + MQTT_TOPIC_STATUS).c_str());
  291. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d\n"), host, port);
  292. #if MQTT_USE_ASYNC
  293. _mqtt.setServer(host, port);
  294. _mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  295. _mqtt.setWill(_mqtt_will, MQTT_QOS, MQTT_RETAIN, "0");
  296. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  297. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  298. _mqtt.setCredentials(_mqtt_user, _mqtt_pass);
  299. }
  300. #if ASYNC_TCP_SSL_ENABLED
  301. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  302. _mqtt.setSecure(secure);
  303. if (secure) {
  304. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  305. unsigned char fp[20] = {0};
  306. if (mqttFormatFP(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  307. _mqtt.addServerFingerprint(fp);
  308. } else {
  309. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  310. }
  311. }
  312. #endif // ASYNC_TCP_SSL_ENABLED
  313. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  314. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), MQTT_QOS);
  315. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), MQTT_RETAIN);
  316. _mqtt.connect();
  317. #else // not MQTT_USE_ASYNC
  318. bool response = true;
  319. #if ASYNC_TCP_SSL_ENABLED
  320. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  321. if (secure) {
  322. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  323. if (_mqtt_client_secure.connect(host, port)) {
  324. char fp[60] = {0};
  325. if (mqttFormatFP(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  326. if (_mqtt_client_secure.verify(fp, host)) {
  327. _mqtt.setClient(_mqtt_client_secure);
  328. } else {
  329. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  330. response = false;
  331. }
  332. _mqtt_client_secure.stop();
  333. yield();
  334. } else {
  335. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  336. response = false;
  337. }
  338. } else {
  339. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  340. response = false;
  341. }
  342. } else {
  343. _mqtt.setClient(_mqtt_client);
  344. }
  345. #else // not ASYNC_TCP_SSL_ENABLED
  346. _mqtt.setClient(_mqtt_client);
  347. #endif // ASYNC_TCP_SSL_ENABLED
  348. if (response) {
  349. _mqtt.setServer(host, port);
  350. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  351. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  352. response = _mqtt.connect(getIdentifier().c_str(), _mqtt_user, _mqtt_pass, _mqtt_will, MQTT_QOS, MQTT_RETAIN, "0");
  353. } else {
  354. response = _mqtt.connect(getIdentifier().c_str(), _mqtt_will, MQTT_QOS, MQTT_RETAIN, "0");
  355. }
  356. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  357. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), MQTT_QOS);
  358. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), MQTT_RETAIN);
  359. }
  360. if (response) {
  361. _mqttOnConnect();
  362. } else {
  363. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  364. }
  365. #endif // MQTT_USE_ASYNC
  366. free(host);
  367. }
  368. void mqttConfigure() {
  369. // Replace identifier
  370. _mqtt_topic = getSetting("mqttTopic", MQTT_TOPIC);
  371. _mqtt_topic.replace("{identifier}", getSetting("hostname"));
  372. if (!_mqtt_topic.endsWith("/")) _mqtt_topic = _mqtt_topic + "/";
  373. // Getters and setters
  374. _mqtt_setter = getSetting("mqttSetter", MQTT_USE_SETTER);
  375. _mqtt_getter = getSetting("mqttGetter", MQTT_USE_GETTER);
  376. _mqtt_forward = !_mqtt_getter.equals(_mqtt_setter);
  377. // Enable
  378. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  379. mqttEnabled(false);
  380. } else {
  381. _mqtt_enabled = getSetting("mqttEnabled", MQTT_ENABLED).toInt() == 1;
  382. }
  383. _mqtt_use_json = (getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1);
  384. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  385. }
  386. void mqttSetBroker(IPAddress ip, unsigned int port) {
  387. setSetting("mqttServer", ip.toString());
  388. setSetting("mqttPort", port);
  389. mqttEnabled(MQTT_AUTOCONNECT);
  390. }
  391. void mqttSetBrokerIfNone(IPAddress ip, unsigned int port) {
  392. if (!hasSetting("mqttServer")) mqttSetBroker(ip, port);
  393. }
  394. void mqttSetup() {
  395. DEBUG_MSG_P(PSTR("[MQTT] MQTT_USE_ASYNC = %d\n"), MQTT_USE_ASYNC);
  396. DEBUG_MSG_P(PSTR("[MQTT] MQTT_AUTOCONNECT = %d\n"), MQTT_AUTOCONNECT);
  397. #if MQTT_USE_ASYNC
  398. _mqtt.onConnect([](bool sessionPresent) {
  399. _mqttOnConnect();
  400. });
  401. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  402. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  403. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  404. }
  405. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  406. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  407. }
  408. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  409. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  410. }
  411. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  412. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  413. }
  414. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  415. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  416. }
  417. #if ASYNC_TCP_SSL_ENABLED
  418. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  419. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  420. }
  421. #endif
  422. _mqttOnDisconnect();
  423. });
  424. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  425. _mqttOnMessage(topic, payload, len);
  426. });
  427. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  428. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  429. });
  430. _mqtt.onPublish([](uint16_t packetId) {
  431. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  432. });
  433. #else // not MQTT_USE_ASYNC
  434. DEBUG_MSG_P(PSTR("[MQTT] Using SYNC MQTT library\n"));
  435. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  436. _mqttOnMessage(topic, (char *) payload, length);
  437. });
  438. #endif // MQTT_USE_ASYNC
  439. mqttConfigure();
  440. mqttRegister(_mqttCallback);
  441. #if WEB_SUPPORT
  442. wsOnSendRegister(_mqttWebSocketOnSend);
  443. #endif
  444. }
  445. void mqttLoop() {
  446. if (WiFi.status() != WL_CONNECTED) return;
  447. #if MQTT_USE_ASYNC
  448. mqttConnect();
  449. #else // not MQTT_USE_ASYNC
  450. if (_mqtt.connected()) {
  451. _mqtt.loop();
  452. } else {
  453. if (_mqtt_connected) {
  454. _mqttOnDisconnect();
  455. _mqtt_connected = false;
  456. }
  457. mqttConnect();
  458. }
  459. #endif
  460. }
  461. #endif // MQTT_SUPPORT