forked from elupus/hass_nibe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
343 lines (283 loc) · 9.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
"""Support for nibe uplink."""
import attr
import asyncio
import logging
from typing import List, Dict, Union, T, Mapping
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant import config_entries
from homeassistant.components import persistent_notification
from homeassistant.const import CONF_NAME
from nibeuplink import Uplink, UplinkSession
from .config_flow import NibeConfigFlow # noqa
from .const import (
CONF_ACCESS_DATA,
CONF_BINARY_SENSORS,
CONF_CATEGORIES,
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
CONF_CLIMATE_SYSTEMS,
CONF_CLIMATES,
CONF_CURRENT_TEMPERATURE,
CONF_REDIRECT_URI,
CONF_SENSORS,
CONF_STATUSES,
CONF_SWITCHES,
CONF_SYSTEM,
CONF_SYSTEMS,
CONF_THERMOSTATS,
CONF_UNIT,
CONF_UNITS,
CONF_VALVE_POSITION,
CONF_WATER_HEATERS,
CONF_WRITEACCESS,
DATA_NIBE,
DOMAIN,
SCAN_INTERVAL,
CONF_FANS,
SIGNAL_PARAMETERS_UPDATED,
SIGNAL_STATUSES_UPDATED,
)
from .services import async_register_services, async_track_delta_time
_LOGGER = logging.getLogger(__name__)
def none_as_true(data):
"""Return a none value as a truth."""
if data is None:
return True
else:
return cv.boolean(data)
def ensure_system_dict(value: Union[Dict[int, T], List[T], None]) -> Dict[int, T]:
"""Wrap value in list if it is not one."""
if value is None:
return {}
if isinstance(value, list):
value_schema = vol.Schema([
vol.Schema({
vol.Required(CONF_SYSTEM): cv.positive_int
}, extra=vol.ALLOW_EXTRA)
])
value = value_schema(value)
return {
x[CONF_SYSTEM]: x
for x in value
}
if isinstance(value, dict):
return value
value = SYSTEM_SCHEMA(value)
return {value[CONF_SYSTEM]: value}
UNIT_SCHEMA = vol.Schema(vol.All(
cv.deprecated(CONF_STATUSES),
{
vol.Required(CONF_UNIT): cv.positive_int,
vol.Optional(CONF_CATEGORIES, default=False): none_as_true,
vol.Optional(CONF_STATUSES, default=False): none_as_true,
}
))
THERMOSTAT_SCHEMA = vol.Schema(
{
vol.Optional(CONF_CLIMATE_SYSTEMS, default=[1]): vol.All(cv.ensure_list, [int]),
vol.Required(CONF_NAME): str,
vol.Optional(CONF_CURRENT_TEMPERATURE): cv.entity_id,
vol.Optional(CONF_VALVE_POSITION): cv.entity_id,
}
)
SYSTEM_SCHEMA = vol.Schema(vol.All(
cv.deprecated(CONF_CLIMATES),
cv.deprecated(CONF_WATER_HEATERS),
cv.deprecated(CONF_FANS),
{
vol.Optional(CONF_SYSTEM): cv.positive_int,
vol.Optional(CONF_UNITS, default=[]): vol.All(cv.ensure_list, [UNIT_SCHEMA]),
vol.Optional(CONF_SENSORS, default=[]): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_CLIMATES): none_as_true,
vol.Optional(CONF_WATER_HEATERS): none_as_true,
vol.Optional(CONF_FANS): none_as_true,
vol.Optional(CONF_SWITCHES, default=[]): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_BINARY_SENSORS, default=[]): vol.All(
cv.ensure_list, [cv.string]
),
vol.Optional(CONF_THERMOSTATS, default={}): {
cv.positive_int: THERMOSTAT_SCHEMA
},
}
))
NIBE_SCHEMA = vol.Schema(
{
vol.Optional(CONF_REDIRECT_URI): cv.string,
vol.Optional(CONF_CLIENT_ID): cv.string,
vol.Optional(CONF_CLIENT_SECRET): cv.string,
vol.Optional(CONF_WRITEACCESS): cv.boolean,
vol.Optional(CONF_SYSTEMS, default={}): vol.All(
ensure_system_dict, {vol.Coerce(str): SYSTEM_SCHEMA}
),
}
)
CONFIG_SCHEMA = vol.Schema({DOMAIN: NIBE_SCHEMA}, extra=vol.ALLOW_EXTRA)
FORWARD_PLATFORMS = (
"climate",
"switch",
"sensor",
"binary_sensor",
"water_heater",
"fan",
)
@attr.s
class NibeData:
"""Holder for nibe data."""
config = attr.ib()
session = attr.ib(default=None, type=UplinkSession)
uplink = attr.ib(default=None, type=Uplink)
systems = attr.ib(default=[], type=List["NibeSystem"])
def _get_merged_config(config: Mapping, entry: config_entries.ConfigEntry):
config = dict(config)
if CONF_SYSTEMS in entry.data:
for system in entry.data[CONF_SYSTEMS].keys():
if system not in config[CONF_SYSTEMS]:
config[CONF_SYSTEMS][system] = SYSTEM_SCHEMA({})
return config
async def async_setup_systems(hass, data: NibeData, entry):
"""Configure each system."""
config = _get_merged_config(data.config, entry)
systems = {
system_id: NibeSystem(
hass, data.uplink, int(system_id), system_cfg, entry.entry_id
)
for system_id, system_cfg in config[CONF_SYSTEMS].items()
}
data.systems = systems
tasks = [system.load() for system in systems.values()]
await asyncio.gather(*tasks)
for platform in FORWARD_PLATFORMS:
hass.async_add_job(
hass.config_entries.async_forward_entry_setup(entry, platform)
)
async def async_setup(hass, config):
"""Configure the nibe uplink component."""
if DOMAIN in config:
data = NibeData(config[DOMAIN])
else:
data = NibeData(NIBE_SCHEMA({}))
hass.data[DATA_NIBE] = data
await async_register_services(hass)
return True
async def async_setup_entry(hass, entry: config_entries.ConfigEntry):
"""Set up an access point from a config entry."""
_LOGGER.debug("Setup nibe entry")
scope = None
if entry.data.get(CONF_WRITEACCESS):
scope = ["READSYSTEM", "WRITESYSTEM"]
else:
scope = ["READSYSTEM"]
def access_data_write(data):
hass.config_entries.async_update_entry(
entry, data={**entry.data, CONF_ACCESS_DATA: data}
)
session = UplinkSession(
client_id=entry.data.get(CONF_CLIENT_ID),
client_secret=entry.data.get(CONF_CLIENT_SECRET),
redirect_uri=entry.data.get(CONF_REDIRECT_URI),
access_data=entry.data.get(CONF_ACCESS_DATA),
access_data_write=access_data_write,
scope=scope,
)
uplink = Uplink(session)
data = hass.data[DATA_NIBE]
data.session = session
data.uplink = uplink
await session.refresh_access_token()
await async_setup_systems(hass, data, entry)
return True
async def async_unload_entry(hass, entry):
"""Unload a configuration entity."""
data = hass.data[DATA_NIBE]
await asyncio.wait(
[
hass.config_entries.async_forward_entry_unload(entry, platform)
for platform in FORWARD_PLATFORMS
]
)
await asyncio.wait([system.unload() for system in data.systems.values()])
await data.session.close()
data.systems = []
data.uplink = None
data.monitor = None
return True
class NibeSystem(object):
"""Object representing a system."""
def __init__(self, hass, uplink, system_id, config, entry_id):
"""Init."""
self.hass = hass
self.config = config
self.system_id = system_id
self.entry_id = entry_id
self.system = None
self.uplink = uplink
self.notice = []
self.statuses = set()
self._device_info = {}
self._unsub = []
@property
def device_info(self):
"""Return a device description for device registry."""
return self._device_info
async def unload(self):
"""Unload system."""
for unsub in reversed(self._unsub):
unsub()
self._unsub = []
async def load(self):
"""Load system."""
self.system = await self.uplink.get_system(self.system_id)
_LOGGER.debug("Loading system: {}".format(self.system))
self._device_info = {
"identifiers": {(DOMAIN, self.system_id)},
"manufacturer": "NIBE Energy Systems",
"model": self.system.get("productName"),
"name": f"{self.system.get('name')} - {self.system_id}",
}
device_registry = await self.hass.helpers.device_registry.async_get_registry()
device_registry.async_get_or_create(
config_entry_id=self.entry_id, **self._device_info
)
await self.update_notifications()
await self.update_statuses()
self._unsub.append(
async_track_delta_time(self.hass, SCAN_INTERVAL, self.update_notifications)
)
self._unsub.append(
async_track_delta_time(self.hass, SCAN_INTERVAL, self.update_statuses)
)
async def update_statuses(self):
"""Update status list."""
status_icons = await self.uplink.get_status(self.system_id)
parameters = {}
statuses = set()
for status_icon in status_icons:
statuses.add(status_icon["title"])
for parameter in status_icon["parameters"]:
parameters[parameter["parameterId"]] = parameter
self.statuses = statuses
_LOGGER.debug("Statuses: %s", statuses)
self.hass.helpers.dispatcher.async_dispatcher_send(
SIGNAL_PARAMETERS_UPDATED, self.system_id, parameters
)
self.hass.helpers.dispatcher.async_dispatcher_send(
SIGNAL_STATUSES_UPDATED, self.system_id, statuses
)
async def update_notifications(self):
"""Update notification list."""
notice = await self.uplink.get_notifications(self.system_id)
added = [k for k in notice if k not in self.notice]
removed = [k for k in self.notice if k not in notice]
self.notice = notice
for x in added:
persistent_notification.async_create(
self.hass,
x["info"]["description"],
x["info"]["title"],
"nibe:{}".format(x["notificationId"]),
)
for x in removed:
persistent_notification.async_dismiss(
self.hass, "nibe:{}".format(x["notificationId"])
)