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.

286 lines
11 KiB

Introduced a HUB component + front panel IRQ handling A HUB component was introduced. This HUB component has all the knowledge about the Yeelight Bedside Lamp 2 hardware. It known what pins are used, that PWM frequencies to use, what pins to switch in binary mode, etc. etc. No configuration is required for this HUB component. It's automatically loaded when the light component is loaded. The light component will use the HUB component to access the pins that are required for driving the LED circuitry. Note that this simplifies the configuration by A LOT. There's no need anymore to configure the pinouts in the YAML file. This is a logical route to take, since we're talking about a factory-produced PCB with a soldered on ESP32 chip, which uses the same GPIO's and settings on all produced devices (I presume). It would be quite redundant to force every user into configuring these pinouts themselves. ** Beware to update your device yaml configuration ** There are a few pinouts left to move into the HUB. I will do that in the next commit. Your device yaml configuration can be simplified along with these changes. Some of the keys in the existing light configuration block will no longer work and will have to be removed (red, green, blue, white). ** Further development ** The HUB will be extended make it the central component that also handles the I2C communication. This way, there is a central place to regulate the traffic to and from the front panel. We will be able to build upon this by implementing extra, fully separated components that handle for example the front panel light level, the power button, the color button and the slider. ** Interrupt handler for the I2C IRQ trigger pin ** One requirement for the I2C communication has already been implemented: an interrupt handler for the GPIO that is used by the front panel to signal the ESP that a new touch or release event is avilable to be read. It doens't do anything functionally right now, but if you watch the log file, you will see that touch events are detected and that they trigger some log messages.
3 years ago
  1. import esphome.codegen as cg
  2. import esphome.config_validation as cv
  3. from esphome.components import light
  4. from esphome import automation
  5. from esphome.core import coroutine, Lambda
  6. from esphome.const import (
  7. CONF_RED, CONF_GREEN, CONF_BLUE, CONF_WHITE, CONF_COLOR_TEMPERATURE,
  8. CONF_STATE, CONF_OUTPUT_ID, CONF_TRIGGER_ID, CONF_ID,
  9. CONF_TRANSITION_LENGTH, CONF_BRIGHTNESS, CONF_EFFECT, CONF_FLASH_LENGTH
  10. )
  11. from .. import bslamp2_ns, CODEOWNERS, CONF_LIGHT_HAL_ID, LightHAL
  12. AUTO_LOAD = ["xiaomi_bslamp2"]
  13. CONF_MASTER1 = "master1"
  14. CONF_MASTER2 = "master2"
  15. CONF_ON_BRIGHTNESS = "on_brightness"
  16. CONF_PRESET_ID = "preset_id"
  17. CONF_PRESETS_ID = "presets_id"
  18. CONF_PRESETS = "presets"
  19. CONF_NEXT = "next"
  20. CONF_GROUP = "group"
  21. CONF_PRESET = "preset"
  22. MIRED_MIN = 153
  23. MIRED_MAX = 588
  24. XiaomiBslamp2LightState = bslamp2_ns.class_("XiaomiBslamp2LightState", light.LightState)
  25. XiaomiBslamp2LightOutput = bslamp2_ns.class_("XiaomiBslamp2LightOutput", light.LightOutput)
  26. PresetsContainer = bslamp2_ns.class_("PresetsContainer", cg.Component)
  27. Preset = bslamp2_ns.class_("Preset", cg.Component)
  28. BrightnessTrigger = bslamp2_ns.class_("BrightnessTrigger", automation.Trigger.template())
  29. ActivatePresetAction = bslamp2_ns.class_("ActivatePresetAction", automation.Action)
  30. DiscoAction = bslamp2_ns.class_("DiscoAction", automation.Action)
  31. PRESETS_SCHEMA = cv.Schema({
  32. str.lower: cv.Schema({
  33. str.lower: light.automation.LIGHT_TURN_ON_ACTION_SCHEMA
  34. })
  35. })
  36. def validate_preset(config):
  37. has_rgb = CONF_RED in config or CONF_GREEN in config or CONF_BLUE in config
  38. has_white = CONF_COLOR_TEMPERATURE in config
  39. has_effect = CONF_EFFECT in config
  40. # Check mutual exclusivity of preset options.
  41. if (has_rgb + has_white + has_effect) > 1:
  42. raise cv.Invalid("Use only one of RGB light, white (color temperature) light or an effect")
  43. # Check the color temperature value range.
  44. if has_white:
  45. if config[CONF_COLOR_TEMPERATURE] < MIRED_MIN or config[CONF_COLOR_TEMPERATURE] > MIRED_MAX:
  46. raise cv.Invalid(f"The color temperature must be in the range {MIRED_MIN} - {MIRED_MAX}")
  47. # When defining an RGB color, it is allowed to omit RGB components that have value 0.
  48. if has_rgb:
  49. if CONF_RED not in config:
  50. config[CONF_RED] = 0
  51. if CONF_GREEN not in config:
  52. config[CONF_GREEN] = 0
  53. if CONF_BLUE not in config:
  54. config[CONF_BLUE] = 0
  55. return config
  56. PRESET_SCHEMA = cv.All(
  57. cv.Schema(
  58. {
  59. cv.GenerateID(CONF_ID): cv.use_id(XiaomiBslamp2LightState),
  60. cv.GenerateID(CONF_PRESET_ID): cv.declare_id(Preset),
  61. cv.Optional(CONF_EFFECT): cv.string,
  62. cv.Optional(CONF_COLOR_TEMPERATURE): cv.color_temperature,
  63. cv.Optional(CONF_RED): cv.percentage,
  64. cv.Optional(CONF_GREEN): cv.percentage,
  65. cv.Optional(CONF_BLUE): cv.percentage,
  66. cv.Optional(CONF_BRIGHTNESS): cv.percentage,
  67. cv.Optional(CONF_TRANSITION_LENGTH): cv.positive_time_period_milliseconds,
  68. }
  69. ),
  70. validate_preset
  71. )
  72. CONFIG_SCHEMA = light.RGB_LIGHT_SCHEMA.extend(
  73. {
  74. cv.GenerateID(CONF_ID): cv.declare_id(XiaomiBslamp2LightState),
  75. cv.GenerateID(CONF_LIGHT_HAL_ID): cv.use_id(LightHAL),
  76. cv.GenerateID(CONF_OUTPUT_ID): cv.declare_id(XiaomiBslamp2LightOutput),
  77. cv.Optional(CONF_ON_BRIGHTNESS): automation.validate_automation(
  78. {
  79. cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(BrightnessTrigger),
  80. }
  81. ),
  82. cv.GenerateID(CONF_PRESETS_ID): cv.declare_id(PresetsContainer),
  83. cv.Optional(CONF_PRESETS): cv.Schema({
  84. str.lower: cv.Schema({
  85. str.lower: PRESET_SCHEMA
  86. })
  87. }),
  88. }
  89. )
  90. def is_preset_group(value):
  91. return value
  92. def is_preset(value):
  93. return value
  94. def maybe_simple_preset_action(schema):
  95. def validator(value):
  96. if isinstance(value, dict):
  97. return schema(value)
  98. value = value.lower()
  99. config = {}
  100. if value == "next_group":
  101. config[CONF_NEXT] = CONF_GROUP
  102. elif value == "next_preset":
  103. config[CONF_NEXT] = CONF_PRESET
  104. elif "." not in value:
  105. config[CONF_GROUP] = value
  106. else:
  107. group, preset = value.split(".", 2)
  108. config[CONF_GROUP] = group
  109. config[CONF_PRESET] = preset
  110. return schema(config)
  111. return validator
  112. @automation.register_action(
  113. "light.disco_on", DiscoAction, light.automation.LIGHT_TURN_ON_ACTION_SCHEMA
  114. )
  115. def disco_action_on_to_code(config, action_id, template_arg, args):
  116. light_var = yield cg.get_variable(config[CONF_ID])
  117. var = cg.new_Pvariable(action_id, template_arg, light_var)
  118. if CONF_STATE in config:
  119. template_ = yield cg.templatable(config[CONF_STATE], args, bool)
  120. cg.add(var.set_state(template_))
  121. if CONF_TRANSITION_LENGTH in config:
  122. template_ = yield cg.templatable(
  123. config[CONF_TRANSITION_LENGTH], args, cg.uint32
  124. )
  125. cg.add(var.set_transition_length(template_))
  126. if CONF_FLASH_LENGTH in config:
  127. template_ = yield cg.templatable(config[CONF_FLASH_LENGTH], args, cg.uint32)
  128. cg.add(var.set_flash_length(template_))
  129. if CONF_BRIGHTNESS in config:
  130. template_ = yield cg.templatable(config[CONF_BRIGHTNESS], args, float)
  131. cg.add(var.set_brightness(template_))
  132. if CONF_RED in config:
  133. template_ = yield cg.templatable(config[CONF_RED], args, float)
  134. cg.add(var.set_red(template_))
  135. if CONF_GREEN in config:
  136. template_ = yield cg.templatable(config[CONF_GREEN], args, float)
  137. cg.add(var.set_green(template_))
  138. if CONF_BLUE in config:
  139. template_ = yield cg.templatable(config[CONF_BLUE], args, float)
  140. cg.add(var.set_blue(template_))
  141. if CONF_COLOR_TEMPERATURE in config:
  142. template_ = yield cg.templatable(config[CONF_COLOR_TEMPERATURE], args, float)
  143. cg.add(var.set_color_temperature(template_))
  144. if CONF_EFFECT in config:
  145. template_ = yield cg.templatable(config[CONF_EFFECT], args, cg.std_string)
  146. cg.add(var.set_effect(template_))
  147. yield var
  148. @automation.register_action(
  149. "light.disco_off", DiscoAction, light.automation.LIGHT_TURN_OFF_ACTION_SCHEMA
  150. )
  151. def disco_action_off_to_code(config, action_id, template_arg, args):
  152. light_var = yield cg.get_variable(config[CONF_ID])
  153. var = cg.new_Pvariable(action_id, template_arg, light_var)
  154. cg.add(var.set_disco_state(False))
  155. yield var
  156. USED_PRESETS = []
  157. def register_preset_action(value):
  158. if "group" in value and not isinstance(value["group"], Lambda):
  159. if "preset" in value and not isinstance(value["preset"], Lambda):
  160. preset_id = [value['group'], value['preset']]
  161. else:
  162. preset_id = [value["group"], None]
  163. USED_PRESETS.append(preset_id)
  164. return value
  165. @automation.register_action(
  166. "preset.activate",
  167. ActivatePresetAction,
  168. cv.All(
  169. maybe_simple_preset_action(cv.Any(
  170. cv.Schema({
  171. cv.GenerateID(CONF_PRESETS_ID): cv.use_id(PresetsContainer),
  172. cv.Required(CONF_GROUP): cv.templatable(cv.string),
  173. cv.Optional(CONF_PRESET): cv.templatable(cv.string)
  174. }),
  175. cv.Schema({
  176. cv.GenerateID(CONF_PRESETS_ID): cv.use_id(PresetsContainer),
  177. cv.Required(CONF_NEXT): cv.one_of(CONF_GROUP, CONF_PRESET, lower=True)
  178. })
  179. )),
  180. register_preset_action
  181. ),
  182. )
  183. def preset_activate_to_code(config, action_id, template_arg, args):
  184. presets_var = yield cg.get_variable(config[CONF_PRESETS_ID])
  185. action_var = cg.new_Pvariable(action_id, template_arg, presets_var)
  186. if CONF_NEXT in config:
  187. cg.add(action_var.set_operation(f"next_{config[CONF_NEXT]}"))
  188. elif CONF_PRESET in config:
  189. cg.add(action_var.set_operation("activate_preset"))
  190. group_template_ = yield cg.templatable(config[CONF_GROUP], args, cg.std_string)
  191. cg.add(action_var.set_group(group_template_))
  192. preset_template_ = yield cg.templatable(config[CONF_PRESET], args, cg.std_string)
  193. cg.add(action_var.set_preset(preset_template_))
  194. else:
  195. cg.add(action_var.set_operation("activate_group"))
  196. group_template_ = yield cg.templatable(config[CONF_GROUP], args, cg.std_string)
  197. cg.add(action_var.set_group(group_template_))
  198. yield action_var
  199. @coroutine
  200. def light_output_to_code(config):
  201. light_output_var = cg.new_Pvariable(config[CONF_OUTPUT_ID])
  202. yield light.register_light(light_output_var, config)
  203. light_hal_var = yield cg.get_variable(config[CONF_LIGHT_HAL_ID])
  204. cg.add(light_output_var.set_parent(light_hal_var))
  205. if hasattr(light, "types") and hasattr(light.types, "COLOR_MODES"):
  206. cg.add_define('HAS_COLOR_MODES')
  207. @coroutine
  208. def on_brightness_to_code(config):
  209. light_output_var = yield cg.get_variable(config[CONF_OUTPUT_ID])
  210. for config in config.get(CONF_ON_BRIGHTNESS, []):
  211. trigger = cg.new_Pvariable(config[CONF_TRIGGER_ID], light_output_var)
  212. yield automation.build_automation(trigger, [(float, "x")], config)
  213. @coroutine
  214. def preset_to_code(config, preset_group, preset_name):
  215. light_var = yield cg.get_variable(config[CONF_ID])
  216. preset_var = cg.new_Pvariable(
  217. config[CONF_PRESET_ID], light_var, preset_group, preset_name)
  218. if CONF_TRANSITION_LENGTH in config:
  219. cg.add(preset_var.set_transition_length(config[CONF_TRANSITION_LENGTH]))
  220. if CONF_BRIGHTNESS in config:
  221. cg.add(preset_var.set_brightness(config[CONF_BRIGHTNESS]))
  222. if CONF_RED in config:
  223. cg.add(preset_var.set_red(config[CONF_RED]))
  224. if CONF_GREEN in config:
  225. cg.add(preset_var.set_green(config[CONF_GREEN]))
  226. if CONF_BLUE in config:
  227. cg.add(preset_var.set_blue(config[CONF_BLUE]))
  228. if CONF_COLOR_TEMPERATURE in config:
  229. cg.add(preset_var.set_color_temperature(config[CONF_COLOR_TEMPERATURE]))
  230. if CONF_EFFECT in config:
  231. cg.add(preset_var.set_effect(config[CONF_EFFECT]))
  232. else:
  233. cg.add(preset_var.set_effect("None"))
  234. yield cg.register_component(preset_var, config)
  235. @coroutine
  236. def presets_to_code(config):
  237. presets_var = cg.new_Pvariable(config[CONF_PRESETS_ID])
  238. yield cg.register_component(presets_var, config)
  239. for preset_group, presets in config.get(CONF_PRESETS, {}).items():
  240. for preset_name, preset_config in presets.items():
  241. preset = yield preset_to_code(preset_config, preset_group, preset_name)
  242. cg.add(presets_var.add_preset(preset))
  243. def to_code(config):
  244. yield light_output_to_code(config)
  245. yield on_brightness_to_code(config)
  246. yield presets_to_code(config)
  247. def validate(config):
  248. valid_presets = config.get(CONF_PRESETS, {});
  249. for group, preset in USED_PRESETS:
  250. if group not in valid_presets:
  251. raise cv.Invalid(f"Invalid light preset group '{group}' used")
  252. if preset is not None and preset not in valid_presets[group]:
  253. raise cv.Invalid(f"Invalid light preset '{group}.{preset}' used")
  254. return config
  255. FINAL_VALIDATE_SCHEMA = cv.Schema(validate);