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.

190 lines
4.7 KiB

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 <AsyncMqttClient.h>
  7. #include <vector>
  8. AsyncMqttClient mqtt;
  9. String mqttTopic;
  10. std::vector<void (*)(unsigned int, const char *, const char *)> _mqtt_callbacks;
  11. #if MQTT_SKIP_RETAINED
  12. unsigned long mqttConnectedAt = 0;
  13. #endif
  14. // -----------------------------------------------------------------------------
  15. // MQTT
  16. // -----------------------------------------------------------------------------
  17. bool mqttConnected() {
  18. return mqtt.connected();
  19. }
  20. void mqttDisconnect() {
  21. mqtt.disconnect();
  22. }
  23. void buildTopics() {
  24. // Replace identifier
  25. mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  26. mqttTopic.replace("{identifier}", getSetting("hostname"));
  27. }
  28. char * mqttSubtopic(char * topic) {
  29. int pos = min(mqttTopic.length(), strlen(topic));
  30. return topic + pos;
  31. }
  32. void mqttSendRaw(const char * topic, const char * message) {
  33. if (mqtt.connected()) {
  34. DEBUG_MSG("[MQTT] Sending %s => %s\n", topic, message);
  35. mqtt.publish(topic, MQTT_QOS, MQTT_RETAIN, message);
  36. }
  37. }
  38. void mqttSend(const char * topic, const char * message) {
  39. String path = mqttTopic + String(topic);
  40. mqttSendRaw(path.c_str(), message);
  41. }
  42. void mqttSubscribeRaw(const char * topic) {
  43. if (mqtt.connected()) {
  44. DEBUG_MSG("[MQTT] Subscribing to %s\n", topic);
  45. mqtt.subscribe(topic, MQTT_QOS);
  46. }
  47. }
  48. void mqttSubscribe(const char * topic) {
  49. String path = mqttTopic + String(topic);
  50. mqttSubscribeRaw(path.c_str());
  51. }
  52. void mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  53. _mqtt_callbacks.push_back(callback);
  54. }
  55. void _mqttOnConnect(bool sessionPresent) {
  56. DEBUG_MSG("[MQTT] Connected!\n");
  57. #if MQTT_SKIP_RETAINED
  58. mqttConnectedAt = millis();
  59. #endif
  60. // Build MQTT topics
  61. buildTopics();
  62. // Say hello and report our IP and VERSION
  63. mqttSend(MQTT_IP_TOPIC, getIP().c_str());
  64. mqttSend(MQTT_VERSION_TOPIC, APP_VERSION);
  65. // Subscribe to system topics
  66. mqttSubscribe(MQTT_ACTION_TOPIC);
  67. // Send connect event to subscribers
  68. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  69. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  70. }
  71. }
  72. void _mqttOnDisconnect(AsyncMqttClientDisconnectReason reason) {
  73. DEBUG_MSG("[MQTT] Disconnected!\n");
  74. // Send disconnect event to subscribers
  75. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  76. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  77. }
  78. }
  79. void _mqttOnMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  80. char message[len+1];
  81. strlcpy(message, payload, len+1);
  82. DEBUG_MSG("[MQTT] Received %s => %s", topic, message);
  83. #if MQTT_SKIP_RETAINED
  84. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  85. DEBUG_MSG(" - SKIPPED\n");
  86. return;
  87. }
  88. #endif
  89. DEBUG_MSG("\n");
  90. // Check system topics
  91. char * p = mqttSubtopic(topic);
  92. if (strcmp(p, MQTT_ACTION_TOPIC) == 0) {
  93. if (strcmp(payload, MQTT_ACTION_RESET) == 0) {
  94. ESP.reset();
  95. }
  96. }
  97. // Send message event to subscribers
  98. // Topic is set to the specific part each one might be checking
  99. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  100. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  101. }
  102. }
  103. void mqttConnect() {
  104. if (!mqtt.connected()) {
  105. mqtt.disconnect();
  106. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  107. if (strlen(host) == 0) return;
  108. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  109. char * user = strdup(getSetting("mqttUser").c_str());
  110. char * pass = strdup(getSetting("mqttPassword").c_str());
  111. DEBUG_MSG("[MQTT] Connecting to broker at %s", host);
  112. mqtt.setServer(host, port);
  113. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  114. mqtt.setWill((mqttTopic + MQTT_HEARTBEAT_TOPIC).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  115. if ((strlen(user) > 0) && (strlen(pass) > 0)) {
  116. DEBUG_MSG(" as user '%s'.", user);
  117. mqtt.setCredentials(user, pass);
  118. }
  119. DEBUG_MSG("\n");
  120. mqtt.connect();
  121. }
  122. }
  123. void mqttSetup() {
  124. mqtt.onConnect(_mqttOnConnect);
  125. mqtt.onDisconnect(_mqttOnDisconnect);
  126. mqtt.onMessage(_mqttOnMessage);
  127. buildTopics();
  128. }
  129. void mqttLoop() {
  130. static unsigned long lastPeriod = 0;
  131. if (WiFi.status() == WL_CONNECTED) {
  132. if (!mqtt.connected()) {
  133. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  134. if (currPeriod != lastPeriod) {
  135. lastPeriod = currPeriod;
  136. mqttConnect();
  137. }
  138. }
  139. }
  140. }