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.

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