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.

512 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. if (mqtt.connected()) 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. if (_mqttClientSecure.verify(fp, host)) {
  278. mqtt.setClient(_mqttClientSecure);
  279. } else {
  280. DEBUG_MSG_P(PSTR("[MQTT] Invalid fingerprint\n"));
  281. response = false;
  282. }
  283. } else {
  284. DEBUG_MSG_P(PSTR("[MQTT] Wrong fingerprint\n"));
  285. response = false;
  286. }
  287. } else {
  288. DEBUG_MSG_P(PSTR("[MQTT] Client connection failed\n"));
  289. response = false;
  290. }
  291. } else {
  292. mqtt.setClient(_mqttClient);
  293. }
  294. #else // not ASYNC_TCP_SSL_ENABLED
  295. mqtt.setClient(_mqttClient);
  296. #endif // ASYNC_TCP_SSL_ENABLED
  297. if (response) {
  298. mqtt.setServer(host, port);
  299. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  300. DEBUG_MSG_P(PSTR("[MQTT] Connecting as user %s\n"), _mqttUser);
  301. response = mqtt.connect(getIdentifier().c_str(), _mqttUser, _mqttPass, _mqttWill, MQTT_QOS, MQTT_RETAIN, "0");
  302. } else {
  303. response = mqtt.connect(getIdentifier().c_str(), _mqttWill, MQTT_QOS, MQTT_RETAIN, "0");
  304. }
  305. }
  306. if (response) {
  307. _mqttOnConnect();
  308. _mqttConnected = true;
  309. } else {
  310. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  311. }
  312. #endif // MQTT_USE_ASYNC
  313. free(host);
  314. }
  315. }
  316. void mqttConfigure() {
  317. // Replace identifier
  318. _mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  319. _mqttTopic.replace("{identifier}", getSetting("hostname"));
  320. if (!_mqttTopic.endsWith("/")) _mqttTopic = _mqttTopic + "/";
  321. _mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  322. _mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  323. _mqttForward = !_mqttGetter.equals(_mqttSetter);
  324. }
  325. void mqttSetup() {
  326. #if MQTT_USE_ASYNC
  327. mqtt.onConnect([](bool sessionPresent) {
  328. _mqttOnConnect();
  329. });
  330. mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  331. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  332. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  333. }
  334. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  335. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  336. }
  337. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  338. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  339. }
  340. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  341. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  342. }
  343. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  344. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  345. }
  346. #if ASYNC_TCP_SSL_ENABLED
  347. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  348. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  349. }
  350. #endif
  351. _mqttOnDisconnect();
  352. });
  353. mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  354. _mqttOnMessage(topic, payload, len);
  355. });
  356. mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  357. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  358. });
  359. mqtt.onPublish([](uint16_t packetId) {
  360. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  361. });
  362. #else
  363. mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  364. _mqttOnMessage(topic, (char *) payload, length);
  365. });
  366. #endif
  367. mqttRegister(_mqttCallback);
  368. }
  369. void mqttLoop() {
  370. static unsigned long lastPeriod = 0;
  371. if (WiFi.status() == WL_CONNECTED) {
  372. if (!mqtt.connected()) {
  373. #if not MQTT_USE_ASYNC
  374. if (_mqttConnected) {
  375. _mqttOnDisconnect();
  376. _mqttConnected = false;
  377. }
  378. #endif
  379. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  380. if (currPeriod != lastPeriod) {
  381. lastPeriod = currPeriod;
  382. mqttConnect();
  383. }
  384. #if not MQTT_USE_ASYNC
  385. } else {
  386. mqtt.loop();
  387. #endif
  388. }
  389. }
  390. }