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.

580 lines
16 KiB

8 years ago
8 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<void (*)(unsigned int, const char *, const char *)> _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 mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  150. _mqtt_callbacks.push_back(callback);
  151. }
  152. // -----------------------------------------------------------------------------
  153. // Callbacks
  154. // -----------------------------------------------------------------------------
  155. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  156. if (type == MQTT_CONNECT_EVENT) {
  157. mqttSubscribe(MQTT_TOPIC_ACTION);
  158. }
  159. if (type == MQTT_MESSAGE_EVENT) {
  160. // Match topic
  161. String t = mqttSubtopic((char *) topic);
  162. // Actions
  163. if (t.equals(MQTT_TOPIC_ACTION)) {
  164. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  165. customReset(CUSTOM_RESET_MQTT);
  166. ESP.restart();
  167. }
  168. }
  169. }
  170. }
  171. void _mqttOnConnect() {
  172. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  173. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MIN;
  174. #if MQTT_SKIP_RETAINED
  175. _mqtt_connected_at = millis();
  176. #endif
  177. // Send first Heartbeat
  178. heartbeat();
  179. // Send connect event to subscribers
  180. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  181. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  182. }
  183. }
  184. void _mqttOnDisconnect() {
  185. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  186. // Send disconnect event to subscribers
  187. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  188. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  189. }
  190. }
  191. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  192. if (len == 0) return;
  193. char message[len + 1];
  194. strlcpy(message, (char *) payload, len + 1);
  195. #if MQTT_SKIP_RETAINED
  196. if (millis() - _mqtt_connected_at < MQTT_SKIP_TIME) {
  197. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  198. return;
  199. }
  200. #endif
  201. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  202. // Send message event to subscribers
  203. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  204. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  205. }
  206. }
  207. #if MQTT_USE_ASYNC
  208. bool mqttFormatFP(const char * fingerprint, unsigned char * bytearray) {
  209. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  210. if (strlen(fingerprint) != 59) return false;
  211. DEBUG_MSG_P(PSTR("[MQTT] Fingerprint %s\n"), fingerprint);
  212. // walk the fingerprint
  213. for (unsigned int i=0; i<20; i++) {
  214. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  215. }
  216. return true;
  217. }
  218. #else
  219. bool mqttFormatFP(const char * fingerprint, char * destination) {
  220. // check length (20 2-character digits ':' or ' ' separated => 20*2+19 = 59)
  221. if (strlen(fingerprint) != 59) return false;
  222. DEBUG_MSG_P(PSTR("[MQTT] Fingerprint %s\n"), fingerprint);
  223. // copy it
  224. strncpy(destination, fingerprint, 59);
  225. // walk the fingerprint replacing ':' for ' '
  226. for (unsigned char i = 0; i<59; i++) {
  227. if (destination[i] == ':') destination[i] = ' ';
  228. }
  229. return true;
  230. }
  231. #endif
  232. void mqttEnabled(bool status) {
  233. _mqtt_enabled = status;
  234. setSetting("mqttEnabled", status ? 1 : 0);
  235. }
  236. bool mqttEnabled() {
  237. return _mqtt_enabled;
  238. }
  239. void mqttConnect() {
  240. // Do not connect if disabled
  241. if (!_mqtt_enabled) return;
  242. // Do not connect if already connected
  243. if (_mqtt.connected()) return;
  244. // Check reconnect interval
  245. static unsigned long last = 0;
  246. if (millis() - last < _mqtt_reconnect_delay) return;
  247. last = millis();
  248. // Increase the reconnect delay
  249. _mqtt_reconnect_delay += MQTT_RECONNECT_DELAY_STEP;
  250. if (_mqtt_reconnect_delay > MQTT_RECONNECT_DELAY_MAX) {
  251. _mqtt_reconnect_delay = MQTT_RECONNECT_DELAY_MAX;
  252. }
  253. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  254. if (strlen(host) == 0) return;
  255. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  256. if (_mqtt_user) free(_mqtt_user);
  257. if (_mqtt_pass) free(_mqtt_pass);
  258. if (_mqtt_will) free(_mqtt_will);
  259. _mqtt_user = strdup(getSetting("mqttUser", MQTT_USER).c_str());
  260. _mqtt_pass = strdup(getSetting("mqttPassword", MQTT_PASS).c_str());
  261. _mqtt_will = strdup((_mqtt_topic + MQTT_TOPIC_STATUS).c_str());
  262. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d\n"), host, port);
  263. #if MQTT_USE_ASYNC
  264. _mqtt.setServer(host, port);
  265. _mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  266. _mqtt.setWill(_mqtt_will, MQTT_QOS, MQTT_RETAIN, "0");
  267. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  268. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  269. _mqtt.setCredentials(_mqtt_user, _mqtt_pass);
  270. }
  271. #if ASYNC_TCP_SSL_ENABLED
  272. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  273. _mqtt.setSecure(secure);
  274. if (secure) {
  275. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  276. unsigned char fp[20] = {0};
  277. if (mqttFormatFP(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  278. _mqtt.addServerFingerprint(fp);
  279. } else {
  280. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  281. }
  282. }
  283. #endif // ASYNC_TCP_SSL_ENABLED
  284. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  285. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), MQTT_QOS);
  286. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), MQTT_RETAIN);
  287. _mqtt.connect();
  288. #else // not MQTT_USE_ASYNC
  289. bool response = true;
  290. #if ASYNC_TCP_SSL_ENABLED
  291. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  292. if (secure) {
  293. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  294. if (_mqtt_client_secure.connect(host, port)) {
  295. char fp[60] = {0};
  296. if (mqttFormatFP(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  297. if (_mqtt_client_secure.verify(fp, host)) {
  298. _mqtt.setClient(_mqtt_client_secure);
  299. } else {
  300. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  301. response = false;
  302. }
  303. _mqtt_client_secure.stop();
  304. yield();
  305. } else {
  306. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  307. response = false;
  308. }
  309. } else {
  310. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  311. response = false;
  312. }
  313. } else {
  314. _mqtt.setClient(_mqtt_client);
  315. }
  316. #else // not ASYNC_TCP_SSL_ENABLED
  317. _mqtt.setClient(_mqtt_client);
  318. #endif // ASYNC_TCP_SSL_ENABLED
  319. if (response) {
  320. _mqtt.setServer(host, port);
  321. if ((strlen(_mqtt_user) > 0) && (strlen(_mqtt_pass) > 0)) {
  322. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqtt_user);
  323. response = _mqtt.connect(getIdentifier().c_str(), _mqtt_user, _mqtt_pass, _mqtt_will, MQTT_QOS, MQTT_RETAIN, "0");
  324. } else {
  325. response = _mqtt.connect(getIdentifier().c_str(), _mqtt_will, MQTT_QOS, MQTT_RETAIN, "0");
  326. }
  327. DEBUG_MSG_P(PSTR("[MQTT] Will topic: %s\n"), _mqtt_will);
  328. DEBUG_MSG_P(PSTR("[MQTT] QoS: %d\n"), MQTT_QOS);
  329. DEBUG_MSG_P(PSTR("[MQTT] Retain flag: %d\n"), MQTT_RETAIN);
  330. }
  331. if (response) {
  332. _mqttOnConnect();
  333. } else {
  334. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  335. }
  336. #endif // MQTT_USE_ASYNC
  337. free(host);
  338. }
  339. void mqttConfigure() {
  340. // Replace identifier
  341. _mqtt_topic = getSetting("mqttTopic", MQTT_TOPIC);
  342. _mqtt_topic.replace("{identifier}", getSetting("hostname"));
  343. if (!_mqtt_topic.endsWith("/")) _mqtt_topic = _mqtt_topic + "/";
  344. // Getters and setters
  345. _mqtt_setter = getSetting("mqttSetter", MQTT_USE_SETTER);
  346. _mqtt_getter = getSetting("mqttGetter", MQTT_USE_GETTER);
  347. _mqtt_forward = !_mqtt_getter.equals(_mqtt_setter);
  348. // Enable
  349. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) {
  350. mqttEnabled(false);
  351. } else {
  352. _mqtt_enabled = getSetting("mqttEnabled", MQTT_ENABLED).toInt() == 1;
  353. }
  354. _mqtt_use_json = (getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1);
  355. }
  356. #if MDNS_SUPPORT
  357. boolean mqttDiscover() {
  358. int count = MDNS.queryService("mqtt", "tcp");
  359. DEBUG_MSG_P("[MQTT] MQTT brokers found: %d\n", count);
  360. for (int i=0; i<count; i++) {
  361. DEBUG_MSG_P("[MQTT] Broker at %s:%d\n", MDNS.IP(i).toString().c_str(), MDNS.port(i));
  362. if ((i==0) && (getSetting("mqttServer").length() == 0)) {
  363. setSetting("mqttServer", MDNS.IP(i).toString());
  364. setSetting("mqttPort", MDNS.port(i));
  365. mqttEnabled(MQTT_AUTOCONNECT);
  366. }
  367. }
  368. }
  369. #endif // MDNS_SUPPORT
  370. void mqttSetup() {
  371. DEBUG_MSG_P(PSTR("[MQTT] MQTT_USE_ASYNC = %d\n"), MQTT_USE_ASYNC);
  372. DEBUG_MSG_P(PSTR("[MQTT] MQTT_AUTOCONNECT = %d\n"), MQTT_AUTOCONNECT);
  373. #if MQTT_USE_ASYNC
  374. _mqtt.onConnect([](bool sessionPresent) {
  375. _mqttOnConnect();
  376. });
  377. _mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  378. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  379. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  380. }
  381. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  382. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  383. }
  384. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  385. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  386. }
  387. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  388. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  389. }
  390. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  391. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  392. }
  393. #if ASYNC_TCP_SSL_ENABLED
  394. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  395. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  396. }
  397. #endif
  398. _mqttOnDisconnect();
  399. });
  400. _mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  401. _mqttOnMessage(topic, payload, len);
  402. });
  403. _mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  404. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  405. });
  406. _mqtt.onPublish([](uint16_t packetId) {
  407. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  408. });
  409. #else // not MQTT_USE_ASYNC
  410. DEBUG_MSG_P(PSTR("[MQTT] Using SYNC MQTT library\n"));
  411. _mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  412. _mqttOnMessage(topic, (char *) payload, length);
  413. });
  414. #endif // MQTT_USE_ASYNC
  415. mqttConfigure();
  416. mqttRegister(_mqttCallback);
  417. }
  418. void mqttLoop() {
  419. if (WiFi.status() != WL_CONNECTED) return;
  420. #if MQTT_USE_ASYNC
  421. mqttConnect();
  422. #else // not MQTT_USE_ASYNC
  423. if (_mqtt.connected()) {
  424. _mqtt.loop();
  425. } else {
  426. if (_mqtt_connected) {
  427. _mqttOnDisconnect();
  428. _mqtt_connected = false;
  429. }
  430. mqttConnect();
  431. }
  432. #endif
  433. }