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.

357 lines
10 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 <vector>
  7. const char *mqtt_user = 0;
  8. const char *mqtt_pass = 0;
  9. #if MQTT_USE_ASYNC
  10. #include <AsyncMqttClient.h>
  11. AsyncMqttClient mqtt;
  12. #else
  13. #include <PubSubClient.h>
  14. WiFiClient mqttWiFiClient;
  15. PubSubClient mqtt(mqttWiFiClient);
  16. bool _mqttConnected = false;
  17. #endif
  18. String mqttTopic;
  19. bool _mqttForward;
  20. char *_mqttUser = 0;
  21. char *_mqttPass = 0;
  22. std::vector<void (*)(unsigned int, const char *, const char *)> _mqtt_callbacks;
  23. #if MQTT_SKIP_RETAINED
  24. unsigned long mqttConnectedAt = 0;
  25. #endif
  26. // -----------------------------------------------------------------------------
  27. // Public API
  28. // -----------------------------------------------------------------------------
  29. bool mqttConnected() {
  30. return mqtt.connected();
  31. }
  32. void mqttDisconnect() {
  33. mqtt.disconnect();
  34. }
  35. void buildTopics() {
  36. // Replace identifier
  37. mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  38. mqttTopic.replace("{identifier}", getSetting("hostname"));
  39. if (!mqttTopic.endsWith("/")) mqttTopic = mqttTopic + "/";
  40. }
  41. bool mqttForward() {
  42. return _mqttForward;
  43. }
  44. String mqttSubtopic(char * topic) {
  45. String response;
  46. String t = String(topic);
  47. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  48. if (t.startsWith(mqttTopic) && t.endsWith(mqttSetter)) {
  49. response = t.substring(mqttTopic.length(), t.length() - mqttSetter.length());
  50. }
  51. return response;
  52. }
  53. void mqttSendRaw(const char * topic, const char * message) {
  54. if (mqtt.connected()) {
  55. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  56. #if MQTT_USE_ASYNC
  57. mqtt.publish(topic, MQTT_QOS, MQTT_RETAIN, message);
  58. #else
  59. mqtt.publish(topic, message, MQTT_RETAIN);
  60. #endif
  61. }
  62. }
  63. void mqttSend(const char * topic, const char * message) {
  64. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  65. String path = mqttTopic + String(topic) + mqttGetter;
  66. mqttSendRaw(path.c_str(), message);
  67. }
  68. void mqttSend(const char * topic, unsigned int index, const char * message) {
  69. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  70. String path = mqttTopic + String(topic) + String ("/") + String(index) + mqttGetter;;
  71. mqttSendRaw(path.c_str(), message);
  72. }
  73. void mqttSubscribeRaw(const char * topic) {
  74. if (mqtt.connected() && (strlen(topic) > 0)) {
  75. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  76. mqtt.subscribe(topic, MQTT_QOS);
  77. }
  78. }
  79. void mqttSubscribe(const char * topic) {
  80. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  81. String path = mqttTopic + String(topic) + mqttSetter;
  82. mqttSubscribeRaw(path.c_str());
  83. }
  84. // -----------------------------------------------------------------------------
  85. // Callbacks
  86. // -----------------------------------------------------------------------------
  87. void mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  88. _mqtt_callbacks.push_back(callback);
  89. }
  90. void _mqttOnConnect() {
  91. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  92. #if MQTT_SKIP_RETAINED
  93. mqttConnectedAt = millis();
  94. #endif
  95. // Build MQTT topics
  96. buildTopics();
  97. // Send first Heartbeat
  98. heartbeat();
  99. // Subscribe to system topics
  100. mqttSubscribe(MQTT_TOPIC_ACTION);
  101. // Send connect event to subscribers
  102. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  103. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  104. }
  105. }
  106. void _mqttOnDisconnect() {
  107. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  108. // Send disconnect event to subscribers
  109. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  110. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  111. }
  112. }
  113. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  114. char message[len + 1];
  115. strlcpy(message, (char *) payload, len + 1);
  116. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s"), topic, message);
  117. #if MQTT_SKIP_RETAINED
  118. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  119. DEBUG_MSG_P(PSTR(" - SKIPPED\n"));
  120. return;
  121. }
  122. #endif
  123. DEBUG_MSG_P(PSTR("\n"));
  124. // Check system topics
  125. String t = mqttSubtopic((char *) topic);
  126. if (t.equals(MQTT_TOPIC_ACTION)) {
  127. if (strcmp(message, MQTT_ACTION_RESET) == 0) {
  128. customReset(CUSTOM_RESET_MQTT);
  129. ESP.restart();
  130. }
  131. }
  132. // Send message event to subscribers
  133. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  134. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  135. }
  136. }
  137. bool fp2array(const char * fingerprint, unsigned char * bytearray) {
  138. // check length (20 2-character digits ':'-separated => 20*2+19 = 59)
  139. if (strlen(fingerprint) != 59) return false;
  140. DEBUG_MSG_P(PSTR("[MQTT] Fingerprint %s\n"), fingerprint);
  141. // walk the fingerprint
  142. for (unsigned int i=0; i<20; i++) {
  143. bytearray[i] = strtol(fingerprint + 3*i, NULL, 16);
  144. }
  145. return true;
  146. }
  147. void mqttConnect() {
  148. if (!mqtt.connected()) {
  149. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) return;
  150. // Last option: reconnect to wifi after MQTT_MAX_TRIES attemps in a row
  151. #if MQTT_MAX_TRIES > 0
  152. static unsigned int tries = 0;
  153. static unsigned long last_try = millis();
  154. if (millis() - last_try < MQTT_TRY_INTERVAL) {
  155. if (++tries > MQTT_MAX_TRIES) {
  156. DEBUG_MSG_P(PSTR("[MQTT] MQTT_MAX_TRIES met, disconnecting from WiFi\n"));
  157. wifiDisconnect();
  158. tries = 0;
  159. return;
  160. }
  161. } else {
  162. tries = 0;
  163. }
  164. last_try = millis();
  165. #endif
  166. mqtt.disconnect();
  167. if (_mqttUser) free(_mqttUser);
  168. if (_mqttPass) free(_mqttPass);
  169. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  170. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  171. _mqttUser = strdup(getSetting("mqttUser").c_str());
  172. _mqttPass = strdup(getSetting("mqttPassword").c_str());
  173. char * will = strdup((mqttTopic + MQTT_TOPIC_STATUS).c_str());
  174. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d"), host, port);
  175. mqtt.setServer(host, port);
  176. #if MQTT_USE_ASYNC
  177. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  178. mqtt.setWill(will, MQTT_QOS, MQTT_RETAIN, "0");
  179. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  180. DEBUG_MSG_P(PSTR(" as user '%s'."), _mqttUser);
  181. mqtt.setCredentials(_mqttUser, _mqttPass);
  182. }
  183. DEBUG_MSG_P(PSTR("\n"));
  184. #if ASYNC_TCP_SSL_ENABLED
  185. bool secure = getSetting("mqttUseSSL", MQTT_USE_SSL).toInt() == 1;
  186. mqtt.setSecure(secure);
  187. if (secure) {
  188. DEBUG_MSG_P(PSTR("[MQTT] Using SSL\n"));
  189. unsigned char fp[20];
  190. if (fp2array(getSetting("mqttFP").c_str(), fp)) {
  191. mqtt.addServerFingerprint(fp);
  192. }
  193. }
  194. #endif
  195. mqtt.connect();
  196. #else
  197. bool response;
  198. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  199. DEBUG_MSG_P(PSTR(" as user '%s'\n"), _mqttUser);
  200. response = mqtt.connect(getIdentifier().c_str(), _mqttUser, _mqttPass, will, MQTT_QOS, MQTT_RETAIN, "0");
  201. } else {
  202. DEBUG_MSG_P(PSTR("\n"));
  203. response = mqtt.connect(getIdentifier().c_str(), will, MQTT_QOS, MQTT_RETAIN, "0");
  204. }
  205. if (response) {
  206. _mqttOnConnect();
  207. _mqttConnected = true;
  208. } else {
  209. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  210. }
  211. #endif
  212. free(host);
  213. free(will);
  214. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  215. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  216. _mqttForward = !mqttGetter.equals(mqttSetter);
  217. }
  218. }
  219. void mqttSetup() {
  220. #if MQTT_USE_ASYNC
  221. mqtt.onConnect([](bool sessionPresent) {
  222. _mqttOnConnect();
  223. });
  224. mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  225. if (reason == AsyncMqttClientDisconnectReason::TCP_DISCONNECTED) {
  226. DEBUG_MSG_P(PSTR("[MQTT] TCP Disconnected\n"));
  227. }
  228. if (reason == AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED) {
  229. DEBUG_MSG_P(PSTR("[MQTT] Identifier Rejected\n"));
  230. }
  231. if (reason == AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE) {
  232. DEBUG_MSG_P(PSTR("[MQTT] Server unavailable\n"));
  233. }
  234. if (reason == AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS) {
  235. DEBUG_MSG_P(PSTR("[MQTT] Malformed credentials\n"));
  236. }
  237. if (reason == AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED) {
  238. DEBUG_MSG_P(PSTR("[MQTT] Not authorized\n"));
  239. }
  240. if (reason == AsyncMqttClientDisconnectReason::TLS_BAD_FINGERPRINT) {
  241. DEBUG_MSG_P(PSTR("[MQTT] Bad fingerprint\n"));
  242. }
  243. _mqttOnDisconnect();
  244. });
  245. mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  246. _mqttOnMessage(topic, payload, len);
  247. });
  248. #else
  249. mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  250. _mqttOnMessage(topic, (char *) payload, length);
  251. });
  252. #endif
  253. buildTopics();
  254. }
  255. void mqttLoop() {
  256. static unsigned long lastPeriod = 0;
  257. if (WiFi.status() == WL_CONNECTED) {
  258. if (!mqtt.connected()) {
  259. #if not MQTT_USE_ASYNC
  260. if (_mqttConnected) {
  261. _mqttOnDisconnect();
  262. _mqttConnected = false;
  263. }
  264. #endif
  265. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  266. if (currPeriod != lastPeriod) {
  267. lastPeriod = currPeriod;
  268. mqttConnect();
  269. }
  270. #if not MQTT_USE_ASYNC
  271. } else {
  272. mqtt.loop();
  273. #endif
  274. }
  275. }
  276. }