-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsensor.py
668 lines (600 loc) · 23.4 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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
"""Sensor for Toon Smart Meter integration."""
from __future__ import annotations
import asyncio
from datetime import timedelta
from functools import reduce
import logging
from typing import Final
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorStateClass,
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import UnitOfVolume, UnitOfEnergy, UnitOfPower, UnitOfTemperature
from homeassistant.const import (
CONF_HOST,
CONF_PORT,
CONF_RESOURCES,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle, dt
BASE_URL = "http://{0}:{1}/hdrv_zwave?action=getDevices.json"
DEVICE_CLASS_WATER = "water"
_LOGGER = logging.getLogger(__name__)
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=10)
SENSOR_PREFIX = "Toon "
ATTR_MEASUREMENT = "measurement"
ATTR_SECTION = "section"
CONF_POWERPLUGS = "powerplugs"
SENSOR_LIST = {
"gasused",
"gasusedcnt",
"elecusageflowpulse",
"elecusagecntpulse",
"elecusageflowlow",
"elecusageflowhigh",
"elecprodflowlow",
"elecprodflowhigh",
"elecusagecntlow",
"elecusagecnthigh",
"elecprodcntlow",
"elecprodcnthigh",
"elecsolar",
"elecsolarcnt",
"heat",
"waterflow",
"waterquantity",
}
SENSOR_TYPES: Final[tuple[SensorEntityDescription, ...]] = (
SensorEntityDescription(
key="gasused",
name="Gas Used Last Hour",
icon="mdi:gas-cylinder",
native_unit_of_measurement=UnitOfVolume.CUBIC_METERS,
device_class=SensorDeviceClass.GAS,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="gasusedcnt",
name="Gas Used Cnt",
icon="mdi:gas-cylinder",
native_unit_of_measurement=UnitOfVolume.CUBIC_METERS,
device_class=SensorDeviceClass.GAS,
state_class=SensorStateClass.TOTAL_INCREASING,
),
SensorEntityDescription(
key="elecusageflowpulse",
name="Power Use",
icon="mdi:flash",
native_unit_of_measurement=UnitOfPower.WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="elecusageflowlow",
name="P1 Power Use Low",
icon="mdi:flash",
native_unit_of_measurement=UnitOfPower.WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="elecusageflowhigh",
name="P1 Power Use High",
icon="mdi:flash",
native_unit_of_measurement=UnitOfPower.WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="elecprodflowlow",
name="P1 Power Prod Low",
icon="mdi:flash",
native_unit_of_measurement=UnitOfPower.WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="elecprodflowhigh",
name="P1 Power Prod High",
icon="mdi:flash",
native_unit_of_measurement=UnitOfPower.WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="elecusagecntpulse",
name="Power Use Cnt",
icon="mdi:flash",
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
),
SensorEntityDescription(
key="elecusagecntlow",
name="P1 Power Use Cnt Low",
icon="mdi:flash",
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
),
SensorEntityDescription(
key="elecusagecnthigh",
name="P1 Power Use Cnt High",
icon="mdi:flash",
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
),
SensorEntityDescription(
key="elecprodcntlow",
name="P1 Power Prod Cnt Low",
icon="mdi:flash",
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
),
SensorEntityDescription(
key="elecprodcnthigh",
name="P1 Power Prod Cnt High",
icon="mdi:flash",
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
),
SensorEntityDescription(
key="elecsolar",
name="P1 Power Solar",
icon="mdi:flash",
native_unit_of_measurement=UnitOfPower.WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="elecsolarcnt",
name="P1 Power Solar Cnt",
icon="mdi:flash",
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
),
SensorEntityDescription(
key="heat",
name="P1 Heat",
icon="mdi:fire",
unit_of_measurement="Gj",
),
SensorEntityDescription(
key="waterquantity",
name="P1 waterquantity",
icon="mdi:water",
native_unit_of_measurement=UnitOfVolume.LITERS,
device_class=SensorDeviceClass.WATER,
state_class=SensorStateClass.TOTAL_INCREASING,
),
SensorEntityDescription(
key="waterflow",
name="P1 waterflow",
icon="mdi:water-pump",
unit_of_measurement = "l/m",
device_class=SensorDeviceClass.WATER,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="powerplugflow",
name="PowerPlug Power Use",
icon="mdi:flash",
native_unit_of_measurement=UnitOfPower.WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
),
SensorEntityDescription(
key="powerplugcnt",
name="PowerPlug Power Use Cnt",
icon="mdi:flash",
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
),
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Optional(CONF_PORT, default=80): cv.positive_int,
vol.Required(CONF_RESOURCES, default=list(SENSOR_LIST)): vol.All(
cv.ensure_list, [vol.In(SENSOR_LIST)]
),
vol.Optional(CONF_POWERPLUGS, default=list()): cv.ensure_list,
}
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Setup the Toon Smart Meter sensors."""
session = async_get_clientsession(hass)
data = ToonSmartMeterData(session, config.get(CONF_HOST), config.get(CONF_PORT))
await data.async_update()
# Create a new sensor for each sensor type.
entities = []
for description in SENSOR_TYPES:
if description.key in config[CONF_RESOURCES]:
entities.append(ToonSmartMeterSensor(description, data, ""))
if description.key in ["powerplugflow", "powerplugcnt"]:
for powerplug in config[CONF_POWERPLUGS]:
entities.append(ToonSmartMeterSensor(description, data, powerplug))
async_add_entities(entities, True)
return True
# pylint: disable=abstract-method
class ToonSmartMeterData(object):
"""Handle Toon object and limit updates."""
def __init__(self, session, host, port):
"""Initialize the data object."""
self._session = session
self._url = BASE_URL.format(host, port)
self.data = {}
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Download and update data from Toon."""
try:
async with async_timeout.timeout(5):
response = await self._session.get(
self._url, headers={"Accept-Encoding": "identity"}
)
self.data = await response.json(content_type="text/javascript")
_LOGGER.debug("Data received from Toon: %s", self.data)
except aiohttp.ClientError:
_LOGGER.error("Cannot connect to Toon using url '%s'", self._url)
except asyncio.TimeoutError:
_LOGGER.error(
"Timeout error occurred while connecting to Toon using url '%s'",
self._url
)
except (TypeError, KeyError) as err:
_LOGGER.error(f"Cannot parse data received from Toon: %s", err)
class ToonSmartMeterSensor(SensorEntity):
"""Representation of a Smart Meter connected to Toon."""
def __init__(self, description: SensorEntityDescription, data, powerplug):
"""Initialize the sensor."""
self._entity_description = description
self._data = data
self.device_type = self._entity_description.key
self.powerplug_name = powerplug
if self._entity_description.key in ["powerplugflow", "powerplugcnt"]:
self._attr_name = f"{SENSOR_PREFIX} {self.powerplug_name} {self._entity_description.name}"
self._attr_unique_id = f"{SENSOR_PREFIX}_{self.powerplug_name}_{self._entity_description.name}"
else:
self._attr_name = f"{SENSOR_PREFIX} {self._entity_description.name}"
self._attr_unique_id = f"{SENSOR_PREFIX}_{self._entity_description.name}"
self._attr_icon = self._entity_description.icon
self._attr_state_class = self._entity_description.state_class
self._attr_native_unit_of_measurement = self._entity_description.native_unit_of_measurement
self._attr_device_class = self._entity_description.device_class
self._state = None
self._discovery = False
self._dev_id = {}
def _validateOutput(self, value):
"""Return 0 if the output from the Toon is NaN (happens after a reboot)"""
try:
if value.lower() == "nan":
value = 0
except:
return value
return value
@property
def state(self):
"""Return the state of the sensor. (total/current power consumption/production or total gas used)"""
return self._state
async def async_update(self):
"""Get the latest data and use it to update our sensor state."""
await self._data.async_update()
energy = self._data.data
if not energy:
return
if self._discovery == False:
for key in energy:
dev = energy[key]
"""elec verbruik pulse"""
if (
key in ["dev_2.2", "dev_3.2", "dev_4.2", "dev_7.2", "dev_9.2"]
and safe_get(
energy, [key, "CurrentElectricityQuantity"], default="NaN"
)
!= "NaN"
):
self._dev_id["elecusageflowpulse"] = key
self._dev_id["elecusagecntpulse"] = key
"""gas verbruik"""
if (
dev["type"] in ["gas", "HAE_METER_v2_1", "HAE_METER_v3_1", "HAE_METER_v4_1"]
and safe_get(energy, [key, "CurrentGasQuantity"], default="NaN")
!= "NaN"
):
self._dev_id["gasused"] = key
self._dev_id["gasusedcnt"] = key
"""elec verbruik laag"""
if (
dev["type"]
in [
"elec_delivered_lt",
"HAE_METER_v2_5",
"HAE_METER_v3_6",
"HAE_METER_v3_5",
"HAE_METER_v4_6",
"HAE_METER_HEAT_5",
]
and safe_get(
energy, [key, "CurrentElectricityQuantity"], default="NaN"
)
!= "NaN"
):
self._dev_id["elecusageflowlow"] = key
self._dev_id["elecusagecntlow"] = key
"""elec verbruik hoog/normaal"""
if (
dev["type"]
in [
"elec_delivered_nt",
"HAE_METER_v2_3",
"HAE_METER_v3_3",
"HAE_METER_v3_4",
"HAE_METER_v4_4",
"HAE_METER_HEAT_3",
]
and safe_get(
energy, [key, "CurrentElectricityQuantity"], default="NaN"
)
!= "NaN"
):
self._dev_id["elecusageflowhigh"] = key
self._dev_id["elecusagecnthigh"] = key
"""elec teruglevering laag"""
if (
dev["type"]
in [
"elec_received_lt",
"HAE_METER_v2_6",
"HAE_METER_v3_7",
"HAE_METER_v4_7",
"HAE_METER_HEAT_6",
]
and safe_get(
energy, [key, "CurrentElectricityQuantity"], default="NaN"
)
!= "NaN"
):
self._dev_id["elecprodflowlow"] = key
self._dev_id["elecprodcntlow"] = key
"""elec teruglevering hoog/normaal"""
if (
dev["type"]
in [
"elec_received_nt",
"HAE_METER_v2_4",
"HAE_METER_v3_5",
"HAE_METER_v4_5",
"HAE_METER_HEAT_4",
]
and safe_get(
energy, [key, "CurrentElectricityQuantity"], default="NaN"
)
!= "NaN"
):
self._dev_id["elecprodflowhigh"] = key
self._dev_id["elecprodcnthigh"] = key
"""solar"""
if (
dev["type"]
in [
"elec_solar",
"HAE_METER_v3_3",
"HAE_METER_v4_3",
]
and safe_get(
energy, [key, "CurrentElectricityQuantity"], default="NaN"
)
!= "NaN"
):
self._dev_id["elecsolar"] = key
self._dev_id["elecsolarcnt"] = key
"""heat"""
if (
dev["name"]
in [
"heat",
"HAE_METER_v3_8",
"HAE_METER_v4_8",
"HAE_METER_HEAT_1",
]
and safe_get(
energy, [key, "CurrentHeatQuantity"], default="NaN"
)
!= "NaN"
):
self._dev_id["heat"] = key
"""water"""
if (
dev["type"]
in [
"HAE_METER_v4_9",
]
and safe_get(
energy, [key, "CurrentWaterQuantity"], default="NaN"
)
!= "NaN"
):
self._dev_id["waterquantity"] = key
self._dev_id["waterflow"] = key
self._discovery = True
_LOGGER.debug("Discovered: '%s'", self._dev_id)
"""gas verbruik laatste uur"""
if self.device_type == "gasused":
if self.device_type in self._dev_id:
self._state = (
float(energy[self._dev_id[self.device_type]]["CurrentGasFlow"]) / 1000
)
"""gas verbruik teller laatste uur"""
elif self.device_type == "gasusedcnt":
if self.device_type in self._dev_id:
self._state = (
float(energy[self._dev_id[self.device_type]]["CurrentGasQuantity"]) / 1000
)
"""elec verbruik puls"""
elif self.device_type == "elecusageflowpulse":
if self.device_type in self._dev_id:
self._state = (
float(energy[self._dev_id[self.device_type]]["CurrentElectricityFlow"])
)
"""elec verbruik teller puls"""
elif self.device_type == "elecusagecntpulse":
if self.device_type in self._dev_id:
self._state = (
float(energy[self._dev_id[self.device_type]]["CurrentElectricityQuantity"]) / 1000
)
"""elec verbruik laag"""
elif self.device_type == "elecusageflowlow":
if self.device_type in self._dev_id:
self._state = self._validateOutput(
energy[self._dev_id[self.device_type]]["CurrentElectricityFlow"]
)
"""elec verbruik teller laag"""
elif self.device_type == "elecusagecntlow":
if self.device_type in self._dev_id:
self._state = self._validateOutput(
float(
energy[self._dev_id[self.device_type]]["CurrentElectricityQuantity"]
)
/ 1000
)
"""elec verbruik hoog/normaal"""
elif self.device_type == "elecusageflowhigh":
if self.device_type in self._dev_id:
self._state = self._validateOutput(
energy[self._dev_id[self.device_type]]["CurrentElectricityFlow"]
)
"""elec verbruik teller hoog/normaal"""
elif self.device_type == "elecusagecnthigh":
if self.device_type in self._dev_id:
self._state = self._validateOutput(
float(
energy[self._dev_id[self.device_type]]["CurrentElectricityQuantity"]
)
/ 1000
)
"""elec teruglever laag"""
elif self.device_type == "elecprodflowlow":
if self.device_type in self._dev_id:
self._state = self._validateOutput(
energy[self._dev_id[self.device_type]]["CurrentElectricityFlow"]
)
"""elec teruglever teller laag"""
elif self.device_type == "elecprodcntlow":
if self.device_type in self._dev_id:
self._state = self._validateOutput(
float(
energy[self._dev_id[self.device_type]]["CurrentElectricityQuantity"]
)
/ 1000
)
"""elec teruglever hoog/normaal"""
elif self.device_type == "elecprodflowhigh":
if self.device_type in self._dev_id:
self._state = self._validateOutput(
energy[self._dev_id[self.device_type]]["CurrentElectricityFlow"]
)
"""elec teruglever teller hoog/normaal"""
elif self.device_type == "elecprodcnthigh":
if self.device_type in self._dev_id:
self._state = self._validateOutput(
float(
energy[self._dev_id[self.device_type]]["CurrentElectricityQuantity"]
)
/ 1000
)
"""zon op toon"""
elif self.device_type == "elecsolar":
if "dev_4.export" in energy:
self._state = self._validateOutput(
energy["dev_4.export"]["CurrentElectricityFlow"]
)
elif "dev_3.export" in energy:
self._state = self._validateOutput(
energy["dev_3.export"]["CurrentElectricityFlow"]
)
elif "dev_7.export" in energy:
self._state = self._validateOutput(
energy["dev_7.export"]["CurrentElectricityFlow"]
)
elif self.device_type in self._dev_id:
self._state = self._validateOutput(
energy[self._dev_id[self.device_type]]["CurrentElectricityFlow"]
)
"""zon op toon teller"""
elif self.device_type == "elecsolarcnt":
if "dev_4.export" in energy:
self._state = self._validateOutput(
float(energy["dev_4.export"]["CurrentElectricityQuantity"]) / 1000
)
elif "dev_3.export" in energy:
self._state = self._validateOutput(
float(energy["dev_3.export"]["CurrentElectricityQuantity"]) / 1000
)
elif "dev_7.export" in energy:
self._state = self._validateOutput(
float(energy["dev_7.export"]["CurrentElectricityQuantity"]) / 1000
)
elif self.device_type in self._dev_id:
self._state = self._validateOutput(
float(
energy[self._dev_id[self.device_type]]["CurrentElectricityQuantity"]
)
/ 1000
)
elif self.device_type == "heat":
if self.device_type in self._dev_id:
self._state = self._validateOutput(
float(
energy[self._dev_id[self.device_type]]["CurrentHeatQuantity"]
)
/ 1000
)
elif self.device_type == "waterquantity":
if self.device_type in self._dev_id:
self._state = (
float(energy[self._dev_id[self.device_type]]["CurrentWaterQuantity"])
)
elif self.device_type == "waterflow":
if self.device_type in self._dev_id:
self._state = (
float(energy[self._dev_id[self.device_type]]["CurrentWaterFlow"])
)
elif self.device_type == "powerplugflow":
for key in energy:
dev = energy[key]
if dev["name"] == self.powerplug_name:
self._state = self._validateOutput(
float(
dev["CurrentElectricityFlow"]
)
)
elif self.device_type == "powerplugcnt":
for key in energy:
dev = energy[key]
if dev["name"] == self.powerplug_name:
self._state = self._validateOutput(
float(
dev["CurrentElectricityQuantity"]
)
/ 1000
)
_LOGGER.debug(f"Device: {self.device_type} State: {self._state} PowerPlug: {self.powerplug_name}")
def safe_get(_dict, keys, default=None):
def _reducer(d, key):
if isinstance(d, dict):
return d.get(key, default)
return default
return reduce(_reducer, keys, _dict)