1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-10 22:10:02 +00:00
Files
.devcontainer
.github
.vscode
homeassistant
auth
backports
brands
components
3_day_blinds
abode
accuweather
acer_projector
acmeda
actiontec
adax
adguard
ads
advantage_air
aemet
aep_ohio
aep_texas
aftership
agent_dvr
air_quality
airly
airnow
airq
airthings
airthings_ble
airtouch4
airvisual
airvisual_pro
airzone
airzone_cloud
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
alpha_vantage
amazon_polly
amberelectric
ambiclimate
ambient_station
amcrest
amp_motorization
ampio
analytics
android_ip_webcam
androidtv
androidtv_remote
anel_pwrctrl
anova
anthemav
anwb_energie
aosmith
apache_kafka
apcupsd
api
appalachianpower
apple_tv
application_credentials
apprise
aprs
aqualogic
aquostv
aranet
arcam_fmj
arest
arris_tg2492lg
aruba
arwn
aseko_pool_live
assist_pipeline
asterisk_cdr
asterisk_mbox
asuswrt
atag
aten_pe
atlanticcityelectric
atome
august
august_ble
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
avea
avion
awair
aws
axis
azure_devops
azure_event_hub
azure_service_bus
backup
baf
baidu
balboa
bayesian
bbox
beewi_smartclim
bge
binary_sensor
bitcoin
bizkaibus
blackbird
blebox
blink
blinksticklight
bliss_automation
bloc_blinds
blockchain
bloomsky
blue_current
bluemaestro
blueprint
bluesound
bluetooth
bluetooth_adapters
bluetooth_le_tracker
bluetooth_tracker
bmw_connected_drive
bond
bosch_shc
brandt
braviatv
brel_home
broadlink
brother
brottsplatskartan
browser
brunt
bsblan
bswitch
bt_home_hub_5
bt_smarthub
bthome
bticino
bubendorff
buienradar
button
caldav
calendar
camera
canary
cast
ccm15
cert_expiry
channels
circuit
cisco_ios
cisco_mobility_express
cisco_webex_teams
citybikes
clementine
clickatell
clicksend
clicksend_tts
climate
cloud
cloudflare
cmus
co2signal
coinbase
color_extractor
comed
comed_hourly_pricing
comelit
comfoconnect
command_line
compensation
concord232
coned
config
configurator
control4
conversation
coolmaster
counter
cover
cozytouch
cppm_tracker
cpuspeed
cribl
crownstone
cups
currencylayer
dacia
daikin
danfoss_air
datadog
date
datetime
ddwrt
debugpy
deconz
decora
decora_wifi
default_config
delijn
delmarva
deluge
demo
denon
denonavr
derivative
devialet
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
diagnostics
dialogflow
diaz
digital_loggers
digital_ocean
directv
discogs
discord
discovergy
dlib_face_detect
dlib_face_identify
dlink
dlna_dmr
dlna_dms
dnsip
dominos
doods
doorbird
dooya
dormakaba_dkey
dovado
downloader
dremel_3d_printer
drop_connect
dsmr
dsmr_reader
dte_energy_bridge
dublin_bus_transport
duckdns
dunehd
duotecno
dwd_weather_warnings
dweet
dynalite
eafm
eastron
easyenergy
ebox
ebusd
ecoal_boiler
ecobee
ecoforest
econet
ecovacs
ecowitt
eddystone_temperature
edimax
edl21
efergy
egardia
eight_sleep
electrasmart
electric_kiwi
elgato
eliqonline
elkm1
elmax
elv
emby
emoncms
emoncms_history
emonitor
emulated_hue
emulated_kasa
emulated_roku
energie_vanons
energy
energyzero
enigma2
enmax
enocean
enphase_envoy
entur_public_transport
environment_canada
envisalink
ephember
epson
epsonworkforce
escea
esera_onewire
esphome
etherscan
eufy
eufylife_ble
event
evergy
everlights
evil_genius_labs
evohome
ezviz
faa_delays
facebook
facebox
fail2ban
familyhub
fan
fastdotcom
feedreader
ffmpeg
ffmpeg_motion
ffmpeg_noise
fibaro
fido
file
file_upload
filesize
filter
fints
fire_tv
fireservicerota
firmata
fitbit
fivem
fixer
fjaraskupan
fleetgo
flexit
flexit_bacnet
flexom
flic
flick_electric
flipr
flo
flock
flume
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
fortios
foscam
foursquare
free_mobile
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
frontier_silicon
fujitsu_anywair
fully_kiosk
futurenow
garadget
garages_amsterdam
gardena_bluetooth
gaviota
gc100
gdacs
generic
generic_hygrostat
generic_thermostat
geniushub
geo_json_events
geo_location
geo_rss_events
geocaching
geofency
geonetnz_quakes
geonetnz_volcano
gios
github
gitlab_ci
gitter
glances
goalzero
gogogate2
goodwe
google
google_assistant
google_assistant_sdk
google_cloud
google_domains
google_generative_ai_conversation
google_mail
google_maps
google_pubsub
google_sheets
google_tasks
google_translate
google_travel_time
google_wifi
govee_ble
gpsd
gpslogger
graphite
gree
greeneye_monitor
greenwave
group
growatt_server
gstreamer
gtfs
guardian
habitica
hardkernel
hardware
harman_kardon_avr
harmony
hassio
havana_shade
haveibeenpwned
hddtemp
hdmi_cec
heatmiser
heiwa
heos
here_travel_time
hexaom
hi_kumo
hikvision
hikvisioncam
hisense_aehw4a1
history
history_stats
hitron_coda
hive
hlk_sw16
holiday
home_connect
home_plus_control
homeassistant
homeassistant_alerts
homeassistant_green
homeassistant_hardware
homeassistant_sky_connect
homeassistant_yellow
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
homeworks
honeywell
horizon
hp_ilo
html5
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
hurrican_shutters_wholesale
hvv_departures
hydrawise
hyperion
ialarm
iammeter
iaqualink
ibeacon
icloud
idasen_desk
idteck_prox
ifttt
iglo
ign_sismologia
ihc
image
image_processing
image_upload
imap
improv_ble
incomfort
indianamichiganpower
influxdb
inkbird
input_boolean
input_button
input_datetime
input_number
input_select
input_text
inspired_shades
insteon
integration
intellifire
intent
intent_script
intesishome
ios
iotawatt
iperf3
ipma
ipp
iqvia
irish_rail_transport
islamic_prayer_times
ismartwindow
iss
isy994
itach
itunes
izone
jellyfin
jewish_calendar
joaoapps_join
juicenet
justnimbus
jvc_projector
kaiterra
kaleidescape
kankun
keba
keenetic_ndms2
kef
kegtron
kentuckypower
keyboard
keyboard_remote
keymitt_ble
kira
kitchen_sink
kiwi
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
kwb
lacrosse
lacrosse_view
lametric
landisgyr_heat_meter
lannouncer
lastfm
launch_library
laundrify
lawn_mower
lcn
ld2410_ble
led_ble
legrand
lg_netcast
lg_soundbar
lidarr
life360
lifx
lifx_cloud
light
lightwave
limitlessled
linear_garage_door
linksys_smart
linode
linux_battery
lirc
litejet
litterrobot
livisi
llamalab_automate
local_calendar
local_file
local_ip
local_todo
locative
lock
logbook
logentries
logger
logi_circle
london_air
london_underground
lookin
loqed
lovelace
luci
luftdaten
lupusec
lutron
lutron_caseta
luxaflex
lw12wifi
lyric
mailbox
mailgun
manual
manual_mqtt
map
marantz
martec
marytts
mastodon
matrix
matter
maxcube
mazda
meater
medcom_ble
media_extractor
media_player
media_source
mediaroom
melcloud
melissa
melnor
meraki
message_bird
met
met_eireann
meteo_france
meteoalarm
meteoclimatic
metoffice
mfi
microsoft
microsoft_face
microsoft_face_detect
microsoft_face_identify
mijndomein_energie
mikrotik
mill
min_max
minecraft_server
minio
mjpeg
moat
mobile_app
mochad
modbus
modem_callerid
modern_forms
moehlenhoff_alpha2
mold_indicator
monessen
monoprice
moon
mopeka
motion_blinds
motioneye
motionmount
mpd
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
msteams
mullvad
mutesync
mvglive
my
mycroft
myq
mysensors
mystrom
mythicbeastsdns
nad
nam
namecheapdns
nanoleaf
neato
nederlandse_spoorwegen
ness_alarm
nest
netatmo
netdata
netgear
netgear_lte
netio
network
neurio_energy
nexia
nexity
nextbus
nextcloud
nextdns
nfandroidtv
nibe_heatpump
nightscout
niko_home_control
nilu
nina
nissan_leaf
nmap_tracker
nmbs
no_ip
noaa_tides
nobo_hub
norway_air
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nutrichef
nws
nx584
nzbget
oasa_telematics
obihai
octoprint
oem
ohmconnect
ombi
omnilogic
onboarding
oncue
ondilo_ico
onewire
onkyo
onvif
open_meteo
openai_conversation
openalpr_cloud
opencv
openerz
openevse
openexchangerates
opengarage
openhardwaremonitor
openhome
opensensemap
opensky
opentherm_gw
openuv
openweathermap
opnsense
opower
opple
oralb
oru
oru_opower
orvibo
osoenergy
osramlightify
otbr
otp
ourgroceries
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_bluray
panasonic_viera
pandora
panel_custom
panel_iframe
pcs_lighting
peco
peco_opower
pegel_online
pencom
pepco
permobil
persistent_notification
person
pge
philips_js
pi_hole
picnic
picotts
pilight
ping
pioneer
piper
pjlink
plaato
plant
plex
plugwise
plum_lightpad
pocketcasts
point
poolsense
portlandgeneral
powerwall
private_ble_device
profiler
progettihwsw
proliphix
prometheus
prosegur
prowl
proximity
proxmoxve
proxy
prusalink
ps4
pse
psoklahoma
pulseaudio_loopback
pure_energie
purpleair
push
pushbullet
pushover
pushsafer
pvoutput
pvpc_hourly_pricing
pyload
python_script
qbittorrent
qingping
qld_bushfire
qnap
qnap_qsw
qrcode
quadrafire
quantum_gateway
qvr_pro
qwikswitch
rachio
radarr
radio_browser
radiotherm
rainbird
raincloud
rainforest_eagle
rainmachine
random
rapt_ble
raspberry_pi
raspyrfm
raven_rock_mfg
rdw
recollect_waste
recorder
recovery_mode
recswitch
reddit
refoss
rejseplanen
remember_the_milk
remote
remote_rpi_gpio
renault
renson
reolink
repairs
repetier
rest
rest_command
rexel
rflink
rfxtrx
rhasspy
ridwell
ring
ripple
risco
rituals_perfume_genie
rmvtransport
roborock
rocketchat
roku
roomba
roon
route53
rova
rpi_camera
rpi_power
rss_feed_template
rtorrent
rtsp_to_webrtc
ruckus_unleashed
russound_rio
russound_rnet
ruuvi_gateway
ruuvitag_ble
rympro
sabnzbd
saj
samsungtv
satel_integra
scene
schedule
schlage
schluter
scl
scrape
screenaway
screenlogic
script
scsgate
search
season
select
sendgrid
sense
sensibo
sensirion_ble
sensor
sensorblue
sensorpro
sensorpush
sentry
senz
serial
serial_pm
sesame
seven_segments
seventeentrack
sfr_box
sharkiq
shell_command
shelly
shodan
shopping_list
sia
sigfox
sighthound
signal_messenger
simplepush
simplisafe
simply_automated
simu
simulated
sinch
siren
sisyphus
sky_hub
skybeacon
skybell
slack
sleepiq
slide
slimproto
sma
smappee
smart_blinds
smart_home
smart_meter_texas
smarther
smartthings
smarttub
smarty
smhi
sms
smtp
snapcast
snips
snmp
snooz
solaredge
solaredge_local
solarlog
solax
soma
somfy
somfy_mylink
sonarr
songpal
sonos
sony_projector
soundtouch
spaceapi
spc
speedtestdotnet
spider
splunk
spotify
sql
squeezebox
srp_energy
ssdp
starline
starlingbank
starlink
startca
statistics
statsd
steam_online
steamist
stiebel_eltron
stookalert
stookwijzer
stream
streamlabswater
stt
subaru
suez_water
sun
sunweg
supervisord
supla
surepetcare
swepco
swiss_hydrological_data
swiss_public_transport
swisscom
switch
switch_as_x
switchbee
switchbot
switchbot_cloud
switcher_kis
switchmate
symfonisk
syncthing
syncthru
synology_chat
synology_dsm
synology_srm
syslog
system_bridge
system_health
system_log
systemmonitor
tado
tag
tailscale
tailwind
tami4
tank_utility
tankerkoenig
tapsaff
tasmota
tautulli
tcp
ted5000
telegram
telegram_bot
tellduslive
tellstick
telnet
temper
template
tensorflow
tesla_wall_connector
tessie
text
tfiac
thermobeacon
thermoplus
thermopro
thermoworks_smoke
thethingsnetwork
thingspeak
thinkingcleaner
thomson
thread
threshold
tibber
tikteck
tile
tilt_ble
time
time_date
timer
tmb
tod
todo
todoist
tolo
tomato
tomorrowio
toon
torque
totalconnect
touchline
tplink
tplink_lte
tplink_omada
traccar
trace
tractive
tradfri
trafikverket_camera
trafikverket_ferry
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
travisci
trend
tts
tuya
twentemilieu
twilio
twilio_call
twilio_sms
twinkly
twitch
twitter
ubiwizz
ubus
ue_smart_radio
uk_transport
ukraine_alarm
ultraloq
unifi
unifi_direct
unifiled
unifiprotect
universal
upb
upc_connect
upcloud
update
upnp
uprise_smart_shades
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
v2c
vacuum
vallox
valve
vasttrafik
velbus
velux
venstar
vera
verisure
vermont_castings
versasense
version
vesync
viaggiatreno
vicare
vilfo
vivotek
vizio
vlc
vlc_telnet
vodafone_station
voicerss
voip
volkszaehler
volumio
volvooncall
vulcan
vultr
w800rf32
wake_on_lan
wake_word
wallbox
waqi
water_heater
waterfurnace
watson_iot
watson_tts
watttime
waze_travel_time
weather
weatherflow
weatherkit
webhook
webostv
websocket_api
wemo
whirlpool
whisper
whois
wiffi
wilight
wirelesstag
withings
wiz
wled
__init__.py
binary_sensor.py
button.py
config_flow.py
const.py
coordinator.py
diagnostics.py
helpers.py
light.py
manifest.json
models.py
number.py
select.py
sensor.py
services.yaml
strings.json
switch.py
update.py
wolflink
workday
worldclock
worldtidesinfo
worxlandroid
ws66i
wsdot
wyoming
x10
xbox
xeoma
xiaomi
xiaomi_aqara
xiaomi_ble
xiaomi_miio
xiaomi_tv
xmpp
xs1
yale_home
yale_smart_alarm
yalexs_ble
yamaha
yamaha_musiccast
yandex_transport
yandextts
yardian
yeelight
yeelightsunflower
yi
yolink
youless
youtube
zabbix
zamg
zengge
zeroconf
zerproc
zestimate
zeversolar
zha
zhong_hong
ziggo_mediabox_xl
zodiac
zone
zoneminder
zwave_js
zwave_me
__init__.py
generated
helpers
scripts
util
__init__.py
__main__.py
block_async_io.py
bootstrap.py
config.py
config_entries.py
const.py
core.py
data_entry_flow.py
exceptions.py
loader.py
package_constraints.txt
requirements.py
runner.py
setup.py
strings.json
machine
pylint
rootfs
script
tests
.core_files.yaml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.pre-commit-config.yaml
.prettierignore
.strict-typing
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
build.yaml
codecov.yml
mypy.ini
pyproject.toml
requirements.txt
requirements_all.txt
requirements_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
core/homeassistant/components/wled/light.py
2023-10-06 20:04:44 +02:00

276 lines
9.1 KiB
Python

"""Support for LED lights."""
from __future__ import annotations
from functools import partial
from typing import Any, cast
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_EFFECT,
ATTR_RGB_COLOR,
ATTR_RGBW_COLOR,
ATTR_TRANSITION,
ColorMode,
LightEntity,
LightEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import ATTR_COLOR_PRIMARY, ATTR_ON, ATTR_SEGMENT_ID, DOMAIN
from .coordinator import WLEDDataUpdateCoordinator
from .helpers import wled_exception_handler
from .models import WLEDEntity
PARALLEL_UPDATES = 1
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up WLED light based on a config entry."""
coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
if coordinator.keep_main_light:
async_add_entities([WLEDMainLight(coordinator=coordinator)])
update_segments = partial(
async_update_segments,
coordinator,
set(),
async_add_entities,
)
coordinator.async_add_listener(update_segments)
update_segments()
class WLEDMainLight(WLEDEntity, LightEntity):
"""Defines a WLED main light."""
_attr_color_mode = ColorMode.BRIGHTNESS
_attr_icon = "mdi:led-strip-variant"
_attr_translation_key = "main"
_attr_supported_features = LightEntityFeature.TRANSITION
_attr_supported_color_modes = {ColorMode.BRIGHTNESS}
def __init__(self, coordinator: WLEDDataUpdateCoordinator) -> None:
"""Initialize WLED main light."""
super().__init__(coordinator=coordinator)
self._attr_unique_id = coordinator.data.info.mac_address
@property
def brightness(self) -> int | None:
"""Return the brightness of this light between 1..255."""
return self.coordinator.data.state.brightness
@property
def is_on(self) -> bool:
"""Return the state of the light."""
return bool(self.coordinator.data.state.on)
@property
def available(self) -> bool:
"""Return if this main light is available or not."""
return self.coordinator.has_main_light and super().available
@wled_exception_handler
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the light."""
transition = None
if ATTR_TRANSITION in kwargs:
# WLED uses 100ms per unit, so 10 = 1 second.
transition = round(kwargs[ATTR_TRANSITION] * 10)
await self.coordinator.wled.master(on=False, transition=transition)
@wled_exception_handler
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the light."""
transition = None
if ATTR_TRANSITION in kwargs:
# WLED uses 100ms per unit, so 10 = 1 second.
transition = round(kwargs[ATTR_TRANSITION] * 10)
await self.coordinator.wled.master(
on=True, brightness=kwargs.get(ATTR_BRIGHTNESS), transition=transition
)
class WLEDSegmentLight(WLEDEntity, LightEntity):
"""Defines a WLED light based on a segment."""
_attr_supported_features = LightEntityFeature.EFFECT | LightEntityFeature.TRANSITION
_attr_icon = "mdi:led-strip-variant"
def __init__(
self,
coordinator: WLEDDataUpdateCoordinator,
segment: int,
) -> None:
"""Initialize WLED segment light."""
super().__init__(coordinator=coordinator)
self._rgbw = coordinator.data.info.leds.rgbw
self._wv = coordinator.data.info.leds.wv
self._segment = segment
# Segment 0 uses a simpler name, which is more natural for when using
# a single segment / using WLED with one big LED strip.
if segment == 0:
self._attr_name = None
else:
self._attr_name = f"Segment {segment}"
self._attr_unique_id = (
f"{self.coordinator.data.info.mac_address}_{self._segment}"
)
self._attr_color_mode = ColorMode.RGB
self._attr_supported_color_modes = {ColorMode.RGB}
if self._rgbw and self._wv:
self._attr_color_mode = ColorMode.RGBW
self._attr_supported_color_modes = {ColorMode.RGBW}
@property
def available(self) -> bool:
"""Return True if entity is available."""
try:
self.coordinator.data.state.segments[self._segment]
except IndexError:
return False
return super().available
@property
def rgb_color(self) -> tuple[int, int, int] | None:
"""Return the color value."""
return self.coordinator.data.state.segments[self._segment].color_primary[:3]
@property
def rgbw_color(self) -> tuple[int, int, int, int] | None:
"""Return the color value."""
return cast(
tuple[int, int, int, int],
self.coordinator.data.state.segments[self._segment].color_primary,
)
@property
def effect(self) -> str | None:
"""Return the current effect of the light."""
return self.coordinator.data.state.segments[self._segment].effect.name
@property
def brightness(self) -> int | None:
"""Return the brightness of this light between 1..255."""
state = self.coordinator.data.state
# If this is the one and only segment, calculate brightness based
# on the main and segment brightness
if not self.coordinator.has_main_light:
return int(
(state.segments[self._segment].brightness * state.brightness) / 255
)
return state.segments[self._segment].brightness
@property
def effect_list(self) -> list[str]:
"""Return the list of supported effects."""
return [effect.name for effect in self.coordinator.data.effects]
@property
def is_on(self) -> bool:
"""Return the state of the light."""
state = self.coordinator.data.state
# If there is no main, we take the main state into account
# on the segment level.
if not self.coordinator.has_main_light and not state.on:
return False
return bool(state.segments[self._segment].on)
@wled_exception_handler
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the light."""
transition = None
if ATTR_TRANSITION in kwargs:
# WLED uses 100ms per unit, so 10 = 1 second.
transition = round(kwargs[ATTR_TRANSITION] * 10)
# If there is no main control, and only 1 segment, handle the main
if not self.coordinator.has_main_light:
await self.coordinator.wled.master(on=False, transition=transition)
return
await self.coordinator.wled.segment(
segment_id=self._segment, on=False, transition=transition
)
@wled_exception_handler
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the light."""
data: dict[str, Any] = {
ATTR_ON: True,
ATTR_SEGMENT_ID: self._segment,
}
if ATTR_RGB_COLOR in kwargs:
data[ATTR_COLOR_PRIMARY] = kwargs[ATTR_RGB_COLOR]
if ATTR_RGBW_COLOR in kwargs:
data[ATTR_COLOR_PRIMARY] = kwargs[ATTR_RGBW_COLOR]
if ATTR_TRANSITION in kwargs:
# WLED uses 100ms per unit, so 10 = 1 second.
data[ATTR_TRANSITION] = round(kwargs[ATTR_TRANSITION] * 10)
if ATTR_BRIGHTNESS in kwargs:
data[ATTR_BRIGHTNESS] = kwargs[ATTR_BRIGHTNESS]
if ATTR_EFFECT in kwargs:
data[ATTR_EFFECT] = kwargs[ATTR_EFFECT]
# If there is no main control, and only 1 segment, handle the main
if not self.coordinator.has_main_light:
main_data = {ATTR_ON: True}
if ATTR_BRIGHTNESS in data:
main_data[ATTR_BRIGHTNESS] = data[ATTR_BRIGHTNESS]
data[ATTR_BRIGHTNESS] = 255
if ATTR_TRANSITION in data:
main_data[ATTR_TRANSITION] = data[ATTR_TRANSITION]
del data[ATTR_TRANSITION]
await self.coordinator.wled.segment(**data)
await self.coordinator.wled.master(**main_data)
return
await self.coordinator.wled.segment(**data)
@callback
def async_update_segments(
coordinator: WLEDDataUpdateCoordinator,
current_ids: set[int],
async_add_entities: AddEntitiesCallback,
) -> None:
"""Update segments."""
segment_ids = {light.segment_id for light in coordinator.data.state.segments}
new_entities: list[WLEDMainLight | WLEDSegmentLight] = []
# More than 1 segment now? No main? Add main controls
if not coordinator.keep_main_light and (
len(current_ids) < 2 and len(segment_ids) > 1
):
new_entities.append(WLEDMainLight(coordinator))
# Process new segments, add them to Home Assistant
for segment_id in segment_ids - current_ids:
current_ids.add(segment_id)
new_entities.append(WLEDSegmentLight(coordinator, segment_id))
async_add_entities(new_entities)