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.

303 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. #if MQTT_USE_ASYNC
  8. #include <AsyncMqttClient.h>
  9. AsyncMqttClient mqtt;
  10. #else
  11. #include <PubSubClient.h>
  12. WiFiClient mqttWiFiClient;
  13. PubSubClient mqtt(mqttWiFiClient);
  14. bool _mqttConnected = false;
  15. #endif
  16. String mqttTopic;
  17. bool _mqttForward;
  18. char *_mqttUser = 0;
  19. char *_mqttPass = 0;
  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_P(PSTR("[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_P(PSTR("[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_P(PSTR("[MQTT] Connected!\n"));
  89. #if MQTT_SKIP_RETAINED
  90. mqttConnectedAt = millis();
  91. #endif
  92. // Build MQTT topics
  93. buildTopics();
  94. // Send first Heartbeat
  95. heartbeat();
  96. // Subscribe to system topics
  97. mqttSubscribe(MQTT_TOPIC_ACTION);
  98. // Send connect event to subscribers
  99. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  100. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  101. }
  102. }
  103. void _mqttOnDisconnect() {
  104. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  105. // Send disconnect event to subscribers
  106. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  107. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  108. }
  109. }
  110. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  111. char message[len + 1];
  112. strlcpy(message, (char *) payload, len + 1);
  113. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s"), topic, message);
  114. #if MQTT_SKIP_RETAINED
  115. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  116. DEBUG_MSG_P(PSTR(" - SKIPPED\n"));
  117. return;
  118. }
  119. #endif
  120. DEBUG_MSG_P(PSTR("\n"));
  121. // Check system topics
  122. String t = mqttSubtopic((char *) topic);
  123. if (t.equals(MQTT_TOPIC_ACTION)) {
  124. if (strcmp(message, MQTT_ACTION_RESET) == 0) {
  125. ESP.restart();
  126. }
  127. }
  128. // Send message event to subscribers
  129. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  130. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  131. }
  132. }
  133. void mqttConnect() {
  134. if (!mqtt.connected()) {
  135. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) return;
  136. // Last option: reconnect to wifi after MQTT_MAX_TRIES attemps in a row
  137. #if MQTT_MAX_TRIES > 0
  138. static unsigned int tries = 0;
  139. static unsigned long last_try = millis();
  140. if (millis() - last_try < MQTT_TRY_INTERVAL) {
  141. if (++tries > MQTT_MAX_TRIES) {
  142. DEBUG_MSG_P(PSTR("[MQTT] MQTT_MAX_TRIES met, disconnecting from WiFi\n"));
  143. wifiDisconnect();
  144. tries = 0;
  145. return;
  146. }
  147. } else {
  148. tries = 0;
  149. }
  150. last_try = millis();
  151. #endif
  152. mqtt.disconnect();
  153. if (_mqttUser) free(_mqttUser);
  154. if (_mqttPass) free(_mqttPass);
  155. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  156. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  157. _mqttUser = strdup(getSetting("mqttUser").c_str());
  158. _mqttPass = strdup(getSetting("mqttPassword").c_str());
  159. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d"), host, port);
  160. mqtt.setServer(host, port);
  161. #if MQTT_USE_ASYNC
  162. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  163. mqtt.setWill((mqttTopic + MQTT_TOPIC_STATUS).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  164. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  165. DEBUG_MSG_P(PSTR(" as user '%s'."), _mqttUser);
  166. mqtt.setCredentials(_mqttUser, _mqttPass);
  167. }
  168. DEBUG_MSG_P(PSTR("\n"));
  169. mqtt.connect();
  170. #else
  171. bool response;
  172. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  173. DEBUG_MSG_P(PSTR(" as user '%s'\n"), _mqttUser);
  174. response = mqtt.connect(getIdentifier().c_str(), _mqttUser, _mqttPass, (mqttTopic + MQTT_TOPIC_STATUS).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  175. } else {
  176. DEBUG_MSG_P(PSTR("\n"));
  177. response = mqtt.connect(getIdentifier().c_str(), (mqttTopic + MQTT_TOPIC_STATUS).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  178. }
  179. if (response) {
  180. _mqttOnConnect();
  181. _mqttConnected = true;
  182. } else {
  183. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  184. }
  185. #endif
  186. free(host);
  187. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  188. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  189. bool _mqttForward = !mqttGetter.equals(mqttSetter);
  190. }
  191. }
  192. void mqttSetup() {
  193. #if MQTT_USE_ASYNC
  194. mqtt.onConnect([](bool sessionPresent) {
  195. _mqttOnConnect();
  196. });
  197. mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  198. _mqttOnDisconnect();
  199. });
  200. mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  201. _mqttOnMessage(topic, payload, len);
  202. });
  203. #else
  204. mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  205. _mqttOnMessage(topic, (char *) payload, length);
  206. });
  207. #endif
  208. buildTopics();
  209. }
  210. void mqttLoop() {
  211. static unsigned long lastPeriod = 0;
  212. if (WiFi.status() == WL_CONNECTED) {
  213. if (!mqtt.connected()) {
  214. #if not MQTT_USE_ASYNC
  215. if (_mqttConnected) {
  216. _mqttOnDisconnect();
  217. _mqttConnected = false;
  218. }
  219. #endif
  220. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  221. if (currPeriod != lastPeriod) {
  222. lastPeriod = currPeriod;
  223. mqttConnect();
  224. }
  225. #if not MQTT_USE_ASYNC
  226. } else {
  227. mqtt.loop();
  228. #endif
  229. }
  230. }
  231. }