11import logging
22import io
3- import itertools
43import aiohttp
5- import colorgram
64
75from homeassistant .core import HomeAssistant
86from homeassistant .helpers .typing import ConfigType , DiscoveryInfoType
1917
2018from . import const
2119from .entity_resolver import expand_entities
20+ from .color_extract import extract_palette
2221
2322_LOGGER = logging .getLogger (__name__ )
2423
@@ -35,7 +34,8 @@ async def async_setup_platform(
3534 hass ,
3635 config [const .CONF_NAME ],
3736 config [const .CONF_TARGET ],
38- config .get (const .CONF_FILTER_ON ) or False
37+ config .get (const .CONF_FILTER_ON ) or False ,
38+ True if (downsample := config .get (const .CONF_DOWNSAMPLE )) is None else downsample ,
3939 )
4040
4141 add_entities ([cast_device ])
@@ -46,11 +46,12 @@ class LightCastPlayer(MediaPlayerEntity):
4646 _attr_supported_features = MediaPlayerEntityFeature .PLAY_MEDIA | MediaPlayerEntityFeature .BROWSE_MEDIA
4747 _attr_device_class = MediaPlayerDeviceClass .TV
4848
49- def __init__ (self , hass : HomeAssistant , name : str , device_target : str , filter_on : bool ) -> None :
49+ def __init__ (self , hass : HomeAssistant , name : str , device_target : str , filter_on : bool , downsample : bool ) -> None :
5050 self .hass = hass
5151 self ._attr_name = name
5252 self .device_target = device_target
5353 self .filter_on = filter_on
54+ self .downsample = downsample
5455
5556 async def async_browse_media (self , media_content_type : str | None = None ,
5657 media_content_id : str | None = None ) -> BrowseMedia :
@@ -95,21 +96,16 @@ async def process_image(self, media_type: str, media_id: str) -> None:
9596 ) as response :
9697 response_data = await response .read ()
9798
98- n_colors = len (valid_entities )
99- _LOGGER .info ('Downloaded image, extracting palette of %d colors' , n_colors )
99+ palette = extract_palette (io .BytesIO (response_data ), len (valid_entities ), downsample = self .downsample )
100100
101- extracted_colors = colorgram .extract (io .BytesIO (response_data ), n_colors )
102- _LOGGER .info ('Extracted palette of %d colors from image' , len (extracted_colors ))
103-
104- for e , color in zip (valid_entities , itertools .cycle (extracted_colors )):
105- rgb_color = [color .rgb .r , color .rgb .g , color .rgb .b ]
106- _LOGGER .info ('Set light %s to %s' , e .entity_id , rgb_color )
101+ for e , color in zip (valid_entities , palette ):
102+ _LOGGER .info ('Set light %s to %s' , e .entity_id , color )
107103 await self .hass .services .async_call (
108104 light .DOMAIN ,
109105 light .SERVICE_TURN_ON ,
110106 {
111107 ATTR_ENTITY_ID : e .entity_id ,
112- light .ATTR_RGB_COLOR : rgb_color
108+ light .ATTR_RGB_COLOR : color
113109 }
114110 )
115111
0 commit comments