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.

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