-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
241 lines (196 loc) · 7.75 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""Module for ambient_extractor (RGB/brightness extraction from images) component."""
import asyncio
import io
import logging
from PIL import UnidentifiedImageError, Image, ImageStat
import aiohttp
import async_timeout
from colorthief import ColorThief
import voluptuous as vol
import math
from homeassistant.components.light import (
ATTR_RGB_COLOR,
# ATTR_BRIGHTNESS_PCT,
ATTR_BRIGHTNESS,
DOMAIN as LIGHT_DOMAIN,
LIGHT_TURN_ON_SCHEMA,
)
from homeassistant.const import SERVICE_TURN_ON as LIGHT_SERVICE_TURN_ON
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import aiohttp_client
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType
from .const import (
ATTR_PATH,
ATTR_URL,
DOMAIN,
SERVICE_TURN_ON,
ATTR_BRIGHTNESS_AUTO,
ATTR_BRIGHTNESS_MODE,
ATTR_BRIGHTNESS_MIN,
ATTR_BRIGHTNESS_MAX,
ATTR_RGB_TEMPERATURE,
)
_LOGGER = logging.getLogger(__name__)
# Extend the existing light.turn_on service schema
SERVICE_SCHEMA = vol.All(
cv.has_at_least_one_key(ATTR_URL, ATTR_PATH),
cv.make_entity_service_schema(
{
**LIGHT_TURN_ON_SCHEMA,
vol.Exclusive(ATTR_PATH, "ambient_extractor"): cv.isfile,
vol.Exclusive(ATTR_URL, "ambient_extractor"): cv.url,
vol.Optional(ATTR_BRIGHTNESS_AUTO, default=False): cv.boolean,
vol.Optional(ATTR_BRIGHTNESS_MODE, default="mean"): cv.string,
vol.Optional(ATTR_BRIGHTNESS_MIN, default=2): cv.positive_int,
vol.Optional(ATTR_BRIGHTNESS_MAX, default=70): cv.positive_int,
vol.Optional(ATTR_RGB_TEMPERATURE, default=0): cv.match_all,
}
),
)
def _get_file(file_path):
"""Get a PIL acceptable input file reference.
Allows us to mock patch during testing to make BytesIO stream.
"""
return file_path
def _get_color(file_handler) -> tuple:
"""Given an image file, extract the predominant color from it."""
color_thief = ColorThief(file_handler)
# get_color returns a SINGLE RGB value for the given image
color = color_thief.get_color(quality=1)
_LOGGER.debug("Extracted RGB color %s from image", color)
return color
def _get_brightness(file_handler, br_mode, color):
if br_mode == "natural":
im = Image.open(file_handler)
stat = ImageStat.Stat(im)
r,g,b = stat.mean
return math.sqrt(0.241*(r**2) + 0.691*(g**2) + 0.068*(b**2))
if br_mode == "rms":
im = Image.open(file_handler).convert('L')
stat = ImageStat.Stat(im)
return stat.rms[0]
if br_mode == "dominant":
r, g, b = color
return (r + g + b) / 3
# mean
im = Image.open(file_handler).convert('L')
stat = ImageStat.Stat(im)
return stat.mean[0]
async def async_setup(hass: HomeAssistant, hass_config: ConfigType) -> bool:
"""Set up services for ambient_extractor integration."""
async def async_handle_service(service_call: ServiceCall) -> None:
"""Decide which ambient_extractor method to call based on service."""
service_data = dict(service_call.data)
br_min = 2
br_max = 70
check_brightness = True
br_mode = "mean"
rgb_temperature = 0
if ATTR_BRIGHTNESS_MIN in service_data:
br_min = service_data.pop(ATTR_BRIGHTNESS_MIN)
if ATTR_BRIGHTNESS_MAX in service_data:
br_max = service_data.pop(ATTR_BRIGHTNESS_MAX)
if ATTR_BRIGHTNESS_AUTO in service_data:
check_brightness = service_data.pop(ATTR_BRIGHTNESS_AUTO)
if ATTR_BRIGHTNESS_MODE in service_data:
br_mode = service_data.pop(ATTR_BRIGHTNESS_MODE)
if ATTR_RGB_TEMPERATURE in service_data:
rgb_temperature = service_data.pop(ATTR_RGB_TEMPERATURE)
try:
if ATTR_URL in service_data:
image_type = "URL"
image_reference = service_data.pop(ATTR_URL)
colorset = await async_extract_color_from_url(
image_reference, check_brightness, br_mode
)
elif ATTR_PATH in service_data:
image_type = "file path"
image_reference = service_data.pop(ATTR_PATH)
colorset = await hass.async_add_executor_job(
extract_color_from_path, image_reference, check_brightness, br_mode
)
color = colorset["color"]
if check_brightness:
brightness = colorset["brightness"]
except UnidentifiedImageError as ex:
_LOGGER.error(
"Bad image from %s '%s' provided, are you sure it's an image? %s",
image_type, # pylint: disable=used-before-assignment
image_reference,
ex,
)
return
if color:
"""Apply RGB temperature"""
tempered_color = (
color[0] * (1 + 0.14 * rgb_temperature),
color[1] * (1 - 0.01 * rgb_temperature),
color[2] * (1 - 0.13 * rgb_temperature)
)
service_data[ATTR_RGB_COLOR] = tempered_color
if brightness:
"""Apply min and max brightness"""
if br_min >= br_max:
effective_brightness = br_min
else:
effective_brightness = br_min + ( (brightness / 255) * (br_max - br_min) )
service_data[ATTR_BRIGHTNESS] = effective_brightness
if color or brightness:
await hass.services.async_call(
LIGHT_DOMAIN, LIGHT_SERVICE_TURN_ON, service_data, blocking=True
)
hass.services.async_register(
DOMAIN,
SERVICE_TURN_ON,
async_handle_service,
schema=SERVICE_SCHEMA,
)
async def async_extract_color_from_url(url, check_brightness, br_mode):
"""Handle call for URL based image."""
if not hass.config.is_allowed_external_url(url):
_LOGGER.error(
"External URL '%s' is not allowed, please add to 'allowlist_external_urls'",
url,
)
return None
_LOGGER.debug("Getting predominant RGB from image URL '%s'", url)
# Download the image into a buffer for ColorThief to check against
try:
session = aiohttp_client.async_get_clientsession(hass)
async with async_timeout.timeout(10):
response = await session.get(url)
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error("Failed to get ColorThief image due to HTTPError: %s", err)
return None
content = await response.content.read()
with io.BytesIO(content) as _file:
_file.name = "ambient_extractor.jpg"
_file.seek(0)
color = _get_color(_file)
brightness = 0
if check_brightness:
brightness = _get_brightness(_file, br_mode, color)
return {
"color": color,
"brightness": brightness
}
def extract_color_from_path(file_path, check_brightness, br_mode):
"""Handle call for local file based image."""
if not hass.config.is_allowed_path(file_path):
_LOGGER.error(
"File path '%s' is not allowed, please add to 'allowlist_external_dirs'",
file_path,
)
return None
_LOGGER.debug("Getting predominant RGB from file path '%s'", file_path)
_file = _get_file(file_path)
color = _get_color(_file)
brightness = 0
if check_brightness:
brightness = _get_brightness(_file, br_mode, color)
return {
"color": color,
"brightness": brightness
}
return True