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.

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