-
-
Notifications
You must be signed in to change notification settings - Fork 32k
/
Copy path__init__.py
484 lines (393 loc) · 15.8 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
"""Component to allow for providing device or service updates."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import timedelta
from enum import StrEnum
from functools import lru_cache
import logging
from typing import Any, Final, final
from awesomeversion import AwesomeVersion, AwesomeVersionCompareException
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ENTITY_PICTURE, STATE_OFF, STATE_ON, EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.config_validation import (
PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE,
)
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType
from .const import (
ATTR_AUTO_UPDATE,
ATTR_BACKUP,
ATTR_IN_PROGRESS,
ATTR_INSTALLED_VERSION,
ATTR_LATEST_VERSION,
ATTR_RELEASE_SUMMARY,
ATTR_RELEASE_URL,
ATTR_SKIPPED_VERSION,
ATTR_TITLE,
ATTR_VERSION,
DOMAIN,
SERVICE_INSTALL,
SERVICE_SKIP,
UpdateEntityFeature,
)
SCAN_INTERVAL = timedelta(minutes=15)
ENTITY_ID_FORMAT: Final = DOMAIN + ".{}"
_LOGGER = logging.getLogger(__name__)
class UpdateDeviceClass(StrEnum):
"""Device class for update."""
FIRMWARE = "firmware"
DEVICE_CLASSES_SCHEMA = vol.All(vol.Lower, vol.Coerce(UpdateDeviceClass))
__all__ = [
"ATTR_BACKUP",
"ATTR_INSTALLED_VERSION",
"ATTR_LATEST_VERSION",
"ATTR_VERSION",
"DEVICE_CLASSES_SCHEMA",
"DOMAIN",
"PLATFORM_SCHEMA_BASE",
"PLATFORM_SCHEMA",
"SERVICE_INSTALL",
"SERVICE_SKIP",
"UpdateDeviceClass",
"UpdateEntity",
"UpdateEntityDescription",
"UpdateEntityFeature",
]
# mypy: disallow-any-generics
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up Select entities."""
component = hass.data[DOMAIN] = EntityComponent[UpdateEntity](
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
await component.async_setup(config)
component.async_register_entity_service(
SERVICE_INSTALL,
{
vol.Optional(ATTR_VERSION): cv.string,
vol.Optional(ATTR_BACKUP, default=False): cv.boolean,
},
async_install,
[UpdateEntityFeature.INSTALL],
)
component.async_register_entity_service(
SERVICE_SKIP,
{},
async_skip,
)
component.async_register_entity_service(
"clear_skipped",
{},
async_clear_skipped,
)
websocket_api.async_register_command(hass, websocket_release_notes)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up a config entry."""
component: EntityComponent[UpdateEntity] = hass.data[DOMAIN]
return await component.async_setup_entry(entry)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
component: EntityComponent[UpdateEntity] = hass.data[DOMAIN]
return await component.async_unload_entry(entry)
async def async_install(entity: UpdateEntity, service_call: ServiceCall) -> None:
"""Service call wrapper to validate the call."""
# If version is not specified, but no update is available.
if (version := service_call.data.get(ATTR_VERSION)) is None and (
entity.installed_version == entity.latest_version
or entity.latest_version is None
):
raise HomeAssistantError(f"No update available for {entity.entity_id}")
# If version is specified, but not supported by the entity.
if (
version is not None
and not entity.supported_features & UpdateEntityFeature.SPECIFIC_VERSION
):
raise HomeAssistantError(
f"Installing a specific version is not supported for {entity.entity_id}"
)
# If backup is requested, but not supported by the entity.
if (
backup := service_call.data[ATTR_BACKUP]
) and not entity.supported_features & UpdateEntityFeature.BACKUP:
raise HomeAssistantError(f"Backup is not supported for {entity.entity_id}")
# Update is already in progress.
if entity.in_progress is not False:
raise HomeAssistantError(
f"Update installation already in progress for {entity.entity_id}"
)
await entity.async_install_with_progress(version, backup)
async def async_skip(entity: UpdateEntity, service_call: ServiceCall) -> None:
"""Service call wrapper to validate the call."""
if entity.auto_update:
raise HomeAssistantError(
f"Skipping update is not supported for {entity.entity_id}"
)
await entity.async_skip()
async def async_clear_skipped(entity: UpdateEntity, service_call: ServiceCall) -> None:
"""Service call wrapper to validate the call."""
if entity.auto_update:
raise HomeAssistantError(
f"Clearing skipped update is not supported for {entity.entity_id}"
)
await entity.async_clear_skipped()
@dataclass
class UpdateEntityDescription(EntityDescription):
"""A class that describes update entities."""
device_class: UpdateDeviceClass | None = None
entity_category: EntityCategory | None = EntityCategory.CONFIG
@lru_cache(maxsize=256)
def _version_is_newer(latest_version: str, installed_version: str) -> bool:
"""Return True if version is newer."""
return AwesomeVersion(latest_version) > installed_version
class UpdateEntity(RestoreEntity):
"""Representation of an update entity."""
_entity_component_unrecorded_attributes = frozenset(
{ATTR_ENTITY_PICTURE, ATTR_IN_PROGRESS, ATTR_RELEASE_SUMMARY}
)
entity_description: UpdateEntityDescription
_attr_auto_update: bool = False
_attr_installed_version: str | None = None
_attr_device_class: UpdateDeviceClass | None
_attr_in_progress: bool | int = False
_attr_latest_version: str | None = None
_attr_release_summary: str | None = None
_attr_release_url: str | None = None
_attr_state: None = None
_attr_supported_features: UpdateEntityFeature = UpdateEntityFeature(0)
_attr_title: str | None = None
__skipped_version: str | None = None
__in_progress: bool = False
@property
def auto_update(self) -> bool:
"""Indicate if the device or service has auto update enabled."""
return self._attr_auto_update
@property
def installed_version(self) -> str | None:
"""Version installed and in use."""
return self._attr_installed_version
def _default_to_device_class_name(self) -> bool:
"""Return True if an unnamed entity should be named by its device class.
For updates this is True if the entity has a device class.
"""
return self.device_class is not None
@property
def device_class(self) -> UpdateDeviceClass | None:
"""Return the class of this entity."""
if hasattr(self, "_attr_device_class"):
return self._attr_device_class
if hasattr(self, "entity_description"):
return self.entity_description.device_class
return None
@property
def entity_category(self) -> EntityCategory | None:
"""Return the category of the entity, if any."""
if hasattr(self, "_attr_entity_category"):
return self._attr_entity_category
if hasattr(self, "entity_description"):
return self.entity_description.entity_category
if self.supported_features & UpdateEntityFeature.INSTALL:
return EntityCategory.CONFIG
return EntityCategory.DIAGNOSTIC
@property
def entity_picture(self) -> str | None:
"""Return the entity picture to use in the frontend.
Update entities return the brand icon based on the integration
domain by default.
"""
return (
f"https://brands.home-assistant.io/_/{self.platform.platform_name}/icon.png"
)
@property
def in_progress(self) -> bool | int | None:
"""Update installation progress.
Needs UpdateEntityFeature.PROGRESS flag to be set for it to be used.
Can either return a boolean (True if in progress, False if not)
or an integer to indicate the progress in from 0 to 100%.
"""
return self._attr_in_progress
@property
def latest_version(self) -> str | None:
"""Latest version available for install."""
return self._attr_latest_version
@property
def release_summary(self) -> str | None:
"""Summary of the release notes or changelog.
This is not suitable for long changelogs, but merely suitable
for a short excerpt update description of max 255 characters.
"""
return self._attr_release_summary
@property
def release_url(self) -> str | None:
"""URL to the full release notes of the latest version available."""
return self._attr_release_url
@property
def supported_features(self) -> UpdateEntityFeature:
"""Flag supported features."""
return self._attr_supported_features
@property
def title(self) -> str | None:
"""Title of the software.
This helps to differentiate between the device or entity name
versus the title of the software installed.
"""
return self._attr_title
@final
async def async_skip(self) -> None:
"""Skip the current offered version to update."""
if (latest_version := self.latest_version) is None:
raise HomeAssistantError(f"Cannot skip an unknown version for {self.name}")
if self.installed_version == latest_version:
raise HomeAssistantError(f"No update available to skip for {self.name}")
self.__skipped_version = latest_version
self.async_write_ha_state()
@final
async def async_clear_skipped(self) -> None:
"""Clear the skipped version."""
self.__skipped_version = None
self.async_write_ha_state()
async def async_install(
self, version: str | None, backup: bool, **kwargs: Any
) -> None:
"""Install an update.
Version can be specified to install a specific version. When `None`, the
latest version needs to be installed.
The backup parameter indicates a backup should be taken before
installing the update.
"""
await self.hass.async_add_executor_job(self.install, version, backup)
def install(self, version: str | None, backup: bool, **kwargs: Any) -> None:
"""Install an update.
Version can be specified to install a specific version. When `None`, the
latest version needs to be installed.
The backup parameter indicates a backup should be taken before
installing the update.
"""
raise NotImplementedError()
async def async_release_notes(self) -> str | None:
"""Return full release notes.
This is suitable for a long changelog that does not fit in the release_summary
property. The returned string can contain markdown.
"""
return await self.hass.async_add_executor_job(self.release_notes)
def release_notes(self) -> str | None:
"""Return full release notes.
This is suitable for a long changelog that does not fit in the release_summary
property. The returned string can contain markdown.
"""
raise NotImplementedError()
@property
@final
def state(self) -> str | None:
"""Return the entity state."""
if (installed_version := self.installed_version) is None or (
latest_version := self.latest_version
) is None:
return None
if latest_version == self.__skipped_version:
return STATE_OFF
if latest_version == installed_version:
return STATE_OFF
try:
newer = _version_is_newer(latest_version, installed_version)
return STATE_ON if newer else STATE_OFF
except AwesomeVersionCompareException:
# Can't compare versions, already tried exact match
return STATE_ON
@final
@property
def state_attributes(self) -> dict[str, Any] | None:
"""Return state attributes."""
if (release_summary := self.release_summary) is not None:
release_summary = release_summary[:255]
# If entity supports progress, return the in_progress value.
# Otherwise, we use the internal progress value.
if self.supported_features & UpdateEntityFeature.PROGRESS:
in_progress = self.in_progress
else:
in_progress = self.__in_progress
installed_version = self.installed_version
latest_version = self.latest_version
skipped_version = self.__skipped_version
# Clear skipped version in case it matches the current installed
# version or the latest version diverged.
if (installed_version is not None and skipped_version == installed_version) or (
latest_version is not None and skipped_version != latest_version
):
skipped_version = None
self.__skipped_version = None
return {
ATTR_AUTO_UPDATE: self.auto_update,
ATTR_INSTALLED_VERSION: installed_version,
ATTR_IN_PROGRESS: in_progress,
ATTR_LATEST_VERSION: latest_version,
ATTR_RELEASE_SUMMARY: release_summary,
ATTR_RELEASE_URL: self.release_url,
ATTR_SKIPPED_VERSION: skipped_version,
ATTR_TITLE: self.title,
}
@final
async def async_install_with_progress(
self, version: str | None, backup: bool
) -> None:
"""Install update and handle progress if needed.
Handles setting the in_progress state in case the entity doesn't
support it natively.
"""
if not self.supported_features & UpdateEntityFeature.PROGRESS:
self.__in_progress = True
self.async_write_ha_state()
try:
await self.async_install(version, backup)
finally:
# No matter what happens, we always stop progress in the end
self._attr_in_progress = False
self.__in_progress = False
self.async_write_ha_state()
async def async_internal_added_to_hass(self) -> None:
"""Call when the update entity is added to hass.
It is used to restore the skipped version, if any.
"""
await super().async_internal_added_to_hass()
state = await self.async_get_last_state()
if state is not None and state.attributes.get(ATTR_SKIPPED_VERSION) is not None:
self.__skipped_version = state.attributes[ATTR_SKIPPED_VERSION]
@websocket_api.require_admin
@websocket_api.websocket_command(
{
vol.Required("type"): "update/release_notes",
vol.Required("entity_id"): cv.entity_id,
}
)
@websocket_api.async_response
async def websocket_release_notes(
hass: HomeAssistant,
connection: websocket_api.connection.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Get the full release notes for a entity."""
component: EntityComponent[UpdateEntity] = hass.data[DOMAIN]
entity = component.get_entity(msg["entity_id"])
if entity is None:
connection.send_error(
msg["id"], websocket_api.const.ERR_NOT_FOUND, "Entity not found"
)
return
if not entity.supported_features & UpdateEntityFeature.RELEASE_NOTES:
connection.send_error(
msg["id"],
websocket_api.const.ERR_NOT_SUPPORTED,
"Entity does not support release notes",
)
return
connection.send_result(
msg["id"],
await entity.async_release_notes(),
)