-
Notifications
You must be signed in to change notification settings - Fork 31
/
sensor.py
320 lines (262 loc) · 10.9 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
import logging
from datetime import datetime, timedelta
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_registry import async_get_registry
from custom_components.miele import DATA_DEVICES
from custom_components.miele import DOMAIN as MIELE_DOMAIN
PLATFORMS = ["miele"]
_LOGGER = logging.getLogger(__name__)
ALL_DEVICES = []
def _map_key(key):
if key == "status":
return "Status"
elif key == "programType":
return "Program Type"
elif key == "programPhase":
return "Program Phase"
elif key == "targetTemperature":
return "Target Temperature"
elif key == "temperature":
return "Temperature"
elif key == "remainingTime":
return "Remaining Time"
elif key == "elapsedTime":
return "Elapsed Time"
elif key == "startTime":
return "Start Time"
def _to_seconds(time_array):
if len(time_array) == 3:
return time_array[0] * 3600 + time_array[1] * 60 + time_array[2]
elif len(time_array) == 2:
return time_array[0] * 3600 + time_array[1] * 60
else:
return 0
# pylint: disable=W0612
def setup_platform(hass, config, add_devices, discovery_info=None):
global ALL_DEVICES
devices = hass.data[MIELE_DOMAIN][DATA_DEVICES]
for k, device in devices.items():
device_state = device["state"]
sensors = []
if "status" in device_state:
sensors.append(MieleStatusSensor(hass, device, "status"))
if "targetTemperature" in device_state:
for i, val in enumerate(device_state["targetTemperature"]):
sensors.append(
MieleTemperatureSensor(hass, device, "targetTemperature", i)
)
if "temperature" in device_state:
for i, val in enumerate(device_state["temperature"]):
sensors.append(MieleTemperatureSensor(hass, device, "temperature", i))
if "remainingTime" in device_state:
sensors.append(MieleTimeSensor(hass, device, "remainingTime"))
if "startTime" in device_state:
sensors.append(MieleTimeSensor(hass, device, "startTime"))
if "elapsedTime" in device_state:
sensors.append(MieleTimeSensor(hass, device, "elapsedTime"))
add_devices(sensors)
ALL_DEVICES = ALL_DEVICES + sensors
def update_device_state():
for device in ALL_DEVICES:
try:
device.async_schedule_update_ha_state(True)
except AssertionError:
_LOGGER.debug(
"Component most likely is disabled manually, if not please report to developer"
"{}".format(device.entity_id)
)
class MieleRawSensor(Entity):
def __init__(self, hass, device, key):
self._hass = hass
self._device = device
self._key = key
@property
def device_id(self):
"""Return the unique ID for this sensor."""
return self._device["ident"]["deviceIdentLabel"]["fabNumber"]
@property
def unique_id(self):
"""Return the unique ID for this sensor."""
return self.device_id + "_" + self._key
@property
def name(self):
"""Return the name of the sensor."""
ident = self._device["ident"]
result = ident["deviceName"]
if len(result) == 0:
return ident["type"]["value_localized"] + " " + _map_key(self._key)
else:
return result + " " + _map_key(self._key)
@property
def state(self):
"""Return the state of the sensor."""
return self._device["state"][self._key]["value_raw"]
async def async_update(self):
if not self.device_id in self._hass.data[MIELE_DOMAIN][DATA_DEVICES]:
_LOGGER.debug("Miele device disappeared: {}".format(self.device_id))
else:
self._device = self._hass.data[MIELE_DOMAIN][DATA_DEVICES][self.device_id]
class MieleStatusSensor(MieleRawSensor):
def __init(self, client, device, key):
pass
@property
def state(self):
"""Return the state of the sensor."""
result = self._device["state"]["status"]["value_localized"]
if result == None:
result = self._device["state"]["status"]["value_raw"]
return result
@property
def device_state_attributes(self):
"""Attributes."""
device_state = self._device["state"]
attributes = {}
if "programType" in device_state:
attributes["programType"] = device_state["programType"]["value_localized"]
attributes["rawProgramType"] = device_state["programType"]["value_raw"]
if "programPhase" in device_state:
attributes["programPhase"] = device_state["programPhase"]["value_localized"]
attributes["rawProgramPhase"] = device_state["programPhase"]["value_raw"]
if "dryingStep" in device_state:
attributes["dryingStep"] = device_state["dryingStep"]["value_localized"]
attributes["rawDryingStep"] = device_state["dryingStep"]["value_raw"]
if "spinningSpeed" in device_state:
attributes["spinningSpeed"] = device_state["spinningSpeed"][
"value_localized"
]
attributes["rawSpinningSpeed"] = device_state["spinningSpeed"]["value_raw"]
if "ventilationStep" in device_state:
attributes["ventilationStep"] = device_state["ventilationStep"][
"value_localized"
]
attributes["rawVentilationStep"] = device_state["ventilationStep"][
"value_raw"
]
if "plateStep" in device_state:
plate_steps = 1
for plateStep in device_state["plateStep"]:
attributes["plateStep" + str(plate_steps)] = plateStep[
"value_localized"
]
attributes["rawPlateStep" + str(plate_steps)] = plateStep["value_raw"]
plate_steps += 1
if "ecoFeedback" in device_state and device_state["ecoFeedback"] is not None:
if "currentWaterConsumption" in device_state["ecoFeedback"]:
attributes["currentWaterConsumption"] = device_state["ecoFeedback"][
"currentWaterConsumption"
]["value"]
attributes["currentWaterConsumptionUnit"] = device_state["ecoFeedback"][
"currentWaterConsumption"
]["unit"]
if "currentEnergyConsumption" in device_state["ecoFeedback"]:
attributes["currentEnergyConsumption"] = device_state["ecoFeedback"][
"currentEnergyConsumption"
]["value"]
attributes["currentEnergyConsumptionUnit"] = device_state[
"ecoFeedback"
]["currentEnergyConsumption"]["unit"]
if "waterForecast" in device_state["ecoFeedback"]:
attributes["waterForecast"] = device_state["ecoFeedback"][
"waterForecast"
]
if "energyForecast" in device_state["ecoFeedback"]:
attributes["energyForecast"] = device_state["ecoFeedback"][
"energyForecast"
]
# Programs will only be running of both remainingTime and elapsedTime indicate
# a value > 0
if "remainingTime" in device_state and "elapsedTime" in device_state:
remainingTime = _to_seconds(device_state["remainingTime"])
elapsedTime = _to_seconds(device_state["elapsedTime"])
if "startTime" in device_state:
startTime = _to_seconds(device_state["startTime"])
else:
startTime = 0
# Calculate progress
if (elapsedTime + remainingTime) == 0:
attributes["progress"] = None
else:
attributes["progress"] = round(
elapsedTime / (elapsedTime + remainingTime) * 100, 1
)
# Calculate end time
if remainingTime == 0:
attributes["finishTime"] = None
else:
now = datetime.now()
attributes["finishTime"] = (
now
+ timedelta(seconds=startTime)
+ timedelta(seconds=remainingTime)
).strftime("%H:%M")
# Calculate start time
if startTime == 0:
now = datetime.now()
attributes["kickoffTime"] = (
now - timedelta(seconds=elapsedTime)
).strftime("%H:%M")
else:
now = datetime.now()
attributes["kickoffTime"] = (
now + timedelta(seconds=startTime)
).strftime("%H:%M")
return attributes
class MieleTimeSensor(MieleRawSensor):
def __init(self, hass, device, key):
pass
@property
def state(self):
"""Return the state of the sensor."""
state_value = self._device["state"][self._key]
if len(state_value) != 2:
return None
else:
return "{:02d}:{:02d}".format(state_value[0], state_value[1])
class MieleTemperatureSensor(Entity):
def __init__(self, hass, device, key, index):
self._hass = hass
self._device = device
self._key = key
self._index = index
@property
def device_id(self):
"""Return the unique ID for this sensor."""
return self._device["ident"]["deviceIdentLabel"]["fabNumber"]
@property
def unique_id(self):
"""Return the unique ID for this sensor."""
return self.device_id + "_" + self._key + "_{}".format(self._index)
@property
def name(self):
"""Return the name of the sensor."""
ident = self._device["ident"]
result = ident["deviceName"]
if len(result) == 0:
return "{} {} {}".format(
ident["type"]["value_localized"], _map_key(self._key), self._index
)
else:
return "{} {} {}".format(result, _map_key(self._key), self._index)
@property
def state(self):
"""Return the state of the sensor."""
state_value = self._device["state"][self._key][self._index]["value_raw"]
if state_value == -32768:
return None
else:
return state_value / 100
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
if self._device["state"][self._key][self._index]["unit"] == "Celsius":
return "°C"
elif self._device["state"][self._key][self._index]["unit"] == "Fahrenheit":
return "°F"
@property
def device_class(self):
return "temperature"
async def async_update(self):
if not self.device_id in self._hass.data[MIELE_DOMAIN][DATA_DEVICES]:
_LOGGER.debug(" Miele device disappeared: {}".format(self.device_id))
else:
self._device = self._hass.data[MIELE_DOMAIN][DATA_DEVICES][self.device_id]