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.

308 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. 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. char * will = strdup((mqttTopic + MQTT_TOPIC_STATUS).c_str());
  162. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d"), host, port);
  163. mqtt.setServer(host, port);
  164. #if MQTT_USE_ASYNC
  165. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  166. mqtt.setWill(will, MQTT_QOS, MQTT_RETAIN, "0");
  167. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  168. DEBUG_MSG_P(PSTR(" as user '%s'."), _mqttUser);
  169. mqtt.setCredentials(_mqttUser, _mqttPass);
  170. }
  171. DEBUG_MSG_P(PSTR("\n"));
  172. mqtt.connect();
  173. #else
  174. bool response;
  175. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  176. DEBUG_MSG_P(PSTR(" as user '%s'\n"), _mqttUser);
  177. response = mqtt.connect(getIdentifier().c_str(), _mqttUser, _mqttPass, will, MQTT_QOS, MQTT_RETAIN, "0");
  178. } else {
  179. DEBUG_MSG_P(PSTR("\n"));
  180. response = mqtt.connect(getIdentifier().c_str(), will, MQTT_QOS, MQTT_RETAIN, "0");
  181. }
  182. if (response) {
  183. _mqttOnConnect();
  184. _mqttConnected = true;
  185. } else {
  186. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  187. }
  188. #endif
  189. free(host);
  190. free(will);
  191. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  192. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  193. bool _mqttForward = !mqttGetter.equals(mqttSetter);
  194. }
  195. }
  196. void mqttSetup() {
  197. #if MQTT_USE_ASYNC
  198. mqtt.onConnect([](bool sessionPresent) {
  199. _mqttOnConnect();
  200. });
  201. mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  202. _mqttOnDisconnect();
  203. });
  204. mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  205. _mqttOnMessage(topic, payload, len);
  206. });
  207. #else
  208. mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  209. _mqttOnMessage(topic, (char *) payload, length);
  210. });
  211. #endif
  212. buildTopics();
  213. }
  214. void mqttLoop() {
  215. static unsigned long lastPeriod = 0;
  216. if (WiFi.status() == WL_CONNECTED) {
  217. if (!mqtt.connected()) {
  218. #if not MQTT_USE_ASYNC
  219. if (_mqttConnected) {
  220. _mqttOnDisconnect();
  221. _mqttConnected = false;
  222. }
  223. #endif
  224. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  225. if (currPeriod != lastPeriod) {
  226. lastPeriod = currPeriod;
  227. mqttConnect();
  228. }
  229. #if not MQTT_USE_ASYNC
  230. } else {
  231. mqtt.loop();
  232. #endif
  233. }
  234. }
  235. }