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.

181 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
  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. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  101. if (strlen(host) == 0) return;
  102. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  103. char * user = strdup(getSetting("mqttUser").c_str());
  104. char * pass = strdup(getSetting("mqttPassword").c_str());
  105. DEBUG_MSG("[MQTT] Connecting to broker at %s", host);
  106. mqtt.setServer(host, port);
  107. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  108. if ((strlen(user) > 0) && (strlen(pass) > 0)) {
  109. DEBUG_MSG(" as user '%s'.", user);
  110. mqtt.setCredentials(user, pass);
  111. }
  112. DEBUG_MSG("\n");
  113. mqtt.connect();
  114. }
  115. }
  116. void mqttSetup() {
  117. mqtt.onConnect(_mqttOnConnect);
  118. mqtt.onDisconnect(_mqttOnDisconnect);
  119. mqtt.onMessage(_mqttOnMessage);
  120. }
  121. void mqttLoop() {
  122. static unsigned long lastPeriod = 0;
  123. if (WiFi.status() == WL_CONNECTED) {
  124. if (!mqtt.connected()) {
  125. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  126. if (currPeriod != lastPeriod) {
  127. lastPeriod = currPeriod;
  128. mqttConnect();
  129. }
  130. }
  131. }
  132. }