-
Notifications
You must be signed in to change notification settings - Fork 54
/
sensor.py
376 lines (336 loc) · 11.7 KB
/
sensor.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
"""Sensors for nibe."""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Callable
from homeassistant.components.sensor import (
ENTITY_ID_FORMAT,
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
UnitOfElectricCurrent,
UnitOfElectricPotential,
UnitOfEnergy,
UnitOfTemperature,
UnitOfTime,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo, EntityCategory
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util.dt import parse_datetime
from nibeuplink.typing import CategoryType, ParameterId, SystemUnit
from . import NibeData, NibeSystem
from .const import CONF_SENSORS, DATA_NIBE_ENTRIES
from .const import DOMAIN as DOMAIN_NIBE
from .entity import NibeParameterEntity
PARALLEL_UPDATES = 0
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities
):
"""Set up the device based on a config entry."""
data: NibeData = hass.data[DATA_NIBE_ENTRIES][entry.entry_id]
uplink = data.uplink
done: set[tuple[int, int]] = set()
def once(system_id: int, parameter_id: int):
nonlocal done
key = (system_id, parameter_id)
if key in done:
return False
done.add(key)
return True
def add_category(system: NibeSystem, category: CategoryType, unit: SystemUnit):
device_info = DeviceInfo(
configuration_url=f"https://nibeuplink.com/System/{system.system_id}",
identifiers={
(
DOMAIN_NIBE,
system.system_id,
"categories",
unit["systemUnitId"],
category["categoryId"],
)
},
via_device=(DOMAIN_NIBE, system.system_id),
name=f"{system.system['name']} - {system.system_id} : {unit['name']} : {category['name']}",
model=f"{unit['product']} : {category['name']}",
manufacturer="NIBE Energy Systems",
)
entities = []
for parameter in category["parameters"]:
if not once(system.system_id, parameter["parameterId"]):
continue
system.set_parameter(parameter["parameterId"], parameter)
entities.append(
NibeSensor(
system,
parameter["parameterId"],
device_info,
PARAMETER_SENSORS_LOOKUP.get(str(parameter["parameterId"])),
)
)
async_add_entities(entities)
def add_sensors(system: NibeSystem):
async_add_entities(
[
NibeSensor(
system,
sensor_id,
DeviceInfo(identifiers={(DOMAIN_NIBE, system.system_id)}),
PARAMETER_SENSORS_LOOKUP.get(str(sensor_id)),
)
for sensor_id in system.config[CONF_SENSORS]
if once(system.system_id, sensor_id)
],
True,
)
async_add_entities(
[NibeSystemSensor(system, description) for description in SYSTEM_SENSORS]
)
async def load_system(system: NibeSystem):
units = await uplink.get_units(system.system_id)
for unit in units:
categories = await uplink.get_categories(
system.system_id, True, unit["systemUnitId"]
)
for category in categories:
add_category(system, category, unit)
add_sensors(system)
for system in data.systems.values():
await load_system(system)
@dataclass
class NibeSensorEntityDescription(SensorEntityDescription):
"""Description of a nibe system sensor."""
PARAMETER_SENSORS = (
NibeSensorEntityDescription(
key="43424",
device_class=SensorDeviceClass.DURATION,
name="compressor operating time hot water",
state_class=SensorStateClass.TOTAL_INCREASING,
native_unit_of_measurement=UnitOfTime.HOURS,
icon="mdi:clock",
),
NibeSensorEntityDescription(
key="43420",
device_class=SensorDeviceClass.DURATION,
name="compressor operating time",
state_class=SensorStateClass.TOTAL_INCREASING,
native_unit_of_measurement=UnitOfTime.HOURS,
icon="mdi:clock",
),
NibeSensorEntityDescription(
key="43416",
name="compressor starts",
state_class=SensorStateClass.TOTAL_INCREASING,
),
NibeSensorEntityDescription(
key="40771",
name="pool2, compr. only",
state_class=SensorStateClass.TOTAL_INCREASING,
),
NibeSensorEntityDescription(
key="40995",
name="external energy meter 2",
state_class=SensorStateClass.TOTAL_INCREASING,
),
NibeSensorEntityDescription(
key="44298",
name="hw, incl. int. add",
state_class=SensorStateClass.TOTAL_INCREASING,
),
NibeSensorEntityDescription(
key="44300",
name="heating, int. add. incl.",
state_class=SensorStateClass.TOTAL_INCREASING,
),
NibeSensorEntityDescription(
key="44302",
name="cooling, compr. only.",
state_class=SensorStateClass.TOTAL_INCREASING,
),
NibeSensorEntityDescription(
key="44304",
name="pool, compr. only.",
state_class=SensorStateClass.TOTAL_INCREASING,
),
NibeSensorEntityDescription(
key="44306",
name="hotwater, compr. only.",
state_class=SensorStateClass.TOTAL_INCREASING,
),
NibeSensorEntityDescription(
key="44308",
name="heating, compr. only.",
state_class=SensorStateClass.TOTAL_INCREASING,
),
NibeSensorEntityDescription(
key="47407",
name="AUX5",
entity_category=EntityCategory.DIAGNOSTIC,
),
NibeSensorEntityDescription(
key="47408",
name="AUX4",
entity_category=EntityCategory.DIAGNOSTIC,
),
NibeSensorEntityDescription(
key="47409",
name="AUX3",
entity_category=EntityCategory.DIAGNOSTIC,
),
NibeSensorEntityDescription(
key="47410",
name="AUX2",
entity_category=EntityCategory.DIAGNOSTIC,
),
NibeSensorEntityDescription(
key="47411",
name="AUX1",
entity_category=EntityCategory.DIAGNOSTIC,
),
NibeSensorEntityDescription(
key="47412",
name="X7",
entity_category=EntityCategory.DIAGNOSTIC,
),
NibeSensorEntityDescription(
key="48745",
name="country",
entity_category=EntityCategory.DIAGNOSTIC,
),
NibeSensorEntityDescription(
key="47212",
name="set max electrical add.",
entity_category=EntityCategory.DIAGNOSTIC,
),
NibeSensorEntityDescription(
key="47214",
device_class=SensorDeviceClass.CURRENT,
name="fuse size",
entity_category=EntityCategory.DIAGNOSTIC,
),
NibeSensorEntityDescription(
key="43122",
device_class=SensorDeviceClass.FREQUENCY,
name="allowed compr. freq. min",
entity_category=EntityCategory.DIAGNOSTIC,
),
)
PARAMETER_SENSORS_LOOKUP = {x.key: x for x in PARAMETER_SENSORS}
class NibeSensor(NibeParameterEntity, SensorEntity):
"""Nibe Sensor."""
entity_description: NibeSystemSensorEntityDescription
def __init__(
self,
system: NibeSystem,
parameter_id: ParameterId,
device_info: dict,
entity_description: NibeSensorEntityDescription | None,
):
"""Init."""
super().__init__(system, parameter_id, ENTITY_ID_FORMAT)
self._attr_device_info = device_info
if entity_description:
self.entity_description = entity_description
@property
def device_class(self) -> str | None:
"""Try to deduce a device class."""
if data := super().device_class:
return data
unit = self.native_unit_of_measurement
if unit in UnitOfTemperature._value2member_map_:
return SensorDeviceClass.TEMPERATURE
elif unit in UnitOfElectricCurrent._value2member_map_:
return SensorDeviceClass.CURRENT
elif unit in UnitOfElectricPotential._value2member_map_:
return SensorDeviceClass.VOLTAGE
elif unit in UnitOfEnergy._value2member_map_:
return SensorDeviceClass.ENERGY
return None
@property
def state_class(self):
"""Return state class of unit."""
if data := super().state_class:
return data
if self.native_unit_of_measurement == UnitOfEnergy.KILO_WATT_HOUR:
return SensorStateClass.TOTAL_INCREASING
if self.native_unit_of_measurement:
return SensorStateClass.MEASUREMENT
else:
return None
@property
def native_unit_of_measurement(self):
"""Return the unit of the sensor."""
return self.get_unit(self._parameter_id)
@property
def native_value(self):
"""Return the state of the sensor."""
return self._value
@dataclass
class NibeSystemSensorEntityDescription(SensorEntityDescription):
"""Description of a nibe system sensor."""
state_fn: Callable[[NibeSystem], StateType] = lambda x: None
attributes_fn: Callable[[NibeSystem], dict[str, str | None]] = lambda x: None
SYSTEM_SENSORS: tuple[NibeSystemSensorEntityDescription, ...] = (
NibeSystemSensorEntityDescription(
key="lastActivityDate",
name="last activity",
device_class=SensorDeviceClass.TIMESTAMP,
entity_category=EntityCategory.DIAGNOSTIC,
state_fn=lambda x: parse_datetime(x.system["lastActivityDate"]),
),
NibeSystemSensorEntityDescription(
key="connectionStatus",
name="connection status",
entity_category=EntityCategory.DIAGNOSTIC,
state_fn=lambda x: x.system["connectionStatus"],
),
NibeSystemSensorEntityDescription(
key="hasAlarmed",
name="has alarmed",
entity_category=EntityCategory.DIAGNOSTIC,
state_fn=lambda x: str(x.system["hasAlarmed"]),
),
NibeSystemSensorEntityDescription(
key="software",
name="software version",
entity_category=EntityCategory.DIAGNOSTIC,
state_fn=lambda x: str(x.software["current"]["name"]) if x.software else None,
),
NibeSystemSensorEntityDescription(
key="statusCount",
name="status count",
entity_category=EntityCategory.DIAGNOSTIC,
state_fn=lambda x: len(x.statuses),
attributes_fn=lambda x: {"statuses": x.statuses},
),
)
class NibeSystemSensor(CoordinatorEntity[NibeSystem], SensorEntity):
"""Generic system sensor."""
entity_description: NibeSystemSensorEntityDescription
def __init__(
self,
system: NibeSystem,
description: NibeSystemSensorEntityDescription,
):
"""Initialize sensor."""
super().__init__(system)
self.entity_description = description
self._system = system
self._attr_device_info = {"identifiers": {(DOMAIN_NIBE, system.system_id)}}
self._attr_unique_id = "{}_system_{}".format(
system.system_id, description.key.lower()
)
@property
def native_value(self) -> StateType:
"""Get the state data from system class."""
return self.entity_description.state_fn(self._system)
@property
def extra_state_attributes(self) -> dict[str, str | None]:
"""Get the attributes (extra state) data from system class."""
return self.entity_description.attributes_fn(self._system)