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.

595 lines
17 KiB

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