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.

84 lines
2.3 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. }
  22. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  23. if (lightHasColor()) {
  24. root["brightness_state_topic"] = getTopic(MQTT_TOPIC_BRIGHTNESS, false);
  25. root["brightness_command_topic"] = getTopic(MQTT_TOPIC_BRIGHTNESS, true);
  26. root["rgb_state_topic"] = getTopic(MQTT_TOPIC_COLOR_RGB, false);
  27. root["rgb_command_topic"] = getTopic(MQTT_TOPIC_COLOR_RGB, true);
  28. root["color_temp_command_topic"] = getTopic(MQTT_TOPIC_MIRED, true);
  29. }
  30. if (lightChannels() > 3) {
  31. root["white_value_state_topic"] = getTopic(MQTT_TOPIC_CHANNEL, 3, false);
  32. root["white_value_command_topic"] = getTopic(MQTT_TOPIC_CHANNEL, 3, true);
  33. }
  34. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  35. root.printTo(output);
  36. }
  37. #if LIGHT_PROVIDER == LIGHT_PROVIDER_NONE
  38. String component = String("switch");
  39. #else
  40. String component = String("light");
  41. #endif
  42. String topic = getSetting("haPrefix", HOMEASSISTANT_PREFIX) +
  43. "/" + component +
  44. "/" + getSetting("hostname") +
  45. "/config";
  46. mqttSendRaw(topic.c_str(), output.c_str());
  47. }
  48. void haConfigure() {
  49. bool enabled = getSetting("haEnabled", HOMEASSISTANT_ENABLED).toInt() == 1;
  50. if (enabled != _haEnabled) haSend(enabled);
  51. _haEnabled = enabled;
  52. }
  53. void haSetup() {
  54. haConfigure();
  55. mqttRegister([](unsigned int type, const char * topic, const char * payload) {
  56. if (type == MQTT_CONNECT_EVENT) haSend(_haEnabled);
  57. });
  58. }
  59. #endif // HOMEASSISTANT_SUPPORT