-
Notifications
You must be signed in to change notification settings - Fork 0
/
coordinator.py
174 lines (149 loc) · 5.87 KB
/
coordinator.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
"""DataUpdateCoordinator for eone."""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import NamedTuple
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import (
DataUpdateCoordinator,
UpdateFailed,
)
from custom_components.eone.api.models import Measure
from .api.client import EOneApiClient
from .api.exceptions import (
InvalidCredentialsException,
EOneException,
UnauthorizedException,
)
from .const import (
CONF_GRID_TYPE,
CONF_VIRTUAL_BATTERY_ID,
CONF_VIRTUAL_DEVICE_ID,
DOMAIN,
LOGGER,
SCAN_INTERVAL_IN_MINUTES,
CONF_MASTER_RELAY_ID,
CONF_WATER_HEATER_ID,
)
class EOneCoordinatorData(NamedTuple):
"""Data returned by the coordinator."""
produced_energy: Measure
grid_energy: Measure
grid_energy_without_battery: Measure
autonomy_rate: Measure
self_conso: Measure
msb_charge: Measure
msb_discharge: Measure
green_energy: Measure
battery_state: Measure
master_relay_state: str
water_heater_energy: Measure
# https://developers.home-assistant.io/docs/integration_fetching_data#coordinated-single-api-poll-for-data-for-all-entities
class EOneDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""
config_entry: ConfigEntry
__auth_token: str | None = None
__token_expiration: datetime | None = None
def __init__(
self,
hass: HomeAssistant,
client: EOneApiClient,
) -> None:
"""Initialize."""
self.client = client
super().__init__(
hass=hass,
logger=LOGGER,
name=DOMAIN,
update_interval=timedelta(minutes=SCAN_INTERVAL_IN_MINUTES),
)
async def _async_update_data(self) -> EOneCoordinatorData:
"""Update data via library."""
try:
email = self.config_entry.data[CONF_EMAIL]
password = self.config_entry.data[CONF_PASSWORD]
grid_type = self.config_entry.data[CONF_GRID_TYPE]
device_id = self.config_entry.data[CONF_VIRTUAL_DEVICE_ID]
virtual_battery_id = self.config_entry.data[
CONF_VIRTUAL_BATTERY_ID
]
master_relay_id = self.config_entry.data[
CONF_MASTER_RELAY_ID
]
water_heater_id = self.config_entry.data[CONF_WATER_HEATER_ID]
await self.authenticate_user(email, password)
result = await self.client.async_get_measures_total(
self.__auth_token, grid_type, device_id
)
result_water_heater = await self.client.async_get_measures_total(
self.__auth_token, grid_type, water_heater_id
)
battery_state = await self.client.async_get_battery_state(
self.__auth_token, virtual_battery_id
)
master_relay_state = await self.client.async_get_relay_state(
self.__auth_token, master_relay_id
)
data = EOneCoordinatorData(
produced_energy=self.find_measure_by_type(
result, "produced_energy"
),
grid_energy=self.find_measure_by_type(result, "grid_energy"),
grid_energy_without_battery=self.find_measure_by_type(
result, "grid_sans_msb_energy"
),
autonomy_rate=self.find_measure_by_type(
result, "autonomy_rate"
),
self_conso=self.find_measure_by_type(result, "self_conso"),
msb_charge=self.find_measure_by_type(result, "msb_charge"),
msb_discharge=self.find_measure_by_type(
result, "msb_discharge"
),
green_energy=self.find_measure_by_type(result, "green_energy"),
battery_state=battery_state,
master_relay_state=master_relay_state,
water_heater_energy=self.find_measure_by_type(result_water_heater, "energy"),
)
self._data = data
return data
except (
UnauthorizedException,
InvalidCredentialsException,
) as exception:
raise ConfigEntryAuthFailed(exception) from exception
except EOneException as exception:
raise UpdateFailed(exception) from exception
async def authenticate_user(self, email, password):
"""Reauthenticate user if needed."""
if (
self.__auth_token is None
or self.__token_expiration is None
or self.__token_expiration < datetime.utcnow()
):
result = await self.client.async_login(email, password)
self.__auth_token = result.auth_token
self.__token_expiration = datetime.utcnow() + timedelta(hours=2)
async def turn_on_master_relay(self):
"""Turn on master relay."""
await self.client.async_turn_on(
self.__auth_token, self.config_entry.data[CONF_MASTER_RELAY_ID]
)
async def turn_off_master_relay(self):
"""Turn off master relay."""
await self.client.async_turn_off(
self.__auth_token, self.config_entry.data[CONF_MASTER_RELAY_ID]
)
def master_relay_is_on(self) -> bool:
"""Return true if master relay is on."""
if self._data is not None and self._data.master_relay_state is not None:
return self._data.master_relay_state == "on"
return False
@staticmethod
def find_measure_by_type(
measures: list[Measure], name: str
) -> Measure | None:
"""Find measure by name."""
return next((m for m in measures if m.type == name), None)