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.

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