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.

88 lines
2.6 KiB

  1. /*
  2. HOME ASSISTANT MODULE
  3. Copyright (C) 2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if HOMEASSISTANT_SUPPORT
  6. #include <ArduinoJson.h>
  7. bool _haEnabled = false;
  8. void haSend(bool add) {
  9. DEBUG_MSG_P(PSTR("[HA] Sending autodiscovery MQTT message\n"));
  10. String output;
  11. if (add) {
  12. DynamicJsonBuffer jsonBuffer;
  13. JsonObject& root = jsonBuffer.createObject();
  14. root["name"] = getSetting("hostname");
  15. root["platform"] = "mqtt";
  16. if (relayCount()) {
  17. root["state_topic"] = getTopic(MQTT_TOPIC_RELAY, 0, false);
  18. root["command_topic"] = getTopic(MQTT_TOPIC_RELAY, 0, true);
  19. root["payload_on"] = String("1");
  20. root["payload_off"] = String("0");
  21. root["availability_topic"] = getTopic(MQTT_TOPIC_STATUS, false);
  22. root["payload_available"] = String("1");
  23. root["payload_not_available"] = String("0");
  24. }
  25. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  26. if (lightHasColor()) {
  27. root["brightness_state_topic"] = getTopic(MQTT_TOPIC_BRIGHTNESS, false);
  28. root["brightness_command_topic"] = getTopic(MQTT_TOPIC_BRIGHTNESS, true);
  29. root["rgb_state_topic"] = getTopic(MQTT_TOPIC_COLOR_RGB, false);
  30. root["rgb_command_topic"] = getTopic(MQTT_TOPIC_COLOR_RGB, true);
  31. root["color_temp_command_topic"] = getTopic(MQTT_TOPIC_MIRED, true);
  32. }
  33. if (lightChannels() > 3) {
  34. root["white_value_state_topic"] = getTopic(MQTT_TOPIC_CHANNEL, 3, false);
  35. root["white_value_command_topic"] = getTopic(MQTT_TOPIC_CHANNEL, 3, true);
  36. }
  37. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  38. root.printTo(output);
  39. }
  40. #if LIGHT_PROVIDER == LIGHT_PROVIDER_NONE
  41. String component = String("switch");
  42. #else
  43. String component = String("light");
  44. #endif
  45. String topic = getSetting("haPrefix", HOMEASSISTANT_PREFIX) +
  46. "/" + component +
  47. "/" + getSetting("hostname") +
  48. "/config";
  49. mqttSendRaw(topic.c_str(), output.c_str());
  50. mqttSend(MQTT_TOPIC_STATUS, MQTT_STATUS_ONLINE, true);
  51. }
  52. void haConfigure() {
  53. bool enabled = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  54. if (enabled != _haEnabled) haSend(enabled);
  55. _haEnabled = enabled;
  56. }
  57. void haSetup() {
  58. haConfigure();
  59. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  60. if (type == MQTT_CONNECT_EVENT) haSend(_haEnabled);
  61. });
  62. }
  63. #endif // HOMEASSISTANT_SUPPORT