Debian Codegraph @

src/ayla_iot_unofficial/fujitsu_hvac.py

raw
1 from time import sleep as syncsleep
2 from asyncio import sleep
3 from typing import Any, Dict, TYPE_CHECKING
4 from datetime import datetime, timedelta, timezone
5 from enum import Enum
6
7 from .device import Device, PropertyName, PropertyValue, AylaReadOnlyPropertyError
8 from .fujitsu_consts import (
9 OEM_MODEL,
10 REFRESH,
11 DISPLAY_TEMP,
12 DEVICE_NAME,
13 DEVICE_CAPABILITIES,
14 OPERATION_MODE,
15 OUTDOOR_TEMPERATURE,
16 ADJUST_TEMPERATURE,
17 FAN_SPEED,
18 HORIZ_SWING_PARAM_MAP,
19 VERT_SWING_PARAM_MAP,
20 SENSED_TEMP_SUPPORTED,
21 SWING_VAL_MAP,
22 MIN_SENSED_TEMP,
23 MAX_SENSED_TEMP,
24 MIN_SENSED_CELSIUS,
25 MAX_SENSED_CELSIUS,
26 MIN_TEMP_HEAT,
27 MAX_TEMP_HEAT,
28 MIN_TEMP_COOL,
29 MAX_TEMP_COOL,
30 DEVICE_MAP,
31 Capability,
32 OpMode,
33 SwingMode,
34 FanSpeed,
35 )
36
37 if TYPE_CHECKING:
38 from .ayla_iot_unofficial import AylaApi
39
40 class DeviceNotSupportedError(Exception):
41 pass
42
43 class SettingNotSupportedError(Exception):
44 pass
45
46 class DeviceOffline(Exception):
47 pass
48
49 def _convert_sensed_temp_to_celsius(value: int) -> float:
50 source_span = MAX_SENSED_TEMP - MIN_SENSED_TEMP
51 celsius_span = MAX_SENSED_CELSIUS - MIN_SENSED_CELSIUS
52
53 value_scaled = float(value - MIN_SENSED_TEMP) / float(source_span)
54
55 return MIN_SENSED_CELSIUS + (value_scaled * celsius_span)
56
57 def check_online(func):
58 def wrapped(self, *args, **kwargs):
59 if not self.is_online():
60 raise DeviceOffline
61
62 return func(self, *args, **kwargs)
63
64 return wrapped
65
66 def check_online_async(func):
67 async def wrapped(self, *args, **kwargs):
68 if not self.is_online():
69 raise DeviceOffline
70
71 return await func(self, *args, **kwargs)
72
73 return wrapped
74
75 class FujitsuHVAC(Device):
76 @staticmethod
77 def supports(device: Dict) -> bool:
78 if OEM_MODEL not in device:
79 return False
80
81 if device[OEM_MODEL] in [
82 model for models in DEVICE_MAP.values() for model in models
83 ]:
84 return True
85
86 return False
87
88 def __init__(self, ayla_api: "AylaApi", device_dct: Dict, europe: bool = False):
89 super().__init__(ayla_api, device_dct, europe)
90 if OEM_MODEL not in device_dct:
91 raise DeviceNotSupportedError("This device is not supported by FujitsuHVAC.")
92
93 self.model = None
94 for modeltype, devices in DEVICE_MAP.items():
95 if device_dct[OEM_MODEL] in devices:
96 self.model = modeltype
97
98 if not self.model:
99 raise DeviceNotSupportedError("This device is not supported by FujitsuHVAC.")
100
101 self._connection_status = device_dct["connection_status"]
102
103 def is_online(self):
104 return self._connection_status != 'Offline'
105
106 @check_online
107 def set_property_value(self, property_name: PropertyName, value: PropertyValue, poll=False, keep_polling_value=None):
108 """Update a property"""
109 if isinstance(property_name, Enum):
110 property_name = property_name.value
111 if isinstance(value, Enum):
112 value = value.value
113
114 if self.properties_full.get(property_name, {}).get('read_only'):
115 raise AylaReadOnlyPropertyError(f'{property_name} is read only')
116 else:
117 """ Get the name of the property. Case sizing for 'SET' varies """
118 property_name = self.properties_full.get(property_name).get("name")
119
120 end_point = self.set_property_endpoint(property_name)
121 data = {'datapoint': {'value': value}}
122 if poll:
123 data['datapoint']['echo'] = 0
124
125 resp = self.ayla_api.self_request('post', end_point, json=data)
126 if poll:
127 self.poll_while(property_name, keep_polling_value)
128 else:
129 self.properties_full[property_name].update(resp)
130
131 @check_online_async
132 async def async_set_property_value(self, property_name: PropertyName, value: PropertyValue, poll=False, keep_polling_value=None):
133 """Update a property async. Override the parent version since it adds SET_ in front of the property name."""
134 if isinstance(property_name, Enum):
135 property_name = property_name.value
136 if isinstance(value, Enum):
137 value = value.value
138
139 if self.properties_full.get(property_name, {}).get('read_only'):
140 raise AylaReadOnlyPropertyError(f'{property_name} is read only')
141 else:
142 """ Get the name of the property. Case sizing for 'SET' varies """
143 property_name = self.properties_full.get(property_name).get("name")
144
145 end_point = self.set_property_endpoint(property_name)
146 data = {'datapoint': {'value': value}}
147 if poll:
148 data['datapoint']['echo'] = 0
149
150 async with await self.ayla_api.async_request('post', end_point, json=data, headers={'x-ayla-source': 'Mobile'}) as resp:
151 resp_data = await resp.json()
152
153 if poll:
154 await self.async_poll_while(property_name, keep_polling_value)
155 else:
156 self.properties_full[property_name].update(resp_data)
157
158
159 @check_online
160 def update(self, props: list[str] | None=None):
161 super().update(props)
162
163 @check_online_async
164 async def async_update(self, props: list[str] | None=None):
165 await super().async_update(props)
166 await self.refresh_sensed_temp()
167
168 def get_last_datapoint(self, property: str) -> dict[str, Any] | None:
169 endpoint = self.set_property_endpoint(property)
170 extra_param = {"limit": 1}
171 data = self.ayla_api.self_request("get", endpoint, params=extra_param).json()
172
173 if len(data) > 0:
174 return data[-1]["datapoint"]
175
176 async def async_get_last_datapoint(self, property: str) -> dict[str, Any] | None:
177 endpoint = self.set_property_endpoint(property)
178 extra_param = {"limit": 1}
179 async with await self.ayla_api.async_request("get", endpoint, params=extra_param) as resp:
180 data = await resp.json()
181
182 if len(data) > 0:
183 return data[-1]["datapoint"]
184
185 return None
186
187 def poll_while(self, property: str, keep_polling_value: Any):
188 count = 0
189 datapoint = self.get_last_datapoint(property)
190 while count < 10:
191 datapoint = self.get_last_datapoint(property)
192 if datapoint and datapoint["value"] != keep_polling_value and datapoint["echo"] == True:
193 break
194
195 count += 1
196 syncsleep(1)
197
198 async def async_poll_while(self, property: str, keep_polling_value: Any):
199 count = 0
200 datapoint = await self.async_get_last_datapoint(property)
201 while count < 10:
202 datapoint = await self.async_get_last_datapoint(property)
203 if datapoint and datapoint["value"] != keep_polling_value and datapoint["echo"] == True:
204 break
205
206 count += 1
207 await sleep(1)
208
209 async def refresh_sensed_temp(self):
210 if SENSED_TEMP_SUPPORTED[self.model]:
211 await self.async_set_property_value(REFRESH, 1)
212 await super().async_update([DISPLAY_TEMP])
213
214 @property
215 def device_name(self) -> str:
216 return self.property_values[DEVICE_NAME]
217
218 @property
219 def capabilities(self) -> Dict[Capability, bool]:
220 caps = self.property_values[DEVICE_CAPABILITIES]
221 ret = {}
222 for c in Capability:
223 if caps & c == c:
224 ret[c] = True
225 else:
226 ret[c] = False
227
228 return ret
229
230 def has_capability(self, capability: Capability) -> bool:
231 try:
232 return self.capabilities[capability]
233 except KeyError:
234 return False
235
236 @property
237 def supported_op_modes(self) -> list[OpMode]:
238 modes = [
239 mode
240 for mode in OpMode
241 if getattr(Capability, f"OP_{mode.name}", False)
242 and self.has_capability(Capability[f"OP_{mode.name}"])
243 ]
244 modes.append(OpMode.OFF)
245 modes.append(OpMode.ON)
246 return modes
247
248 @property
249 def op_mode(self) -> OpMode:
250 return OpMode(self.property_values[OPERATION_MODE])
251
252 @op_mode.setter
253 def op_mode(self, val: OpMode):
254 if val not in self.supported_op_modes:
255 raise SettingNotSupportedError(f"Device does not support operation mode {val.name}")
256
257 self.set_property_value(OPERATION_MODE, val)
258
259 async def async_set_op_mode(self, val: OpMode):
260 if val not in self.supported_op_modes:
261 raise SettingNotSupportedError(f"Device does not support operation mode {val.name}")
262
263 await self.async_set_property_value(OPERATION_MODE, val)
264
265 @property
266 def supported_fan_speeds(self) -> list[FanSpeed]:
267 return [
268 speed
269 for speed in FanSpeed
270 if self.has_capability(Capability[f"FAN_{speed.name}"])
271 ]
272
273 @property
274 def fan_speed(self) -> FanSpeed:
275 return FanSpeed(self.property_values[FAN_SPEED])
276
277 @fan_speed.setter
278 def fan_speed(self, val: FanSpeed):
279 if val not in self.supported_fan_speeds:
280 raise SettingNotSupportedError(f"Device does not support fan speed {val.name}")
281
282 self.set_property_value(FAN_SPEED, val)
283
284 async def async_set_fan_speed(self, val: FanSpeed):
285 if val not in self.supported_fan_speeds:
286 raise SettingNotSupportedError(f"Device does not support fan speed {val.name}")
287
288 await self.async_set_property_value(FAN_SPEED, val)
289
290 @property
291 def sensed_temp(self) -> float | None:
292 if SENSED_TEMP_SUPPORTED[self.model]:
293 return (
294 round(
295 _convert_sensed_temp_to_celsius(
296 int(self.property_values[DISPLAY_TEMP])
297 )
298 * 2
299 )
300 / 2
301 )
302 return None
303
304 @property
305 def outdoor_temperature(self) -> float | None:
306 if (OUTDOOR_TEMPERATURE in self.property_values
307 and self.property_values[OUTDOOR_TEMPERATURE] is not None):
308 return (
309 round(
310 _convert_sensed_temp_to_celsius(
311 int(self.property_values[OUTDOOR_TEMPERATURE])
312 )
313 * 2
314 )
315 / 2
316 )
317 return None
318
319
320 def temperature_range_for_mode(self, mode: OpMode) -> (float, float):
321 if mode not in self.supported_op_modes:
322 raise SettingNotSupportedError(f"Device does not support operation mode {mode.name}")
323
324 if mode == OpMode.HEAT:
325 return (MIN_TEMP_HEAT, MAX_TEMP_HEAT)
326
327 return (MIN_TEMP_COOL, MAX_TEMP_COOL)
328
329 @property
330 def temperature_range(self) -> (float, float):
331 return self.temperature_range_for_mode(self.op_mode)
332
333 @property
334 def set_temp(self) -> float:
335 return float(self.property_values[ADJUST_TEMPERATURE]) / 10.0
336
337 @set_temp.setter
338 def set_temp(self, val: float):
339 # Sometimes F to C conversion doesn't land on a half degree multiple
340 # so round to the nearest 0.5C
341 self.set_property_value(ADJUST_TEMPERATURE, int((round(val*2.0) / 2.0) * 10.0))
342
343 async def async_set_set_temp(self, val: float):
344 await self.async_set_property_value(ADJUST_TEMPERATURE, int((round(val*2.0) / 2.0) * 10.0))
345
346 @property
347 def supported_swing_modes(self) -> list[SwingMode]:
348 modes = [
349 mode
350 for mode in SwingMode
351 if getattr(Capability, mode.name, False)
352 and self.has_capability(Capability[mode.name])
353 ]
354 if SwingMode.SWING_HORIZONTAL in modes and SwingMode.SWING_VERTICAL in modes:
355 modes.append(SwingMode.SWING_BOTH)
356
357 if len(modes) > 0:
358 modes.append(SwingMode.OFF)
359
360 return modes
361
362 @property
363 def swing_mode(self) -> SwingMode:
364 if self.horizontal_swing and self.vertical_swing:
365 return SwingMode.SWING_BOTH
366 elif self.horizontal_swing:
367 return SwingMode.SWING_HORIZONTAL
368 elif self.vertical_swing:
369 return SwingMode.SWING_VERTICAL
370 else:
371 return SwingMode.OFF
372
373 @swing_mode.setter
374 def swing_mode(self, val: SwingMode):
375 if val not in self.supported_swing_modes:
376 raise SettingNotSupportedError(f"Device does not support swing mode {val.name}")
377
378 if val == SwingMode.SWING_BOTH:
379 self.horizontal_swing = True
380 self.vertical_swing = True
381 elif val == SwingMode.SWING_HORIZONTAL:
382 self.horizontal_swing = True
383 self.vertical_swing = False
384 elif val == SwingMode.SWING_VERTICAL:
385 self.vertical_swing = True
386 self.horizontal_swing = False
387 elif val == SwingMode.OFF:
388 self.vertical_swing = False
389 self.horizontal_swing = False
390
391 async def async_set_swing_mode(self, val: SwingMode):
392 if val not in self.supported_swing_modes:
393 raise SettingNotSupportedError(f"Device does not support swing mode {val.name}")
394
395 if val == SwingMode.SWING_BOTH:
396 await self.async_set_horizontal_swing(True)
397 await self.async_set_vertical_swing(True)
398 elif val == SwingMode.SWING_HORIZONTAL:
399 await self.async_set_horizontal_swing(True)
400 await self.async_set_vertical_swing(False)
401 elif val == SwingMode.SWING_VERTICAL:
402 await self.async_set_vertical_swing(True)
403 await self.async_set_horizontal_swing(False)
404 elif val == SwingMode.OFF:
405 await self.async_set_vertical_swing(False)
406 await self.async_set_horizontal_swing(False)
407
408 @property
409 def horizontal_swing(self) -> bool:
410 if not self.has_capability(Capability.SWING_HORIZONTAL):
411 return False
412
413 return self.property_values[HORIZ_SWING_PARAM_MAP[self.model]] == SWING_VAL_MAP[self.model][True]
414
415 @horizontal_swing.setter
416 def horizontal_swing(self, val: bool):
417 if not self.has_capability(Capability.SWING_HORIZONTAL):
418 raise SettingNotSupportedError("Device does not support horizontal swing")
419
420 self.set_property_value(HORIZ_SWING_PARAM_MAP[self.model], SWING_VAL_MAP[self.model][val])
421
422 async def async_set_horizontal_swing(self, val: bool):
423 if not self.has_capability(Capability.SWING_HORIZONTAL):
424 raise SettingNotSupportedError("Device does not support horizontal swing")
425
426 await self.async_set_property_value(HORIZ_SWING_PARAM_MAP[self.model], SWING_VAL_MAP[self.model][val])
427
428 @property
429 def vertical_swing(self) -> bool:
430 if not self.has_capability(Capability.SWING_VERTICAL):
431 return False
432
433 return self.property_values[VERT_SWING_PARAM_MAP[self.model]] == SWING_VAL_MAP[self.model][True]
434
435 @vertical_swing.setter
436 def vertical_swing(self, val: bool):
437 if not self.has_capability(Capability.SWING_VERTICAL):
438 raise SettingNotSupportedError("Device does not support vertical swing")
439
440 self.set_property_value(VERT_SWING_PARAM_MAP[self.model], SWING_VAL_MAP[self.model][val])
441
442 async def async_set_vertical_swing(self, val: bool):
443 if not self.has_capability(Capability.SWING_VERTICAL):
444 raise SettingNotSupportedError("Device does not support vertical swing")
445
446 await self.async_set_property_value(VERT_SWING_PARAM_MAP[self.model], SWING_VAL_MAP[self.model][val])