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.

175 lines
4.5 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
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. void mqttSend(const char * topic, const char * message) {
  30. if (!mqtt.connected()) return;
  31. String path = mqttTopic + String(topic);
  32. DEBUG_MSG("[MQTT] Sending %s %s\n", (char *) path.c_str(), message);
  33. mqtt.publish(path.c_str(), MQTT_QOS, MQTT_RETAIN, message);
  34. }
  35. void mqttSubscribe(const char * topic) {
  36. String path = mqttTopic + String(topic);
  37. DEBUG_MSG("[MQTT] Subscribing to %s\n", (char *) path.c_str());
  38. mqtt.subscribe(path.c_str(), MQTT_QOS);
  39. }
  40. void mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  41. _mqtt_callbacks.push_back(callback);
  42. }
  43. void _mqttOnConnect(bool sessionPresent) {
  44. DEBUG_MSG("[MQTT] Connected!\n");
  45. #if MQTT_SKIP_RETAINED
  46. mqttConnectedAt = millis();
  47. #endif
  48. // Build MQTT topics
  49. buildTopics();
  50. mqtt.setWill((mqttTopic + MQTT_HEARTBEAT_TOPIC).c_str(), MQTT_QOS, MQTT_RETAIN, (char *) "0");
  51. // Say hello and report our IP and VERSION
  52. mqttSend((char *) MQTT_IP_TOPIC, (char *) getIP().c_str());
  53. mqttSend((char *) MQTT_VERSION_TOPIC, (char *) APP_VERSION);
  54. char buffer[50];
  55. getFSVersion(buffer);
  56. mqttSend((char *) MQTT_FSVERSION_TOPIC, buffer);
  57. // Send connect event to subscribers
  58. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  59. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  60. }
  61. }
  62. void _mqttOnDisconnect(AsyncMqttClientDisconnectReason reason) {
  63. DEBUG_MSG("[MQTT] Disconnected!\n");
  64. // Send disconnect event to subscribers
  65. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  66. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  67. }
  68. }
  69. void _mqttOnMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  70. DEBUG_MSG("[MQTT] Received %s %c", topic, payload[0]);
  71. #if MQTT_SKIP_RETAINED
  72. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  73. DEBUG_MSG(" - SKIPPED\n");
  74. return;
  75. }
  76. #endif
  77. DEBUG_MSG("\n");
  78. // Send message event to subscribers
  79. // Topic is set to the specific part each one might be checking
  80. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  81. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic + mqttTopic.length(), payload);
  82. }
  83. }
  84. void mqttConnect() {
  85. if (!mqtt.connected()) {
  86. String host = getSetting("mqttServer", MQTT_SERVER);
  87. String port = getSetting("mqttPort", MQTT_PORT);
  88. String user = getSetting("mqttUser");
  89. String pass = getSetting("mqttPassword");
  90. if (host.length() == 0) return;
  91. DEBUG_MSG("[MQTT] Connecting to broker at %s", (char *) host.c_str());
  92. mqtt.setServer(host.c_str(), port.toInt());
  93. mqtt
  94. .setKeepAlive(MQTT_KEEPALIVE)
  95. .setCleanSession(false)
  96. .setClientId(getSetting("hostname", HOSTNAME).c_str());
  97. if ((user != "") && (pass != "")) {
  98. DEBUG_MSG(" as user '%s'.\n", (char *) user.c_str());
  99. char username[user.length()+1];
  100. user.toCharArray(username, user.length()+1);
  101. char password[pass.length()+1];
  102. pass.toCharArray(password, pass.length()+1);
  103. mqtt.setCredentials(username, password);
  104. } else {
  105. DEBUG_MSG(" anonymously\n");
  106. }
  107. mqtt.connect();
  108. }
  109. }
  110. void mqttSetup() {
  111. mqtt.onConnect(_mqttOnConnect);
  112. mqtt.onDisconnect(_mqttOnDisconnect);
  113. mqtt.onMessage(_mqttOnMessage);
  114. }
  115. void mqttLoop() {
  116. static unsigned long lastPeriod = 0;
  117. if (WiFi.status() == WL_CONNECTED) {
  118. if (!mqtt.connected()) {
  119. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  120. if (currPeriod != lastPeriod) {
  121. lastPeriod = currPeriod;
  122. mqttConnect();
  123. }
  124. }
  125. }
  126. }