mirror of
https://github.com/esphome/esphome.git
synced 2024-11-25 08:28:12 +01:00
Feat: add support for hex color in color component (#4493)
* Feat: add support for hex color in color component * Chore: move hex color validator to color component * Chore: add test * Chore: fix formatting * Chore: make linter happy * Chore: make linter happy * Fix: parse correct offsets Co-authored-by: Oxan van Leeuwen <oxan@oxanvanleeuwen.nl> * Chore: use cv.Invalid * Fix: remove # because it indicates a comment in yaml * Fix: only allow hex if no other color value is set * Fix: tests * Fix: mutual exclusion of raw and hex colors * Chore: format file * Update __init__.py --------- Co-authored-by: Oxan van Leeuwen <oxan@oxanvanleeuwen.nl> Co-authored-by: Jesse Hills <3060199+jesserockz@users.noreply.github.com>
This commit is contained in:
parent
bf79a700b7
commit
b6f628ee40
2 changed files with 46 additions and 15 deletions
|
@ -10,8 +10,20 @@ CONF_RED_INT = "red_int"
|
|||
CONF_GREEN_INT = "green_int"
|
||||
CONF_BLUE_INT = "blue_int"
|
||||
CONF_WHITE_INT = "white_int"
|
||||
CONF_HEX = "hex"
|
||||
|
||||
CONFIG_SCHEMA = cv.Schema(
|
||||
|
||||
def hex_color(value):
|
||||
if len(value) != 6:
|
||||
raise cv.Invalid("Color must have six digits")
|
||||
try:
|
||||
return (int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16))
|
||||
except ValueError as exc:
|
||||
raise cv.Invalid("Color must be hexadecimal") from exc
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.Any(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_ID): cv.declare_id(ColorStruct),
|
||||
cv.Exclusive(CONF_RED, "red"): cv.percentage,
|
||||
|
@ -23,10 +35,17 @@ CONFIG_SCHEMA = cv.Schema(
|
|||
cv.Exclusive(CONF_WHITE, "white"): cv.percentage,
|
||||
cv.Exclusive(CONF_WHITE_INT, "white"): cv.uint8_t,
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA)
|
||||
).extend(cv.COMPONENT_SCHEMA),
|
||||
cv.Schema(
|
||||
{
|
||||
cv.Required(CONF_ID): cv.declare_id(ColorStruct),
|
||||
cv.Required(CONF_HEX): hex_color,
|
||||
}
|
||||
).extend(cv.COMPONENT_SCHEMA),
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
def from_rgbw(config):
|
||||
r = 0
|
||||
if CONF_RED in config:
|
||||
r = int(config[CONF_RED] * 255)
|
||||
|
@ -51,6 +70,16 @@ async def to_code(config):
|
|||
elif CONF_WHITE_INT in config:
|
||||
w = config[CONF_WHITE_INT]
|
||||
|
||||
return (r, g, b, w)
|
||||
|
||||
|
||||
async def to_code(config):
|
||||
if CONF_HEX in config:
|
||||
r, g, b = config[CONF_HEX]
|
||||
w = 0
|
||||
else:
|
||||
r, g, b, w = from_rgbw(config)
|
||||
|
||||
cg.new_variable(
|
||||
config[CONF_ID],
|
||||
cg.StructInitializer(ColorStruct, ("r", r), ("g", g), ("b", b), ("w", w)),
|
||||
|
|
|
@ -2528,6 +2528,8 @@ color:
|
|||
red: 0%
|
||||
green: 1%
|
||||
blue: 100%
|
||||
- id: kbx_green
|
||||
hex: "3DEC55"
|
||||
|
||||
display:
|
||||
- platform: lcd_gpio
|
||||
|
|
Loading…
Reference in a new issue