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.

179 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. mqtt.setWill((mqttTopic + MQTT_HEARTBEAT_TOPIC).c_str(), MQTT_QOS, MQTT_RETAIN, (char *) "0");
  62. // Say hello and report our IP and VERSION
  63. mqttSend(MQTT_IP_TOPIC, getIP().c_str());
  64. mqttSend(MQTT_VERSION_TOPIC, APP_VERSION);
  65. // Send connect event to subscribers
  66. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  67. (*_mqtt_callbacks[i])(MQTT_CONNECT_EVENT, NULL, NULL);
  68. }
  69. }
  70. void _mqttOnDisconnect(AsyncMqttClientDisconnectReason reason) {
  71. DEBUG_MSG("[MQTT] Disconnected!\n");
  72. // Send disconnect event to subscribers
  73. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  74. (*_mqtt_callbacks[i])(MQTT_DISCONNECT_EVENT, NULL, NULL);
  75. }
  76. }
  77. void _mqttOnMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  78. char message[len+1];
  79. strlcpy(message, payload, len+1);
  80. DEBUG_MSG("[MQTT] Received %s => %s", topic, message);
  81. #if MQTT_SKIP_RETAINED
  82. if (millis() - mqttConnectedAt < MQTT_SKIP_TIME) {
  83. DEBUG_MSG(" - SKIPPED\n");
  84. return;
  85. }
  86. #endif
  87. DEBUG_MSG("\n");
  88. // Send message event to subscribers
  89. // Topic is set to the specific part each one might be checking
  90. for (unsigned char i = 0; i < _mqtt_callbacks.size(); i++) {
  91. (*_mqtt_callbacks[i])(MQTT_MESSAGE_EVENT, topic, message);
  92. }
  93. }
  94. void mqttConnect() {
  95. if (!mqtt.connected()) {
  96. mqtt.disconnect();
  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. }