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.

192 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
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. if ((user != "") && (pass != "")) {
  111. DEBUG_MSG(" as user '%s'.\n", (char *) user.c_str());
  112. char username[user.length()+1];
  113. user.toCharArray(username, user.length()+1);
  114. char password[pass.length()+1];
  115. pass.toCharArray(password, pass.length()+1);
  116. mqtt.setCredentials(username, password);
  117. } else {
  118. DEBUG_MSG(" anonymously\n");
  119. }
  120. mqtt.connect();
  121. }
  122. }
  123. void mqttSetup() {
  124. mqtt.onConnect(_mqttOnConnect);
  125. mqtt.onDisconnect(_mqttOnDisconnect);
  126. mqtt.onMessage(_mqttOnMessage);
  127. }
  128. void mqttLoop() {
  129. static unsigned long lastPeriod = 0;
  130. if (WiFi.status() == WL_CONNECTED) {
  131. if (!mqtt.connected()) {
  132. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  133. if (currPeriod != lastPeriod) {
  134. lastPeriod = currPeriod;
  135. mqttConnect();
  136. }
  137. }
  138. }
  139. }