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.

81 lines
2.6 KiB

  1. import re
  2. import esphome.codegen as cg
  3. import esphome.config_validation as cv
  4. from esphome.components import binary_sensor
  5. from esphome.const import CONF_ID, CONF_FOR
  6. from .. import (
  7. bslamp2_ns, CODEOWNERS,
  8. CONF_FRONT_PANEL_HAL_ID, FrontPanelHAL
  9. )
  10. AUTO_LOAD = ["xiaomi_bslamp2"]
  11. CONF_PART = "part"
  12. # The identifier values match the bit values of the events as defined
  13. # in ../front_panel_hal.h.
  14. PARTS = {
  15. "POWER_BUTTON" : 0b001 << 1,
  16. "POWER" : 0b001 << 1,
  17. "COLOR_BUTTON" : 0b010 << 1,
  18. "COLOR" : 0b010 << 1,
  19. "SLIDER" : 0b100 << 1,
  20. }
  21. XiaomiBslamp2TouchBinarySensor = bslamp2_ns.class_(
  22. "XiaomiBslamp2TouchBinarySensor", binary_sensor.BinarySensor, cg.Component)
  23. def get_part_id(value):
  24. normalized = re.sub('\s+', '_', value.upper())
  25. try:
  26. return PARTS[normalized]
  27. except KeyError:
  28. raise cv.Invalid(f"[{value}] is not a valid part identifier")
  29. def validate_for(value):
  30. parts = set()
  31. if isinstance(value, str):
  32. parts.add(get_part_id(value))
  33. elif isinstance(value, list):
  34. for x in value:
  35. parts.add(get_part_id(x))
  36. else:
  37. cv.Invalid("The value must be a single part identifier or a list of identifiers.")
  38. return list(parts)
  39. def validate_part(value):
  40. return [ get_part_id(value) ]
  41. def validate_binary_sensor(conf):
  42. if CONF_PART in conf and CONF_FOR in conf:
  43. raise cv.Invalid("Specify only one of [part] or [for]")
  44. if CONF_PART in conf and not CONF_FOR in conf:
  45. conf[CONF_FOR] = conf[CONF_PART]
  46. if CONF_FOR not in conf:
  47. raise cv.Invalid("'for' is a required option for [binary_sensor.xiaomi_bslamp2]")
  48. return conf
  49. CONFIG_SCHEMA = cv.All(
  50. binary_sensor.BINARY_SENSOR_SCHEMA.extend(
  51. {
  52. cv.GenerateID(): cv.declare_id(XiaomiBslamp2TouchBinarySensor),
  53. cv.GenerateID(CONF_FRONT_PANEL_HAL_ID): cv.use_id(FrontPanelHAL),
  54. # This option is not advertised in the documentation. It must be
  55. # considered deprecated. I'm not announcing it as such yet. Not sure
  56. # if it's useful to do so.
  57. cv.Optional(CONF_PART): validate_part,
  58. cv.Optional(CONF_FOR): validate_for,
  59. }
  60. ).extend(cv.COMPONENT_SCHEMA),
  61. validate_binary_sensor,
  62. )
  63. def to_code(config):
  64. var = cg.new_Pvariable(config[CONF_ID])
  65. yield cg.register_component(var, config)
  66. yield binary_sensor.register_binary_sensor(var, config)
  67. front_panel_hal_var = yield cg.get_variable(config[CONF_FRONT_PANEL_HAL_ID])
  68. cg.add(var.set_parent(front_panel_hal_var))
  69. for part_id in config[CONF_FOR]:
  70. cg.add(var.include_part(part_id))