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.

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