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.

178 lines
4.4 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-2017 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. // Send connect event to subscribers
  67. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  68. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  69. }
  70. }
  71. void _mqttOnDisconnect(AsyncMqttClientDisconnectReason reason) {
  72. DEBUG_MSG("[MQTT] Disconnected!\n");
  73. // Send disconnect event to subscribers
  74. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  75. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  76. }
  77. }
  78. void _mqttOnMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  79. char message[len+1];
  80. strlcpy(message, payload, len+1);
  81. DEBUG_MSG("[MQTT] Received %s => %s", topic, message);
  82. #if MQTT_SKIP_RETAINED
  83. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  84. DEBUG_MSG(" - SKIPPED\n");
  85. return;
  86. }
  87. #endif
  88. DEBUG_MSG("\n");
  89. // Send message event to subscribers
  90. // Topic is set to the specific part each one might be checking
  91. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  92. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  93. }
  94. }
  95. void mqttConnect() {
  96. if (!mqtt.connected()) {
  97. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  98. if (strlen(host) == 0) return;
  99. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  100. char * user = strdup(getSetting("mqttUser").c_str());
  101. char * pass = strdup(getSetting("mqttPassword").c_str());
  102. DEBUG_MSG("[MQTT] Connecting to broker at %s", host);
  103. mqtt.setServer(host, port);
  104. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  105. if ((strlen(user) > 0) && (strlen(pass) > 0)) {
  106. DEBUG_MSG(" as user '%s'.", user);
  107. mqtt.setCredentials(user, pass);
  108. }
  109. DEBUG_MSG("\n");
  110. mqtt.connect();
  111. }
  112. }
  113. void mqttSetup() {
  114. mqtt.onConnect(_mqttOnConnect);
  115. mqtt.onDisconnect(_mqttOnDisconnect);
  116. mqtt.onMessage(_mqttOnMessage);
  117. }
  118. void mqttLoop() {
  119. static unsigned long lastPeriod = 0;
  120. if (WiFi.status() == WL_CONNECTED) {
  121. if (!mqtt.connected()) {
  122. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  123. if (currPeriod != lastPeriod) {
  124. lastPeriod = currPeriod;
  125. mqttConnect();
  126. }
  127. }
  128. }
  129. }