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.

551 lines
16 KiB

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