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:
Dorian Zedler 2023-03-12 21:26:27 +01:00 committed by GitHub
parent 5a56644702
commit 32a0a60480
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 15 deletions

View file

@ -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)),

View file

@ -2528,6 +2528,8 @@ color:
red: 0%
green: 1%
blue: 100%
- id: kbx_green
hex: "3DEC55"
display:
- platform: lcd_gpio