-
-
Notifications
You must be signed in to change notification settings - Fork 32k
/
Copy pathbutton.py
77 lines (57 loc) · 2.32 KB
/
button.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
"""Platform for button."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from ohme import ApiException, ChargerStatus, OhmeApiClient
from homeassistant.components.button import ButtonEntity, ButtonEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import OhmeConfigEntry
from .const import DOMAIN
from .entity import OhmeEntity, OhmeEntityDescription
PARALLEL_UPDATES = 1
@dataclass(frozen=True, kw_only=True)
class OhmeButtonDescription(OhmeEntityDescription, ButtonEntityDescription):
"""Class describing Ohme button entities."""
press_fn: Callable[[OhmeApiClient], Awaitable[None]]
available_fn: Callable[[OhmeApiClient], bool]
BUTTON_DESCRIPTIONS = [
OhmeButtonDescription(
key="approve",
translation_key="approve",
press_fn=lambda client: client.async_approve_charge(),
is_supported_fn=lambda client: client.is_capable("pluginsRequireApprovalMode"),
available_fn=lambda client: client.status is ChargerStatus.PENDING_APPROVAL,
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: OhmeConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up buttons."""
coordinator = config_entry.runtime_data.charge_session_coordinator
async_add_entities(
OhmeButton(coordinator, description)
for description in BUTTON_DESCRIPTIONS
if description.is_supported_fn(coordinator.client)
)
class OhmeButton(OhmeEntity, ButtonEntity):
"""Generic button for Ohme."""
entity_description: OhmeButtonDescription
async def async_press(self) -> None:
"""Handle the button press."""
try:
await self.entity_description.press_fn(self.coordinator.client)
except ApiException as e:
raise HomeAssistantError(
translation_key="api_failed", translation_domain=DOMAIN
) from e
await self.coordinator.async_request_refresh()
@property
def available(self) -> bool:
"""Is entity available."""
return super().available and self.entity_description.available_fn(
self.coordinator.client
)