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.

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