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.

193 lines
4.8 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
8 years ago
8 years ago
  1. /*
  2. ESPurna
  3. MQTT MODULE
  4. Copyright (C) 2016 by Xose Pérez <xose dot perez at gmail dot com>
  5. */
  6. #include <ESP8266WiFi.h>
  7. #include <AsyncMqttClient.h>
  8. #include <vector>
  9. AsyncMqttClient mqtt;
  10. String mqttTopic;
  11. std::vector<void (*)(unsigned int, const char *, const char *)> _mqtt_callbacks;
  12. #if MQTT_SKIP_RETAINED
  13. unsigned long mqttConnectedAt = 0;
  14. #endif
  15. // -----------------------------------------------------------------------------
  16. // MQTT
  17. // -----------------------------------------------------------------------------
  18. bool mqttConnected() {
  19. return mqtt.connected();
  20. }
  21. void mqttDisconnect() {
  22. mqtt.disconnect();
  23. }
  24. void buildTopics() {
  25. // Replace identifier
  26. mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  27. mqttTopic.replace("{identifier}", getSetting("hostname"));
  28. }
  29. unsigned int mqttTopicRootLength() {
  30. return mqttTopic.length();
  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. mqtt.setWill((mqttTopic + MQTT_HEARTBEAT_TOPIC).c_str(), MQTT_QOS, MQTT_RETAIN, (char *) "0");
  63. // Say hello and report our IP and VERSION
  64. mqttSend(MQTT_IP_TOPIC, getIP().c_str());
  65. mqttSend(MQTT_VERSION_TOPIC, APP_VERSION);
  66. char buffer[50];
  67. getFSVersion(buffer);
  68. mqttSend(MQTT_FSVERSION_TOPIC, buffer);
  69. // Send connect event to subscribers
  70. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  71. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  72. }
  73. }
  74. void _mqttOnDisconnect(AsyncMqttClientDisconnectReason reason) {
  75. DEBUG_MSG("[MQTT] Disconnected!\n");
  76. // Send disconnect event to subscribers
  77. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  78. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  79. }
  80. }
  81. void _mqttOnMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  82. char message[len+1];
  83. strlcpy(message, payload, len+1);
  84. DEBUG_MSG("[MQTT] Received %s => %s", topic, message);
  85. #if MQTT_SKIP_RETAINED
  86. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  87. DEBUG_MSG(" - SKIPPED\n");
  88. return;
  89. }
  90. #endif
  91. DEBUG_MSG("\n");
  92. // Send message event to subscribers
  93. // Topic is set to the specific part each one might be checking
  94. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  95. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  96. }
  97. }
  98. void mqttConnect() {
  99. if (!mqtt.connected()) {
  100. String host = getSetting("mqttServer", MQTT_SERVER);
  101. String port = getSetting("mqttPort", MQTT_PORT);
  102. String user = getSetting("mqttUser");
  103. String pass = getSetting("mqttPassword");
  104. if (host.length() == 0) return;
  105. DEBUG_MSG("[MQTT] Connecting to broker at %s", (char *) host.c_str());
  106. mqtt.setServer(host.c_str(), port.toInt());
  107. mqtt
  108. .setKeepAlive(MQTT_KEEPALIVE)
  109. .setCleanSession(false)
  110. .setClientId(getSetting("hostname", HOSTNAME).c_str());
  111. if ((user != "") && (pass != "")) {
  112. DEBUG_MSG(" as user '%s'.\n", (char *) user.c_str());
  113. char username[user.length()+1];
  114. user.toCharArray(username, user.length()+1);
  115. char password[pass.length()+1];
  116. pass.toCharArray(password, pass.length()+1);
  117. mqtt.setCredentials(username, password);
  118. } else {
  119. DEBUG_MSG(" anonymously\n");
  120. }
  121. mqtt.connect();
  122. }
  123. }
  124. void mqttSetup() {
  125. mqtt.onConnect(_mqttOnConnect);
  126. mqtt.onDisconnect(_mqttOnDisconnect);
  127. mqtt.onMessage(_mqttOnMessage);
  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. }