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.

439 lines
13 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
  12. #include <AsyncMqttClient.h>
  13. AsyncMqttClient mqtt;
  14. #else
  15. #include <PubSubClient.h>
  16. WiFiClient mqttWiFiClient;
  17. PubSubClient mqtt(mqttWiFiClient);
  18. bool _mqttConnected = false;
  19. #endif
  20. String _mqttTopic;
  21. String _mqttSetter;
  22. String _mqttGetter;
  23. bool _mqttForward;
  24. char *_mqttUser = 0;
  25. char *_mqttPass = 0;
  26. char *_mqttWill;
  27. std::vector<void (*)(unsigned int, const char *, const char *)> _mqtt_callbacks;
  28. #if MQTT_SKIP_RETAINED
  29. unsigned long mqttConnectedAt = 0;
  30. #endif
  31. typedef struct {
  32. char * topic;
  33. char * message;
  34. } mqtt_message_t;
  35. std::vector<mqtt_message_t> _mqtt_queue;
  36. Ticker mqttFlushTicker;
  37. // -----------------------------------------------------------------------------
  38. // Public API
  39. // -----------------------------------------------------------------------------
  40. bool mqttConnected() {
  41. return mqtt.connected();
  42. }
  43. void mqttDisconnect() {
  44. mqtt.disconnect();
  45. }
  46. bool mqttForward() {
  47. return _mqttForward;
  48. }
  49. String mqttSubtopic(char * topic) {
  50. String response;
  51. String t = String(topic);
  52. if (t.startsWith(_mqttTopic) && t.endsWith(_mqttSetter)) {
  53. response = t.substring(_mqttTopic.length(), t.length() - _mqttSetter.length());
  54. }
  55. return response;
  56. }
  57. void mqttSendRaw(const char * topic, const char * message) {
  58. if (mqtt.connected()) {
  59. #if MQTT_USE_ASYNC
  60. unsigned int packetId = mqtt.publish(topic, MQTT_QOS, MQTT_RETAIN, message);
  61. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s (PID %d)\n"), topic, message, packetId);
  62. #else
  63. mqtt.publish(topic, message, MQTT_RETAIN);
  64. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  65. #endif
  66. }
  67. }
  68. void _mqttFlush() {
  69. if (_mqtt_queue.size() == 0) return;
  70. DynamicJsonBuffer jsonBuffer;
  71. JsonObject& root = jsonBuffer.createObject();
  72. for (unsigned char i=0; i<_mqtt_queue.size(); i++) {
  73. mqtt_message_t element = _mqtt_queue[i];
  74. root[element.topic] = element.message;
  75. }
  76. #if NTP_SUPPORT
  77. if (ntpConnected()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  78. #endif
  79. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname");
  80. root[MQTT_TOPIC_IP] = getIP();
  81. String output;
  82. root.printTo(output);
  83. String path = _mqttTopic + String(MQTT_TOPIC_JSON);
  84. mqttSendRaw(path.c_str(), output.c_str());
  85. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  86. mqtt_message_t element = _mqtt_queue[i];
  87. free(element.topic);
  88. free(element.message);
  89. }
  90. _mqtt_queue.clear();
  91. }
  92. void mqttSend(const char * topic, const char * message, bool force) {
  93. bool useJson = force ? false : getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  94. if (useJson) {
  95. mqtt_message_t element;
  96. element.topic = strdup(topic);
  97. element.message = strdup(message);
  98. _mqtt_queue.push_back(element);
  99. mqttFlushTicker.once_ms(MQTT_USE_JSON_DELAY, _mqttFlush);
  100. } else {
  101. String path = _mqttTopic + String(topic) + _mqttGetter;
  102. mqttSendRaw(path.c_str(), message);
  103. }
  104. }
  105. void mqttSend(const char * topic, const char * message) {
  106. mqttSend(topic, message, false);
  107. }
  108. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  109. char buffer[strlen(topic)+5];
  110. snprintf_P(buffer, sizeof(buffer), PSTR("%s/%d"), topic, index);
  111. mqttSend(buffer, message, force);
  112. }
  113. void mqttSend(const char * topic, unsigned int index, const char * message) {
  114. mqttSend(topic, index, message, false);
  115. }
  116. void mqttSubscribeRaw(const char * topic) {
  117. if (mqtt.connected() && (strlen(topic) > 0)) {
  118. #if MQTT_USE_ASYNC
  119. unsigned int packetId = mqtt.subscribe(topic, MQTT_QOS);
  120. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s (PID %d)\n"), topic, packetId);
  121. #else
  122. mqtt.subscribe(topic, MQTT_QOS);
  123. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  124. #endif
  125. }
  126. }
  127. void mqttSubscribe(const char * topic) {
  128. String path = _mqttTopic + String(topic) + _mqttSetter;
  129. mqttSubscribeRaw(path.c_str());
  130. }
  131. void mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  132. _mqtt_callbacks.push_back(callback);
  133. }
  134. // -----------------------------------------------------------------------------
  135. // Callbacks
  136. // -----------------------------------------------------------------------------
  137. void _mqttCallback(unsigned int type, const char * topic, const char * payload) {
  138. if (type == MQTT_CONNECT_EVENT) {
  139. mqttSubscribe(MQTT_TOPIC_ACTION);
  140. }
  141. if (type == MQTT_MESSAGE_EVENT) {
  142. // Match topic
  143. String t = mqttSubtopic((char *) topic);
  144. // Actions
  145. if (t.equals(MQTT_TOPIC_ACTION)) {
  146. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  147. customReset(CUSTOM_RESET_MQTT);
  148. ESP.restart();
  149. }
  150. }
  151. }
  152. }
  153. void _mqttOnConnect() {
  154. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  155. #if MQTT_SKIP_RETAINED
  156. mqttConnectedAt = millis();
  157. #endif
  158. // Build MQTT topics
  159. mqttConfigure();
  160. // Send first Heartbeat
  161. heartbeat();
  162. // Send connect event to subscribers
  163. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  164. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  165. }
  166. }
  167. void _mqttOnDisconnect() {
  168. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  169. // Send disconnect event to subscribers
  170. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  171. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  172. }
  173. }
  174. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  175. if (len == 0) return;
  176. char message[len + 1];
  177. strlcpy(message, (char *) payload, len + 1);
  178. #if MQTT_SKIP_RETAINED
  179. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  180. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s - SKIPPED\n"), topic, message);
  181. return;
  182. }
  183. #endif
  184. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s\n"), topic, message);
  185. // Send message event to subscribers
  186. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  187. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  188. }
  189. }
  190. bool fp2array(const char * fingerprint, unsigned char * bytearray) {
  191. // check length (20 2-character digits ':'-separated => 20*2+19 = 59)
  192. if (strlen(fingerprint) != 59) return false;
  193. DEBUG_MSG_P(PSTR("[MQTT] Fingerprint %s\n"), fingerprint);
  194. // walk the fingerprint
  195. for (unsigned int i=0; i<20; i++) {
  196. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  197. }
  198. return true;
  199. }
  200. void mqttConnect() {
  201. if (!mqtt.connected()) {
  202. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) return;
  203. // Last option: reconnect to wifi after MQTT_MAX_TRIES attemps in a row
  204. #if MQTT_MAX_TRIES > 0
  205. static unsigned int tries = 0;
  206. static unsigned long last_try = millis();
  207. if (millis() - last_try < MQTT_TRY_INTERVAL) {
  208. if (++tries > MQTT_MAX_TRIES) {
  209. DEBUG_MSG_P(PSTR("[MQTT] MQTT_MAX_TRIES met, disconnecting from WiFi\n"));
  210. wifiDisconnect();
  211. tries = 0;
  212. return;
  213. }
  214. } else {
  215. tries = 0;
  216. }
  217. last_try = millis();
  218. #endif
  219. mqtt.disconnect();
  220. if (_mqttUser) free(_mqttUser);
  221. if (_mqttPass) free(_mqttPass);
  222. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  223. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  224. _mqttUser = strdup(getSetting("mqttUser").c_str());
  225. _mqttPass = strdup(getSetting("mqttPassword").c_str());
  226. if (_mqttWill) free(_mqttWill);
  227. _mqttWill = strdup((_mqttTopic + MQTT_TOPIC_STATUS).c_str());
  228. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d"), host, port);
  229. mqtt.setServer(host, port);
  230. #if MQTT_USE_ASYNC
  231. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  232. mqtt.setWill(_mqttWill, MQTT_QOS, MQTT_RETAIN, "0");
  233. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  234. DEBUG_MSG_P(PSTR(" as user '%s'."), _mqttUser);
  235. mqtt.setCredentials(_mqttUser, _mqttPass);
  236. }
  237. DEBUG_MSG_P(PSTR("\n"));
  238. #if ASYNC_TCP_SSL_ENABLED
  239. bool secure = getSetting("mqttUseSSL", MQTT_SSL_ENABLED).toInt() == 1;
  240. mqtt.setSecure(secure);
  241. if (secure) {
  242. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  243. unsigned char fp[20];
  244. if (fp2array(getSetting("mqttFP", MQTT_SSL_FINGERPRINT).c_str(), fp)) {
  245. mqtt.addServerFingerprint(fp);
  246. }
  247. }
  248. #endif
  249. mqtt.connect();
  250. #else
  251. bool response;
  252. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  253. DEBUG_MSG_P(PSTR(" as user '%s'\n"), _mqttUser);
  254. response = mqtt.connect(getIdentifier().c_str(), _mqttUser, _mqttPass, _mqttWill, MQTT_QOS, MQTT_RETAIN, "0");
  255. } else {
  256. DEBUG_MSG_P(PSTR("\n"));
  257. response = mqtt.connect(getIdentifier().c_str(), _mqttWill, MQTT_QOS, MQTT_RETAIN, "0");
  258. }
  259. if (response) {
  260. _mqttOnConnect();
  261. _mqttConnected = true;
  262. } else {
  263. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  264. }
  265. #endif
  266. free(host);
  267. }
  268. }
  269. void mqttConfigure() {
  270. // Replace identifier
  271. _mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  272. _mqttTopic.replace("{identifier}", getSetting("hostname"));
  273. if (!_mqttTopic.endsWith("/")) _mqttTopic = _mqttTopic + "/";
  274. _mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  275. _mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  276. _mqttForward = !_mqttGetter.equals(_mqttSetter);
  277. }
  278. void mqttSetup() {
  279. #if MQTT_USE_ASYNC
  280. mqtt.onConnect([](bool sessionPresent) {
  281. _mqttOnConnect();
  282. });
  283. mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  284. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  285. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  286. }
  287. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  288. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  289. }
  290. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  291. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  292. }
  293. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  294. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  295. }
  296. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  297. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  298. }
  299. #if ASYNC_TCP_SSL_ENABLED
  300. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  301. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  302. }
  303. #endif
  304. _mqttOnDisconnect();
  305. });
  306. mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  307. _mqttOnMessage(topic, payload, len);
  308. });
  309. mqtt.onSubscribe([](uint16_t packetId, uint8_t qos) {
  310. DEBUG_MSG_P(PSTR("[MQTT] Subscribe ACK for PID %d\n"), packetId);
  311. });
  312. mqtt.onPublish([](uint16_t packetId) {
  313. DEBUG_MSG_P(PSTR("[MQTT] Publish ACK for PID %d\n"), packetId);
  314. });
  315. #else
  316. mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  317. _mqttOnMessage(topic, (char *) payload, length);
  318. });
  319. #endif
  320. mqttRegister(_mqttCallback);
  321. }
  322. void mqttLoop() {
  323. static unsigned long lastPeriod = 0;
  324. if (WiFi.status() == WL_CONNECTED) {
  325. if (!mqtt.connected()) {
  326. #if not MQTT_USE_ASYNC
  327. if (_mqttConnected) {
  328. _mqttOnDisconnect();
  329. _mqttConnected = false;
  330. }
  331. #endif
  332. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  333. if (currPeriod != lastPeriod) {
  334. lastPeriod = currPeriod;
  335. mqttConnect();
  336. }
  337. #if not MQTT_USE_ASYNC
  338. } else {
  339. mqtt.loop();
  340. #endif
  341. }
  342. }
  343. }