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.

514 lines
15 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 <ArduinoJson.h>
  7. #include <vector>
  8. #include <Ticker.h>
  9. const char *mqtt_user = 0;
  10. const char *mqtt_pass = 0;
  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 _mqttConnected = false;
  18. WiFiClient _mqttClient;
  19. #if ASYNC_TCP_SSL_ENABLED
  20. WiFiClientSecure _mqttClientSecure;
  21. #endif
  22. #endif
  23. String _mqttTopic;
  24. String _mqttSetter;
  25. String _mqttGetter;
  26. bool _mqttForward;
  27. char *_mqttUser = 0;
  28. char *_mqttPass = 0;
  29. char *_mqttWill;
  30. std::vector<void (*)(unsigned int, const char *, const char *)> _mqtt_callbacks;
  31. #if MQTT_SKIP_RETAINED
  32. unsigned long mqttConnectedAt = 0;
  33. #endif
  34. typedef struct {
  35. char * topic;
  36. char * message;
  37. } mqtt_message_t;
  38. std::vector<mqtt_message_t> _mqtt_queue;
  39. Ticker mqttFlushTicker;
  40. // -----------------------------------------------------------------------------
  41. // Public API
  42. // -----------------------------------------------------------------------------
  43. bool mqttConnected() {
  44. return mqtt.connected();
  45. }
  46. void mqttDisconnect() {
  47. mqtt.disconnect();
  48. }
  49. bool mqttForward() {
  50. return _mqttForward;
  51. }
  52. String mqttSubtopic(char * topic) {
  53. String response;
  54. String t = String(topic);
  55. if (t.startsWith(_mqttTopic) && t.endsWith(_mqttSetter)) {
  56. response = t.substring(_mqttTopic.length(), t.length() - _mqttSetter.length());
  57. }
  58. return response;
  59. }
  60. void mqttSendRaw(const char * topic, const char * message) {
  61. if (mqtt.connected()) {
  62. #if MQTT_USE_ASYNC
  63. unsigned int packetId = mqtt.publish(topic, MQTT_QOS, MQTT_RETAIN, message);
  64. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %d)\n"), topic, message, packetId);
  65. #else
  66. mqtt.publish(topic, message, MQTT_RETAIN);
  67. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  68. #endif
  69. }
  70. }
  71. void _mqttFlush() {
  72. if (_mqtt_queue.size() == 0) return;
  73. DynamicJsonBuffer jsonBuffer;
  74. JsonObject& root = jsonBuffer.createObject();
  75. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  76. mqtt_message_t element = _mqtt_queue[i];
  77. root[element.topic] = element.message;
  78. }
  79. #if NTP_SUPPORT
  80. if (ntpConnected()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  81. #endif
  82. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  83. root[MQTT_TOPIC_IP] = getIP();
  84. String output;
  85. root.printTo(output);
  86. String path = _mqttTopic + String(MQTT_TOPIC_JSON);
  87. mqttSendRaw(path.c_str(), output.c_str());
  88. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  89. mqtt_message_t element = _mqtt_queue[i];
  90. free(element.topic);
  91. free(element.message);
  92. }
  93. _mqtt_queue.clear();
  94. }
  95. void mqttSend(const char * topic, const char * message, bool force) {
  96. bool useJson = force ? false : getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  97. if (useJson) {
  98. mqtt_message_t element;
  99. element.topic = strdup(topic);
  100. element.message = strdup(message);
  101. _mqtt_queue.push_back(element);
  102. mqttFlushTicker.once_ms(MQTT_USE_JSON_DELAY, _mqttFlush);
  103. } else {
  104. String path = _mqttTopic + String(topic) + _mqttGetter;
  105. mqttSendRaw(path.c_str(), message);
  106. }
  107. }
  108. void mqttSend(const char * topic, const char * message) {
  109. mqttSend(topic, message, false);
  110. }
  111. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  112. char buffer[strlen(topic)+5];
  113. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  114. mqttSend(buffer, message, force);
  115. }
  116. void mqttSend(const char * topic, unsigned int index, const char * message) {
  117. mqttSend(topic, index, message, false);
  118. }
  119. void mqttSubscribeRaw(const char * topic) {
  120. if (mqtt.connected() && (strlen(topic) > 0)) {
  121. #if MQTT_USE_ASYNC
  122. unsigned int packetId = mqtt.subscribe(topic, MQTT_QOS);
  123. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  124. #else
  125. mqtt.subscribe(topic, MQTT_QOS);
  126. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  127. #endif
  128. }
  129. }
  130. void mqttSubscribe(const char * topic) {
  131. String path = _mqttTopic + String(topic) + _mqttSetter;
  132. mqttSubscribeRaw(path.c_str());
  133. }
  134. void mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  135. _mqtt_callbacks.push_back(callback);
  136. }
  137. // -----------------------------------------------------------------------------
  138. // Callbacks
  139. // -----------------------------------------------------------------------------
  140. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  141. if (type == MQTT_CONNECT_EVENT) {
  142. mqttSubscribe(MQTT_TOPIC_ACTION);
  143. }
  144. if (type == MQTT_MESSAGE_EVENT) {
  145. // Match topic
  146. String t = mqttSubtopic((char *) topic);
  147. // Actions
  148. if (t.equals(MQTT_TOPIC_ACTION)) {
  149. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  150. customReset(CUSTOM_RESET_MQTT);
  151. ESP.restart();
  152. }
  153. }
  154. }
  155. }
  156. void _mqttOnConnect() {
  157. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  158. #if MQTT_SKIP_RETAINED
  159. mqttConnectedAt = millis();
  160. #endif
  161. // Build MQTT topics
  162. mqttConfigure();
  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 mqttConnect() {
  219. if (!mqtt.connected()) {
  220. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) return;
  221. // Last option: reconnect to wifi after MQTT_MAX_TRIES attemps in a row
  222. #if MQTT_MAX_TRIES > 0
  223. static unsigned int tries = 0;
  224. static unsigned long last_try = millis();
  225. if (millis() - last_try < MQTT_TRY_INTERVAL) {
  226. if (++tries > MQTT_MAX_TRIES) {
  227. DEBUG_MSG_P(PSTR("[MQTT] MQTT_MAX_TRIES met, disconnecting from WiFi\n"));
  228. wifiDisconnect();
  229. tries = 0;
  230. return;
  231. }
  232. } else {
  233. tries = 0;
  234. }
  235. last_try = millis();
  236. #endif
  237. if (_mqttUser) free(_mqttUser);
  238. if (_mqttPass) free(_mqttPass);
  239. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  240. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  241. _mqttUser = strdup(getSetting("mqttUser").c_str());
  242. _mqttPass = strdup(getSetting("mqttPassword").c_str());
  243. if (_mqttWill) free(_mqttWill);
  244. _mqttWill = strdup((_mqttTopic + MQTT_TOPIC_STATUS).c_str());
  245. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d\n"), host, port);
  246. #if MQTT_USE_ASYNC
  247. mqtt.setServer(host, port);
  248. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  249. mqtt.setWill(_mqttWill, MQTT_QOS, MQTT_RETAIN, "0");
  250. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  251. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqttUser);
  252. mqtt.setCredentials(_mqttUser, _mqttPass);
  253. }
  254. #if ASYNC_TCP_SSL_ENABLED
  255. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  256. mqtt.setSecure(secure);
  257. if (secure) {
  258. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  259. unsigned char fp[20] = {0};
  260. if (mqttFormatFP(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  261. mqtt.addServerFingerprint(fp);
  262. } else {
  263. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  264. }
  265. }
  266. #endif // ASYNC_TCP_SSL_ENABLED
  267. mqtt.connect();
  268. #else // not MQTT_USE_ASYNC
  269. bool response = true;
  270. #if ASYNC_TCP_SSL_ENABLED
  271. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  272. if (secure) {
  273. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  274. if (_mqttClientSecure.connect(host, port)) {
  275. char fp[60] = {0};
  276. if (mqttFormatFP(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  277. Serial.println(fp);
  278. Serial.println(strlen(fp));
  279. if (_mqttClientSecure.verify(fp, host)) {
  280. mqtt.setClient(_mqttClientSecure);
  281. } else {
  282. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  283. response = false;
  284. }
  285. } else {
  286. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  287. response = false;
  288. }
  289. } else {
  290. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  291. response = false;
  292. }
  293. } else {
  294. mqtt.setClient(_mqttClient);
  295. }
  296. #else // not ASYNC_TCP_SSL_ENABLED
  297. mqtt.setClient(_mqttClient);
  298. #endif // ASYNC_TCP_SSL_ENABLED
  299. if (response) {
  300. mqtt.setServer(host, port);
  301. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  302. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqttUser);
  303. response = mqtt.connect(getIdentifier().c_str(), _mqttUser, _mqttPass, _mqttWill, MQTT_QOS, MQTT_RETAIN, "0");
  304. } else {
  305. response = mqtt.connect(getIdentifier().c_str(), _mqttWill, MQTT_QOS, MQTT_RETAIN, "0");
  306. }
  307. }
  308. if (response) {
  309. _mqttOnConnect();
  310. _mqttConnected = true;
  311. } else {
  312. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  313. }
  314. #endif // MQTT_USE_ASYNC
  315. free(host);
  316. }
  317. }
  318. void mqttConfigure() {
  319. // Replace identifier
  320. _mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  321. _mqttTopic.replace("{identifier}", getSetting("hostname"));
  322. if (!_mqttTopic.endsWith("/")) _mqttTopic = _mqttTopic + "/";
  323. _mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  324. _mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  325. _mqttForward = !_mqttGetter.equals(_mqttSetter);
  326. }
  327. void mqttSetup() {
  328. #if MQTT_USE_ASYNC
  329. mqtt.onConnect([](bool sessionPresent) {
  330. _mqttOnConnect();
  331. });
  332. mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  333. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  334. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  335. }
  336. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  337. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  338. }
  339. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  340. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  341. }
  342. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  343. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  344. }
  345. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  346. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  347. }
  348. #if ASYNC_TCP_SSL_ENABLED
  349. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  350. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  351. }
  352. #endif
  353. _mqttOnDisconnect();
  354. });
  355. mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  356. _mqttOnMessage(topic, payload, len);
  357. });
  358. mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  359. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  360. });
  361. mqtt.onPublish([](uint16_t packetId) {
  362. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  363. });
  364. #else
  365. mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  366. _mqttOnMessage(topic, (char *) payload, length);
  367. });
  368. #endif
  369. mqttRegister(_mqttCallback);
  370. }
  371. void mqttLoop() {
  372. static unsigned long lastPeriod = 0;
  373. if (WiFi.status() == WL_CONNECTED) {
  374. if (!mqtt.connected()) {
  375. #if not MQTT_USE_ASYNC
  376. if (_mqttConnected) {
  377. _mqttOnDisconnect();
  378. _mqttConnected = false;
  379. }
  380. #endif
  381. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  382. if (currPeriod != lastPeriod) {
  383. lastPeriod = currPeriod;
  384. mqttConnect();
  385. }
  386. #if not MQTT_USE_ASYNC
  387. } else {
  388. mqtt.loop();
  389. #endif
  390. }
  391. }
  392. }