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.

180 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. MQTT MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <ESP8266WiFi.h>
  6. #include <AsyncMqttClient.h>
  7. #include <vector>
  8. AsyncMqttClient mqtt;
  9. String mqttTopic;
  10. std::vector<void (*)(unsigned int, const char *, const char *)> _mqtt_callbacks;
  11. #if MQTT_SKIP_RETAINED
  12. unsigned long mqttConnectedAt = 0;
  13. #endif
  14. // -----------------------------------------------------------------------------
  15. // MQTT
  16. // -----------------------------------------------------------------------------
  17. bool mqttConnected() {
  18. return mqtt.connected();
  19. }
  20. void mqttDisconnect() {
  21. mqtt.disconnect();
  22. }
  23. void buildTopics() {
  24. // Replace identifier
  25. mqttTopic = getSetting("mqttTopic", MQTT_TOPIC);
  26. mqttTopic.replace("{identifier}", getSetting("hostname"));
  27. }
  28. unsigned int mqttTopicRootLength() {
  29. return mqttTopic.length();
  30. }
  31. void mqttSendRaw(const char * topic, const char * message) {
  32. if (mqtt.connected()) {
  33. DEBUG_MSG("[MQTT] Sending %s => %s\n", topic, message);
  34. mqtt.publish(topic, MQTT_QOS, MQTT_RETAIN, message);
  35. }
  36. }
  37. void mqttSend(const char * topic, const char * message) {
  38. String path = mqttTopic + String(topic);
  39. mqttSendRaw(path.c_str(), message);
  40. }
  41. void mqttSubscribeRaw(const char * topic) {
  42. if (mqtt.connected()) {
  43. DEBUG_MSG("[MQTT] Subscribing to %s\n", topic);
  44. mqtt.subscribe(topic, MQTT_QOS);
  45. }
  46. }
  47. void mqttSubscribe(const char * topic) {
  48. String path = mqttTopic + String(topic);
  49. mqttSubscribeRaw(path.c_str());
  50. }
  51. void mqttRegister(void (*callback)(unsigned int, const char *, const char *)) {
  52. _mqtt_callbacks.push_back(callback);
  53. }
  54. void _mqttOnConnect(bool sessionPresent) {
  55. DEBUG_MSG("[MQTT] Connected!\n");
  56. #if MQTT_SKIP_RETAINED
  57. mqttConnectedAt = millis();
  58. #endif
  59. // Build MQTT topics
  60. buildTopics();
  61. // Say hello and report our IP and VERSION
  62. mqttSend(MQTT_IP_TOPIC, getIP().c_str());
  63. mqttSend(MQTT_VERSION_TOPIC, APP_VERSION);
  64. // Send connect event to subscribers
  65. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  66. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  67. }
  68. }
  69. void _mqttOnDisconnect(AsyncMqttClientDisconnectReason reason) {
  70. DEBUG_MSG("[MQTT] Disconnected!\n");
  71. // Send disconnect event to subscribers
  72. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  73. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  74. }
  75. }
  76. void _mqttOnMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  77. char message[len+1];
  78. strlcpy(message, payload, len+1);
  79. DEBUG_MSG("[MQTT] Received %s => %s", topic, message);
  80. #if MQTT_SKIP_RETAINED
  81. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  82. DEBUG_MSG(" - SKIPPED\n");
  83. return;
  84. }
  85. #endif
  86. DEBUG_MSG("\n");
  87. // Send message event to subscribers
  88. // Topic is set to the specific part each one might be checking
  89. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  90. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  91. }
  92. }
  93. void mqttConnect() {
  94. if (!mqtt.connected()) {
  95. mqtt.disconnect();
  96. char * host = strdup(getSetting("mqttServer", MQTT_SERVER).c_str());
  97. if (strlen(host) == 0) return;
  98. unsigned int port = getSetting("mqttPort", MQTT_PORT).toInt();
  99. char * user = strdup(getSetting("mqttUser").c_str());
  100. char * pass = strdup(getSetting("mqttPassword").c_str());
  101. DEBUG_MSG("[MQTT] Connecting to broker at %s", host);
  102. mqtt.setServer(host, port);
  103. mqtt.setKeepAlive(MQTT_KEEPALIVE).setCleanSession(false);
  104. mqtt.setWill((mqttTopic + MQTT_HEARTBEAT_TOPIC).c_str(), MQTT_QOS, MQTT_RETAIN, "0");
  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. buildTopics();
  118. }
  119. void mqttLoop() {
  120. static unsigned long lastPeriod = 0;
  121. if (WiFi.status() == WL_CONNECTED) {
  122. if (!mqtt.connected()) {
  123. unsigned long currPeriod = millis() / MQTT_RECONNECT_DELAY;
  124. if (currPeriod != lastPeriod) {
  125. lastPeriod = currPeriod;
  126. mqttConnect();
  127. }
  128. }
  129. }
  130. }