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.

364 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. if (ntpConnected()) root[MQTT_TOPIC_TIME] = ntpDateTime();
  80. root[MQTT_TOPIC_HOSTNAME] = getSetting("hostname", HOSTNAME);
  81. root[MQTT_TOPIC_IP] = getIP();
  82. String output;
  83. root.printTo(output);
  84. String path = mqttTopic + String(MQTT_TOPIC_JSON);
  85. mqttSendRaw(path.c_str(), output.c_str());
  86. for (unsigned char i = 0; i < _mqtt_queue.size(); i++) {
  87. mqtt_message_t element = _mqtt_queue[i];
  88. free(element.topic);
  89. free(element.message);
  90. }
  91. _mqtt_queue.clear();
  92. }
  93. void mqttSend(const char * topic, const char * message, bool force) {
  94. bool useJson = force ? false : getSetting("mqttUseJson", MQTT_USE_JSON).toInt() == 1;
  95. if (useJson) {
  96. mqtt_message_t element;
  97. element.topic = strdup(topic);
  98. element.message = strdup(message);
  99. _mqtt_queue.push_back(element);
  100. mqttFlushTicker.once_ms(100, _mqttFlush);
  101. } else {
  102. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  103. String path = mqttTopic + String(topic) + mqttGetter;
  104. mqttSendRaw(path.c_str(), message);
  105. }
  106. }
  107. void mqttSend(const char * topic, const char * message) {
  108. mqttSend(topic, message, false);
  109. }
  110. void mqttSend(const char * topic, unsigned int index, const char * message, bool force) {
  111. char buffer[strlen(topic)+5];
  112. sprintf(buffer, "%s/%d", topic, index);
  113. mqttSend(buffer, message, force);
  114. }
  115. void mqttSend(const char * topic, unsigned int index, const char * message) {
  116. mqttSend(topic, index, message, false);
  117. }
  118. void mqttSubscribeRaw(const char * topic) {
  119. if (mqtt.connected() && (strlen(topic) > 0)) {
  120. DEBUG_MSG_P(PSTR("[MQTT] Subscribing to %s\n"), topic);
  121. mqtt.subscribe(topic, MQTT_QOS);
  122. }
  123. }
  124. void mqttSubscribe(const char * topic) {
  125. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  126. String path = mqttTopic + String(topic) + mqttSetter;
  127. mqttSubscribeRaw(path.c_str());
  128. }
  129. // -----------------------------------------------------------------------------
  130. // Callbacks
  131. // -----------------------------------------------------------------------------
  132. void mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  133. _mqtt_callbacks.push_back(callback);
  134. }
  135. void _mqttOnConnect() {
  136. DEBUG_MSG_P(PSTR("[MQTT] Connected!\n"));
  137. #if MQTT_SKIP_RETAINED
  138. mqttConnectedAt = millis();
  139. #endif
  140. // Build MQTT topics
  141. buildTopics();
  142. // Send first Heartbeat
  143. heartbeat();
  144. // Subscribe to system topics
  145. mqttSubscribe(MQTT_TOPIC_ACTION);
  146. // Send connect event to subscribers
  147. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  148. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  149. }
  150. }
  151. void _mqttOnDisconnect() {
  152. DEBUG_MSG_P(PSTR("[MQTT] Disconnected!\n"));
  153. // Send disconnect event to subscribers
  154. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  155. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  156. }
  157. }
  158. void _mqttOnMessage(char* topic, char* payload, unsigned int len) {
  159. char message[len + 1];
  160. strlcpy(message, (char *) payload, len + 1);
  161. DEBUG_MSG_P(PSTR("[MQTT] Received %s => %s"), topic, message);
  162. #if MQTT_SKIP_RETAINED
  163. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  164. DEBUG_MSG_P(PSTR(" - SKIPPED\n"));
  165. return;
  166. }
  167. #endif
  168. DEBUG_MSG_P(PSTR("\n"));
  169. // Check system topics
  170. String t = mqttSubtopic((char *) topic);
  171. if (t.equals(MQTT_TOPIC_ACTION)) {
  172. if (strcmp(message, MQTT_ACTION_RESET) == 0) {
  173. customReset(CUSTOM_RESET_MQTT);
  174. ESP.restart();
  175. }
  176. }
  177. // Send message event to subscribers
  178. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  179. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  180. }
  181. }
  182. void mqttConnect() {
  183. if (!mqtt.connected()) {
  184. if (getSetting("mqttServer", MQTT_SERVER).length() == 0) return;
  185. // Last option: reconnect to wifi after MQTT_MAX_TRIES attemps in a row
  186. #if MQTT_MAX_TRIES > 0
  187. static unsigned int tries = 0;
  188. static unsigned long last_try = millis();
  189. if (millis() - last_try < MQTT_TRY_INTERVAL) {
  190. if (++tries > MQTT_MAX_TRIES) {
  191. DEBUG_MSG_P(PSTR("[MQTT] MQTT_MAX_TRIES met, disconnecting from WiFi\n"));
  192. wifiDisconnect();
  193. tries = 0;
  194. return;
  195. }
  196. } else {
  197. tries = 0;
  198. }
  199. last_try = millis();
  200. #endif
  201. mqtt.disconnect();
  202. if (_mqttUser) free(_mqttUser);
  203. if (_mqttPass) free(_mqttPass);
  204. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  205. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  206. _mqttUser = strdup(getSetting("mqttUser").c_str());
  207. _mqttPass = strdup(getSetting("mqttPassword").c_str());
  208. char * will = strdup((mqttTopic + MQTT_TOPIC_STATUS).c_str());
  209. DEBUG_MSG_P(PSTR("[MQTT] Connecting to broker at %s:%d"), host, port);
  210. mqtt.setServer(host, port);
  211. #if MQTT_USE_ASYNC
  212. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  213. mqtt.setWill(will, MQTT_QOS, MQTT_RETAIN, "0");
  214. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  215. DEBUG_MSG_P(PSTR(" as user '%s'."), _mqttUser);
  216. mqtt.setCredentials(_mqttUser, _mqttPass);
  217. }
  218. DEBUG_MSG_P(PSTR("\n"));
  219. mqtt.connect();
  220. #else
  221. bool response;
  222. if ((strlen(_mqttUser) > 0) && (strlen(_mqttPass) > 0)) {
  223. DEBUG_MSG_P(PSTR(" as user '%s'\n"), _mqttUser);
  224. response = mqtt.connect(getIdentifier().c_str(), _mqttUser, _mqttPass, will, MQTT_QOS, MQTT_RETAIN, "0");
  225. } else {
  226. DEBUG_MSG_P(PSTR("\n"));
  227. response = mqtt.connect(getIdentifier().c_str(), will, MQTT_QOS, MQTT_RETAIN, "0");
  228. }
  229. if (response) {
  230. _mqttOnConnect();
  231. _mqttConnected = true;
  232. } else {
  233. DEBUG_MSG_P(PSTR("[MQTT] Connection failed\n"));
  234. }
  235. #endif
  236. free(host);
  237. free(will);
  238. String mqttSetter = getSetting("mqttSetter", MQTT_USE_SETTER);
  239. String mqttGetter = getSetting("mqttGetter", MQTT_USE_GETTER);
  240. _mqttForward = !mqttGetter.equals(mqttSetter);
  241. }
  242. }
  243. void mqttSetup() {
  244. #if MQTT_USE_ASYNC
  245. mqtt.onConnect([](bool sessionPresent) {
  246. _mqttOnConnect();
  247. });
  248. mqtt.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
  249. _mqttOnDisconnect();
  250. });
  251. mqtt.onMessage([](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  252. _mqttOnMessage(topic, payload, len);
  253. });
  254. #else
  255. mqtt.setCallback([](char* topic, byte* payload, unsigned int length) {
  256. _mqttOnMessage(topic, (char *) payload, length);
  257. });
  258. #endif
  259. buildTopics();
  260. }
  261. void mqttLoop() {
  262. static unsigned long lastPeriod = 0;
  263. if (WiFi.status() == WL_CONNECTED) {
  264. if (!mqtt.connected()) {
  265. #if not MQTT_USE_ASYNC
  266. if (_mqttConnected) {
  267. _mqttOnDisconnect();
  268. _mqttConnected = false;
  269. }
  270. #endif
  271. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  272. if (currPeriod != lastPeriod) {
  273. lastPeriod = currPeriod;
  274. mqttConnect();
  275. }
  276. #if not MQTT_USE_ASYNC
  277. } else {
  278. mqtt.loop();
  279. #endif
  280. }
  281. }
  282. }