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.

306 lines
8.4 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. }
  40. bool mqttForward() {
  41. return _mqttForward;
  42. }
  43. String mqttSubtopic(char * topic) {
  44. String response;
  45. String t = String(topic);
  46. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  47. if (t.startsWith(mqttTopic) && t.endsWith(mqttSetter)) {
  48. response = t.substring(mqttTopic.length(), t.length() - mqttSetter.length());
  49. }
  50. return response;
  51. }
  52. void mqttSendRaw(const char * topic, const char * message) {
  53. if (mqtt.connected()) {
  54. DEBUG_MSG_P(PSTR("[MQTT] Sending %s => %s\n"), topic, message);
  55. #if MQTT_USE_ASYNC
  56. mqtt.publish(topic, MQTT_QOS, MQTT_RETAIN, message);
  57. #else
  58. mqtt.publish(topic, message, MQTT_RETAIN);
  59. #endif
  60. }
  61. }
  62. void mqttSend(const char * topic, const char * message) {
  63. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  64. String path = mqttTopic + String(topic) + mqttGetter;
  65. mqttSendRaw(path.c_str(), message);
  66. }
  67. void mqttSend(const char * topic, unsigned int index, const char * message) {
  68. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  69. String path = mqttTopic + String(topic) + String ("/") + String(index) + mqttGetter;;
  70. mqttSendRaw(path.c_str(), message);
  71. }
  72. void mqttSubscribeRaw(const char * topic) {
  73. if (mqtt.connected() && (strlen(topic) > 0)) {
  74. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  75. mqtt.subscribe(topic, MQTT_QOS);
  76. }
  77. }
  78. void mqttSubscribe(const char * topic) {
  79. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  80. String path = mqttTopic + String(topic) + mqttSetter;
  81. mqttSubscribeRaw(path.c_str());
  82. }
  83. // -----------------------------------------------------------------------------
  84. // Callbacks
  85. // -----------------------------------------------------------------------------
  86. void mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  87. _mqtt_callbacks.push_back(callback);
  88. }
  89. void _mqttOnConnect() {
  90. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  91. #if MQTT_SKIP_RETAINED
  92. mqttConnectedAt = millis();
  93. #endif
  94. // Build MQTT topics
  95. buildTopics();
  96. // Send first Heartbeat
  97. heartbeat();
  98. // Subscribe to system topics
  99. mqttSubscribe(MQTT_TOPIC_ACTION);
  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_P(PSTR("[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_P(PSTR("[MQTT] Received %s => %s"), topic, message);
  116. #if MQTT_SKIP_RETAINED
  117. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  118. DEBUG_MSG_P(PSTR(" - SKIPPED\n"));
  119. return;
  120. }
  121. #endif
  122. DEBUG_MSG_P(PSTR("\n"));
  123. // Check system topics
  124. String t = mqttSubtopic((char *) topic);
  125. if (t.equals(MQTT_TOPIC_ACTION)) {
  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_P(PSTR("[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 (_mqttUser) free(_mqttUser);
  156. if (_mqttPass) free(_mqttPass);
  157. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  158. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  159. _mqttUser = strdup(getSetting("mqttUser").c_str());
  160. _mqttPass = strdup(getSetting("mqttPassword").c_str());
  161. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d"), host, port);
  162. mqtt.setServer(host, port);
  163. #if MQTT_USE_ASYNC
  164. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  165. mqtt.setWill((mqttTopic + MQTT_TOPIC_STATUS).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  166. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  167. DEBUG_MSG_P(PSTR(" as user '%s'."), _mqttUser);
  168. mqtt.setCredentials(_mqttUser, _mqttPass);
  169. }
  170. DEBUG_MSG_P(PSTR("\n"));
  171. mqtt.connect();
  172. #else
  173. bool response;
  174. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  175. DEBUG_MSG_P(PSTR(" as user '%s'\n"), _mqttUser);
  176. response = mqtt.connect(getIdentifier().c_str(), _mqttUser, _mqttPass, (mqttTopic + MQTT_TOPIC_STATUS).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  177. } else {
  178. DEBUG_MSG_P(PSTR("\n"));
  179. response = mqtt.connect(getIdentifier().c_str(), (mqttTopic + MQTT_TOPIC_STATUS).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  180. }
  181. if (response) {
  182. _mqttOnConnect();
  183. _mqttConnected = true;
  184. } else {
  185. DEBUG_MSG_P(PSTR("[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. }