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.

305 lines
8.3 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. std::vector<void (*)(unsigned int, const char *, const char *)> _mqtt_callbacks;
  21. #if MQTT_SKIP_RETAINED
  22. unsigned long mqttConnectedAt = 0;
  23. #endif
  24. // -----------------------------------------------------------------------------
  25. // Public API
  26. // -----------------------------------------------------------------------------
  27. bool mqttConnected() {
  28. return mqtt.connected();
  29. }
  30. void mqttDisconnect() {
  31. mqtt.disconnect();
  32. }
  33. void buildTopics() {
  34. // Replace identifier
  35. mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  36. mqttTopic.replace("{identifier}", getSetting("hostname"));
  37. }
  38. bool mqttForward() {
  39. return _mqttForward;
  40. }
  41. String mqttSubtopic(char * topic) {
  42. String response;
  43. String t = String(topic);
  44. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  45. if (t.startsWith(mqttTopic) && t.endsWith(mqttSetter)) {
  46. response = t.substring(mqttTopic.length(), t.length() - mqttSetter.length());
  47. }
  48. return response;
  49. }
  50. void mqttSendRaw(const char * topic, const char * message) {
  51. if (mqtt.connected()) {
  52. DEBUG_MSG("[MQTT] Sending %s => %s\n", topic, message);
  53. #if MQTT_USE_ASYNC
  54. mqtt.publish(topic, MQTT_QOS, MQTT_RETAIN, message);
  55. #else
  56. mqtt.publish(topic, message, MQTT_RETAIN);
  57. #endif
  58. }
  59. }
  60. void mqttSend(const char * topic, const char * message) {
  61. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  62. String path = mqttTopic + String(topic) + mqttGetter;
  63. mqttSendRaw(path.c_str(), message);
  64. }
  65. void mqttSend(const char * topic, unsigned int index, const char * message) {
  66. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  67. String path = mqttTopic + String(topic) + String ("/") + String(index) + mqttGetter;;
  68. mqttSendRaw(path.c_str(), message);
  69. }
  70. void mqttSubscribeRaw(const char * topic) {
  71. if (mqtt.connected() && (strlen(topic) > 0)) {
  72. DEBUG_MSG("[MQTT] Subscribing to %s\n", topic);
  73. mqtt.subscribe(topic, MQTT_QOS);
  74. }
  75. }
  76. void mqttSubscribe(const char * topic) {
  77. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  78. String path = mqttTopic + String(topic) + mqttSetter;
  79. mqttSubscribeRaw(path.c_str());
  80. }
  81. // -----------------------------------------------------------------------------
  82. // Callbacks
  83. // -----------------------------------------------------------------------------
  84. void mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  85. _mqtt_callbacks.push_back(callback);
  86. }
  87. void _mqttOnConnect() {
  88. DEBUG_MSG("[MQTT] Connected!\n");
  89. #if MQTT_SKIP_RETAINED
  90. mqttConnectedAt = millis();
  91. #endif
  92. // Build MQTT topics
  93. buildTopics();
  94. // Say hello and report our IP and VERSION
  95. mqttSend(MQTT_IP_TOPIC, getIP().c_str());
  96. mqttSend(MQTT_VERSION_TOPIC, APP_VERSION);
  97. mqttSend(MQTT_STATUS_TOPIC, "1");
  98. // Subscribe to system topics
  99. mqttSubscribe(MQTT_ACTION_TOPIC);
  100. // Send connect event to subscribers
  101. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  102. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  103. }
  104. }
  105. void _mqttOnDisconnect() {
  106. DEBUG_MSG("[MQTT] Disconnected!\n");
  107. // Send disconnect event to subscribers
  108. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  109. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  110. }
  111. }
  112. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  113. char message[len + 1];
  114. strlcpy(message, (char *) payload, len + 1);
  115. DEBUG_MSG("[MQTT] Received %s => %s", topic, message);
  116. #if MQTT_SKIP_RETAINED
  117. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  118. DEBUG_MSG(" - SKIPPED\n");
  119. return;
  120. }
  121. #endif
  122. DEBUG_MSG("\n");
  123. // Check system topics
  124. String t = mqttSubtopic((char *) topic);
  125. if (t.equals(MQTT_ACTION_TOPIC)) {
  126. if (strcmp(message, MQTT_ACTION_RESET) == 0) {
  127. ESP.restart();
  128. }
  129. }
  130. // Send message event to subscribers
  131. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  132. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  133. }
  134. }
  135. void mqttConnect() {
  136. if (!mqtt.connected()) {
  137. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) return;
  138. // Last option: reconnect to wifi after MQTT_MAX_TRIES attemps in a row
  139. #if MQTT_MAX_TRIES > 0
  140. static unsigned int tries = 0;
  141. static unsigned long last_try = millis();
  142. if (millis() - last_try < MQTT_TRY_INTERVAL) {
  143. if (++tries > MQTT_MAX_TRIES) {
  144. DEBUG_MSG("[MQTT] MQTT_MAX_TRIES met, disconnecting from WiFi\n");
  145. wifiDisconnect();
  146. tries = 0;
  147. return;
  148. }
  149. } else {
  150. tries = 0;
  151. }
  152. last_try = millis();
  153. #endif
  154. mqtt.disconnect();
  155. if (mqtt_user) free(mqtt_user);
  156. if (mqtt_pass) free(mqtt_pass);
  157. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  158. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  159. mqtt_user = strdup(getSetting("mqttUser").c_str());
  160. mqtt_pass = strdup(getSetting("mqttPassword").c_str());
  161. DEBUG_MSG("[MQTT] Connecting to broker at %s", host);
  162. mqtt.setServer(host, port);
  163. #if MQTT_USE_ASYNC
  164. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  165. mqtt.setWill((mqttTopic + MQTT_STATUS_TOPIC).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  166. if ((strlen(mqtt_user) > 0) && (strlen(mqtt_pass) > 0)) {
  167. DEBUG_MSG(" as user '%s'.", mqtt_user);
  168. mqtt.setCredentials(mqtt_user, mqtt_pass);
  169. }
  170. DEBUG_MSG("\n");
  171. mqtt.connect();
  172. #else
  173. bool response;
  174. if ((strlen(mqtt_user) > 0) && (strlen(mqtt_pass) > 0)) {
  175. DEBUG_MSG(" as user '%s'\n", mqtt_user);
  176. response = mqtt.connect(getIdentifier().c_str(), mqtt_user, mqtt_pass, (mqttTopic + MQTT_STATUS_TOPIC).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  177. } else {
  178. DEBUG_MSG("\n");
  179. response = mqtt.connect(getIdentifier().c_str(), (mqttTopic + MQTT_STATUS_TOPIC).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  180. }
  181. if (response) {
  182. _mqttOnConnect();
  183. _mqttConnected = true;
  184. } else {
  185. DEBUG_MSG("[MQTT] Connection failed\n");
  186. }
  187. #endif
  188. free(host);
  189. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  190. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  191. bool _mqttForward = !mqttGetter.equals(mqttSetter);
  192. }
  193. }
  194. void mqttSetup() {
  195. #if MQTT_USE_ASYNC
  196. mqtt.onConnect([](bool sessionPresent) {
  197. _mqttOnConnect();
  198. });
  199. mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  200. _mqttOnDisconnect();
  201. });
  202. mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  203. _mqttOnMessage(topic, payload, len);
  204. });
  205. #else
  206. mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  207. _mqttOnMessage(topic, (char *) payload, length);
  208. });
  209. #endif
  210. buildTopics();
  211. }
  212. void mqttLoop() {
  213. static unsigned long lastPeriod = 0;
  214. if (WiFi.status() == WL_CONNECTED) {
  215. if (!mqtt.connected()) {
  216. #if not MQTT_USE_ASYNC
  217. if (_mqttConnected) {
  218. _mqttOnDisconnect();
  219. _mqttConnected = false;
  220. }
  221. #endif
  222. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  223. if (currPeriod != lastPeriod) {
  224. lastPeriod = currPeriod;
  225. mqttConnect();
  226. }
  227. #if not MQTT_USE_ASYNC
  228. } else {
  229. mqtt.loop();
  230. #endif
  231. }
  232. }
  233. }