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.

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