| 1 |
"""Basic non-device-specific data object""" |
| 2 |
|
| 3 |
from .exc import AylaReadOnlyPropertyError |
| 4 |
from base64 import b64encode |
| 5 |
from collections import abc, defaultdict |
| 6 |
from datetime import datetime |
| 7 |
from enum import Enum, IntEnum, unique |
| 8 |
from logging import getLogger |
| 9 |
from pprint import pformat |
| 10 |
from re import findall |
| 11 |
from requests import get |
| 12 |
from typing import Any, Dict, Iterable, List, Optional, Set, Union, TYPE_CHECKING |
| 13 |
|
| 14 |
try: |
| 15 |
from ujson import loads |
| 16 |
except ImportError: |
| 17 |
from json import loads |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from .ayla_iot_unofficial import AylaApi |
| 21 |
|
| 22 |
TIMESTAMP_FMT = '%Y-%m-%dT%H:%M:%SZ' |
| 23 |
_LOGGER = getLogger(__name__) |
| 24 |
|
| 25 |
PropertyName = Union[str, Enum] |
| 26 |
PropertyValue = Union[str, int, Enum] |
| 27 |
|
| 28 |
|
| 29 |
def _parse_datetime(date_string: str) -> datetime: |
| 30 |
"""Parse a datetime as returned by the Ayla Networks API""" |
| 31 |
return datetime.strptime(date_string, TIMESTAMP_FMT) |
| 32 |
|
| 33 |
|
| 34 |
@unique |
| 35 |
class VacuumPowerModes(IntEnum): |
| 36 |
"""Vacuum power modes""" |
| 37 |
ECO = 1 |
| 38 |
NORMAL = 0 |
| 39 |
MAX = 2 |
| 40 |
|
| 41 |
|
| 42 |
@unique |
| 43 |
class VacuumOperatingModes(IntEnum): |
| 44 |
"""Vacuum operation modes""" |
| 45 |
STOP = 0 |
| 46 |
PAUSE = 1 |
| 47 |
START = 2 |
| 48 |
RETURN = 3 |
| 49 |
|
| 50 |
|
| 51 |
@unique |
| 52 |
class VacuumProperties(Enum): |
| 53 |
"""Useful properties""" |
| 54 |
""" VACUUM DEVICES """ |
| 55 |
AREAS_TO_CLEAN = "Areas_To_Clean" |
| 56 |
BATTERY_CAPACITY = "Battery_Capacity" |
| 57 |
CHARGING_STATUS = "Charging_Status" |
| 58 |
CLEAN_COMPLETE = "CleanComplete" |
| 59 |
CLEANING_STATISTICS = "Cleaning_Statistics" |
| 60 |
DOCKED_STATUS = "DockedStatus" |
| 61 |
ERROR_CODE = "Error_Code" |
| 62 |
EVACUATING = "Evacuating" # Doesn't really work because update frequency on the dock (default 20s) is too slow |
| 63 |
FIND_DEVICE = "Find_Device" |
| 64 |
LOW_LIGHT_MISSION = "LowLightMission" |
| 65 |
NAV_MODULE_FW_VERSION = "Nav_Module_FW_Version" |
| 66 |
OPERATING_MODE = "Operating_Mode" |
| 67 |
POWER_MODE = "Power_Mode" |
| 68 |
RECHARGE_RESUME = "Recharge_Resume" |
| 69 |
RECHARGING_TO_RESUME = "Recharging_To_Resume" |
| 70 |
ROBOT_FIRMWARE_VERSION = "Robot_Firmware_Version" |
| 71 |
ROBOT_ROOM_LIST = "Robot_Room_List" |
| 72 |
RSSI = "RSSI" |
| 73 |
|
| 74 |
|
| 75 |
VACUUM_ERROR_MESSAGES = { |
| 76 |
1: "Side wheel is stuck", |
| 77 |
2: "Side brush is stuck", |
| 78 |
3: "Suction motor failed", |
| 79 |
4: "Brushroll stuck", |
| 80 |
5: "Side wheel is stuck (2)", |
| 81 |
6: "Bumper is stuck", |
| 82 |
7: "Cliff sensor is blocked", |
| 83 |
8: "Battery power is low", |
| 84 |
9: "No Dustbin", |
| 85 |
10: "Fall sensor is blocked", |
| 86 |
11: "Front wheel is stuck", |
| 87 |
13: "Switched off", |
| 88 |
14: "Magnetic strip error", |
| 89 |
16: "Top bumper is stuck", |
| 90 |
18: "Wheel encoder error", |
| 91 |
} |
| 92 |
|
| 93 |
|
| 94 |
class Device: |
| 95 |
"""Generic device entity""" |
| 96 |
|
| 97 |
def __init__(self, ayla_api: "AylaApi", device_dct: Dict, europe: bool = False): |
| 98 |
""" |
| 99 |
Start object with serial = dsn. For some devices (such as SharkIQ vacuums) a device serial number is needed instead. |
| 100 |
call _update_metadata() to update these values. |
| 101 |
Other objects (such as Culligan water softeners), the DSN is used in place of serial numbers |
| 102 |
""" |
| 103 |
self.ayla_api = ayla_api |
| 104 |
self._dsn = device_dct['dsn'] |
| 105 |
self._key = device_dct['key'] |
| 106 |
self._oem_model_number = device_dct['oem_model'] # type: str |
| 107 |
self._device_model_number = device_dct['model'] # type: Optional[str] |
| 108 |
self._device_serial_number = device_dct['dsn'] # type: Optional[str] |
| 109 |
self._device_mac_address = device_dct['mac'] |
| 110 |
self._device_ip_address = device_dct['lan_ip'] |
| 111 |
self.properties_full = defaultdict(dict) # Using a defaultdict prevents errors before calling `update()` |
| 112 |
self.property_values = DevicePropertiesView(self) |
| 113 |
self.triggers = defaultdict(dict) |
| 114 |
self._settable_properties = None # type: Optional[Set] |
| 115 |
self.europe = europe # type: bool |
| 116 |
self.eu_user_field_url = "https://user-field-eu.aylanetworks.com" |
| 117 |
self.eu_ads_url = "https://ads-eu.aylanetworks.com" |
| 118 |
self.user_field_url = "https://user-field.aylanetworks.com" |
| 119 |
self.ads_url = "https://ads-field.aylanetworks.com" |
| 120 |
|
| 121 |
# Properties |
| 122 |
self._name = device_dct['product_name'] |
| 123 |
self._error = None |
| 124 |
|
| 125 |
@property |
| 126 |
def oem_model_number(self) -> str: |
| 127 |
return self._oem_model_number |
| 128 |
|
| 129 |
@property |
| 130 |
def device_model_number(self) -> Optional[str]: |
| 131 |
return self._device_model_number |
| 132 |
|
| 133 |
@property |
| 134 |
def device_serial_number(self) -> Optional[str]: |
| 135 |
return self._device_serial_number |
| 136 |
|
| 137 |
@property |
| 138 |
def name(self): |
| 139 |
return self._name |
| 140 |
|
| 141 |
@property |
| 142 |
def serial_number(self) -> str: |
| 143 |
return self._dsn |
| 144 |
|
| 145 |
@property |
| 146 |
def metadata_endpoint(self) -> str: |
| 147 |
""" |
| 148 |
Endpoint for device metadata. This API returns a list of device metadata keys and values, based on wild cards. |
| 149 |
Possibly handle keys if an endpoint is discovered/needed |
| 150 |
""" |
| 151 |
return f'{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/dsns/{self._dsn:s}/data.json' |
| 152 |
|
| 153 |
@property |
| 154 |
def dsn_all_properties_endpoint(self) -> str: |
| 155 |
""" |
| 156 |
API endpoint to fetch updated device information |
| 157 |
This API retrieves all the properties for a specified device serial number (DSN). |
| 158 |
""" |
| 159 |
return f'{self.eu_ads_url if self.europe else self.ads_url}/apiv1/dsns/{self.serial_number}/properties.json' |
| 160 |
|
| 161 |
def property_triggers_endpoint(self, property_name) -> str: |
| 162 |
""" |
| 163 |
Certain properties have triggers (e.g. notifications, etc.) tied to them. Get the endpoint that contains the trigger data. |
| 164 |
""" |
| 165 |
return f'{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/dsns/{self._dsn:s}/properties/{property_name:s}/triggers.json' |
| 166 |
|
| 167 |
def set_property_endpoint(self, property_name) -> str: |
| 168 |
"""Get the API endpoint for a given property""" |
| 169 |
return f'{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/dsns/{self._dsn:s}/properties/{property_name:s}/datapoints.json' |
| 170 |
|
| 171 |
def _update_metadata(self): |
| 172 |
""" |
| 173 |
Section for vacuum Metadata |
| 174 |
|
| 175 |
Idealy this could generically handle any datums from metadata |
| 176 |
Update object with values from metadata |
| 177 |
""" |
| 178 |
metadata = self.get_metadata() |
| 179 |
data = [d['datum'] for d in metadata if d.get('datum', {}).get('key', '') == 'sharkDeviceMobileData'] |
| 180 |
if data: |
| 181 |
datum = data[0] |
| 182 |
# I do not know why they don't just use multiple keys for this |
| 183 |
try: |
| 184 |
values = loads(datum.get('value')) |
| 185 |
except ValueError: |
| 186 |
values = {} |
| 187 |
self._device_model_number = values.get('vacModelNumber') |
| 188 |
self._device_serial_number = values.get('vacSerialNumber') |
| 189 |
|
| 190 |
def get_metadata(self): |
| 191 |
"""Fetch device metadata. Not needed for basic operation.""" |
| 192 |
resp = self.ayla_api.self_request('get', self.metadata_endpoint) |
| 193 |
return resp.json() |
| 194 |
|
| 195 |
async def async_get_metadata(self): |
| 196 |
"""Fetch device metadata. Not needed for basic operation.""" |
| 197 |
async with await self.ayla_api.async_request('get', self.metadata_endpoint) as resp: |
| 198 |
resp_data = await resp.json() |
| 199 |
return resp_data |
| 200 |
|
| 201 |
def get_property_value(self, property_name: PropertyName) -> Any: |
| 202 |
"""Get the value of a property from the properties dictionary""" |
| 203 |
if isinstance(property_name, Enum): |
| 204 |
property_name = property_name.value |
| 205 |
|
| 206 |
return self.property_values[property_name] |
| 207 |
|
| 208 |
def set_property_value(self, property_name: PropertyName, value: PropertyValue): |
| 209 |
"""Update a property""" |
| 210 |
if isinstance(property_name, Enum): |
| 211 |
property_name = property_name.value |
| 212 |
if isinstance(value, Enum): |
| 213 |
value = value.value |
| 214 |
|
| 215 |
if self.properties_full.get(property_name, {}).get('read_only'): |
| 216 |
raise AylaReadOnlyPropertyError(f'{property_name} is read only') |
| 217 |
else: |
| 218 |
""" Get the name of the property. Case sizing for 'SET' varies """ |
| 219 |
property_name = self.properties_full.get(property_name).get("name") |
| 220 |
|
| 221 |
end_point = self.set_property_endpoint(property_name) |
| 222 |
data = {'datapoint': {'value': value}} |
| 223 |
resp = self.ayla_api.self_request('post', end_point, json=data) |
| 224 |
self.properties_full[property_name].update(resp.json()) |
| 225 |
|
| 226 |
async def async_set_property_value(self, property_name: PropertyName, value: PropertyValue): |
| 227 |
"""Update a property async""" |
| 228 |
if isinstance(property_name, Enum): |
| 229 |
property_name = property_name.value |
| 230 |
if isinstance(value, Enum): |
| 231 |
value = value.value |
| 232 |
|
| 233 |
if self.properties_full.get(property_name, {}).get('read_only'): |
| 234 |
raise AylaReadOnlyPropertyError(f'{property_name} is read only') |
| 235 |
else: |
| 236 |
""" Get the name of the property. Case sizing for 'SET' varies """ |
| 237 |
property_name = self.properties_full.get(property_name).get("name") |
| 238 |
|
| 239 |
end_point = self.set_property_endpoint(property_name) |
| 240 |
data = {'datapoint': {'value': value}} |
| 241 |
async with await self.ayla_api.async_request('post', end_point, json=data) as resp: |
| 242 |
resp_data = await resp.json() |
| 243 |
self.properties_full[property_name].update(resp_data) |
| 244 |
|
| 245 |
def _clean_property_name(self, raw_property_name: str) -> str: |
| 246 |
"""Clean up property names""" |
| 247 |
if raw_property_name[:4].upper() in ['SET_', 'GET_']: |
| 248 |
return raw_property_name[4:] |
| 249 |
else: |
| 250 |
return raw_property_name |
| 251 |
|
| 252 |
def update(self, property_list: Optional[Iterable[str]] = None): |
| 253 |
"""Update the known device state from all properties and call _do_update to add the properties to the object property dictionary""" |
| 254 |
full_update = property_list is None |
| 255 |
if full_update: |
| 256 |
params = None |
| 257 |
else: |
| 258 |
params = {'names[]': property_list} |
| 259 |
|
| 260 |
resp = self.ayla_api.self_request('get', self.dsn_all_properties_endpoint, params=params) |
| 261 |
properties = resp.json() |
| 262 |
|
| 263 |
return self._do_update(full_update, properties) |
| 264 |
|
| 265 |
async def async_update(self, property_list: Optional[Iterable[str]] = None): |
| 266 |
"""Async update the known device state from all properties and call _do_update to add the properties to the object property dictionary""" |
| 267 |
full_update = property_list is None |
| 268 |
if full_update: |
| 269 |
params = None |
| 270 |
else: |
| 271 |
params = {'names[]': property_list} |
| 272 |
|
| 273 |
async with await self.ayla_api.async_request('get', self.dsn_all_properties_endpoint, params=params) as resp: |
| 274 |
properties = await resp.json() |
| 275 |
|
| 276 |
# _do_update should not be thread blocking |
| 277 |
return self._do_update(full_update, properties) |
| 278 |
|
| 279 |
def _do_update(self, full_update: bool, properties: List[Dict]): |
| 280 |
""" |
| 281 |
Update the internal state from fetched properties. This is called within update()/async_update() |
| 282 |
Categorize properties by Access (e.g. SET-able or Read-Only). |
| 283 |
Alternatively? This could use the read_only property bool instead of 'set_'. |
| 284 |
""" |
| 285 |
property_names = {p['property']['name'] for p in properties} |
| 286 |
settable_properties = {self._clean_property_name(p) for p in property_names if p[:3].upper() == 'SET'} |
| 287 |
readable_properties = { |
| 288 |
self._clean_property_name(p['property']['name']): p['property'] |
| 289 |
for p in properties if p['property']['name'].upper() != 'SET' |
| 290 |
} |
| 291 |
|
| 292 |
if full_update or self._settable_properties is None: |
| 293 |
self._settable_properties = settable_properties |
| 294 |
else: |
| 295 |
self._settable_properties = self._settable_properties.union(settable_properties) |
| 296 |
|
| 297 |
# Update the property map so we can update by name instead of by fickle number |
| 298 |
if full_update: |
| 299 |
# Did a full update, so let's wipe everything |
| 300 |
self.properties_full = defaultdict(dict) |
| 301 |
self.properties_full.update(readable_properties) |
| 302 |
|
| 303 |
return True |
| 304 |
|
| 305 |
@staticmethod |
| 306 |
def _get_most_recent_datum(data_list: List[Dict], date_field: str = 'updated_at') -> Dict: |
| 307 |
"""Get the most recent data point from a list of annoyingly nested values""" |
| 308 |
datapoints = { |
| 309 |
_parse_datetime(d['datapoint'][date_field]): d['datapoint'] for d in data_list if 'datapoint' in d |
| 310 |
} |
| 311 |
if not datapoints: |
| 312 |
return {} |
| 313 |
latest_datum = datapoints[max(datapoints.keys())] |
| 314 |
return latest_datum |
| 315 |
|
| 316 |
def _get_file_property_endpoint(self, property_name: PropertyName) -> str: |
| 317 |
"""Check that property_name is a file property and return its lookup endpoint""" |
| 318 |
if isinstance(property_name, Enum): |
| 319 |
property_name = property_name.value |
| 320 |
|
| 321 |
property_id = self.properties_full[property_name]['key'] |
| 322 |
if self.properties_full[property_name].get('base_type') != 'file': |
| 323 |
raise ValueError(f'{property_name} is not a file property') |
| 324 |
return f'{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/properties/{property_id:d}/datapoints.json' |
| 325 |
|
| 326 |
def get_file_property_url(self, property_name: PropertyName) -> Optional[str]: |
| 327 |
"""File properties are versioned and need a special lookup""" |
| 328 |
try: |
| 329 |
url = self._get_file_property_endpoint(property_name) |
| 330 |
except KeyError: |
| 331 |
return None |
| 332 |
|
| 333 |
resp = self.ayla_api.self_request('get', url) |
| 334 |
data_list = resp.json() |
| 335 |
latest_datum = self._get_most_recent_datum(data_list) |
| 336 |
return latest_datum.get('file') |
| 337 |
|
| 338 |
async def async_get_file_property_url(self, property_name: PropertyName) -> Optional[str]: |
| 339 |
"""File properties are versioned and need a special lookup""" |
| 340 |
try: |
| 341 |
url = self._get_file_property_endpoint(property_name) |
| 342 |
except KeyError: |
| 343 |
return None |
| 344 |
|
| 345 |
async with await self.ayla_api.async_request('get', url) as resp: |
| 346 |
data_list = await resp.json() |
| 347 |
latest_datum = self._get_most_recent_datum(data_list) |
| 348 |
return latest_datum.get('file') |
| 349 |
|
| 350 |
def get_file_property(self, property_name: PropertyName) -> bytes: |
| 351 |
"""Get the latest file for a file property and return as bytes""" |
| 352 |
# These do not require authentication, so we won't use the ayla_api |
| 353 |
url = self.get_file_property_url(property_name) |
| 354 |
resp = get(url) |
| 355 |
return resp.content |
| 356 |
|
| 357 |
async def async_get_file_property(self, property_name: PropertyName) -> bytes: |
| 358 |
"""Get the latest file for a file property and return as bytes""" |
| 359 |
url = await self.async_get_file_property_url(property_name) |
| 360 |
session = self.ayla_api.websession |
| 361 |
async with session.get(url) as resp: |
| 362 |
return await resp.read() |
| 363 |
|
| 364 |
def get_property_triggers(self, property_name: PropertyName): |
| 365 |
"""For a properties triggers, get them and add them to the device""" |
| 366 |
resp = self.ayla_api.self_request('get', self.property_triggers_endpoint(property_name)) |
| 367 |
triggers = resp.json() |
| 368 |
#[{trigger:{key}}] |
| 369 |
for trigger in triggers: |
| 370 |
if trigger["trigger"]["key"] not in self.triggers.keys(): |
| 371 |
self.triggers[trigger["trigger"]["key"]] = trigger["trigger"] |
| 372 |
|
| 373 |
async def async_get_property_triggers(self, property_name: PropertyName): |
| 374 |
"""For a properties triggers, get them and add them to the device""" |
| 375 |
resp = await self.ayla_api.async_request('get', self.property_triggers_endpoint(property_name)) |
| 376 |
triggers = await resp.json() |
| 377 |
#[{trigger:{key}}] |
| 378 |
for trigger in triggers: |
| 379 |
if trigger["trigger"]["key"] not in self.triggers.keys(): |
| 380 |
self.triggers[trigger["trigger"]["key"]] = trigger["trigger"] |
| 381 |
|
| 382 |
class Vacuum(Device): |
| 383 |
""" Extend device into a vacuum specific device """ |
| 384 |
def __init__(self, ayla_api: "AylaApi", device_dct: Dict, europe: bool = False): |
| 385 |
super().__init__(ayla_api, device_dct, europe) |
| 386 |
self._update_metadata() # update metadata needed for sharkIQ |
| 387 |
|
| 388 |
def _encode_room_list(self, rooms: List[str]): |
| 389 |
"""Base64 encode the list of rooms to clean""" |
| 390 |
if not rooms: |
| 391 |
# By default, clean all rooms |
| 392 |
return '*' |
| 393 |
|
| 394 |
room_list = self._get_device_room_list() |
| 395 |
_LOGGER.debug(f'Room list identifier is: {room_list["identifier"]}') |
| 396 |
|
| 397 |
# Header explained: |
| 398 |
# 0x80: Control character - some mode selection |
| 399 |
# 0x01: Start of Heading Character |
| 400 |
# 0x0B: Use Line Tabulation (entries separated by newlines) |
| 401 |
# 0xca: Control character - purpose unknown |
| 402 |
# 0x02: Start of text (indicates start of room list) |
| 403 |
header = '\x80\x01\x0b\xca\x02' |
| 404 |
|
| 405 |
# For each room in the list: |
| 406 |
# - Insert a byte representing the length of the room name string |
| 407 |
# - Add the room name |
| 408 |
# - Join with newlines (presumably because of the 0x0B in the header) |
| 409 |
rooms_enc = "\n".join([chr(len(room)) + room for room in rooms]) |
| 410 |
|
| 411 |
# The footer starts with control character 0x1A |
| 412 |
# Then add the length indicator for the room list identifier |
| 413 |
# Then add the room list identifier |
| 414 |
footer = '\x1a' + chr(len(room_list['identifier'])) + room_list['identifier'] |
| 415 |
|
| 416 |
# Now that we've computed the room list and footer and know their lengths, finish building the header |
| 417 |
# This character denotes the length of the remaining input |
| 418 |
header += chr(0 |
| 419 |
+ 1 # Add one for a newline following the length specifier |
| 420 |
+ len(rooms_enc) |
| 421 |
+ len(footer) |
| 422 |
) |
| 423 |
header += '\n' # This is the newline reference above |
| 424 |
|
| 425 |
# Finally, join and base64 encode the parts |
| 426 |
return b64encode( |
| 427 |
# First encode the string as latin_1 to get the right endianness |
| 428 |
(header + rooms_enc + footer).encode('latin_1') |
| 429 |
# Then return as a utf8 string for ease of handling |
| 430 |
).decode('utf8') |
| 431 |
|
| 432 |
def _get_device_room_list(self): |
| 433 |
"""Gets the list of known rooms from the device, including the map identifier""" |
| 434 |
room_list = self.get_property_value(VacuumProperties.ROBOT_ROOM_LIST) |
| 435 |
split = room_list.split(':') |
| 436 |
return { |
| 437 |
# The room list is preceded by an identifier, which I believe identifies the list of rooms with the |
| 438 |
# onboard map in the robot |
| 439 |
'identifier': split[0], |
| 440 |
'rooms': split[1:], |
| 441 |
} |
| 442 |
|
| 443 |
def get_room_list(self) -> List[str]: |
| 444 |
"""Gets the list of rooms known by the device""" |
| 445 |
return self._get_device_room_list()['rooms'] |
| 446 |
|
| 447 |
def clean_rooms(self, rooms: List[str]) -> None: |
| 448 |
payload = self._encode_room_list(rooms) |
| 449 |
_LOGGER.debug('Room list payload: ' + payload) |
| 450 |
self.set_property_value(VacuumProperties.AREAS_TO_CLEAN, payload) |
| 451 |
self.set_vacuum_operating_mode(VacuumOperatingModes.START) |
| 452 |
|
| 453 |
async def async_clean_rooms(self, rooms: List[str]) -> None: |
| 454 |
payload = self._encode_room_list(rooms) |
| 455 |
_LOGGER.debug("Room list payload: " + payload) |
| 456 |
await self.async_set_property_value(VacuumProperties.AREAS_TO_CLEAN, payload) |
| 457 |
await self.async_set_vacuum_operating_mode(VacuumOperatingModes.START) |
| 458 |
|
| 459 |
def set_vacuum_operating_mode(self, mode: VacuumOperatingModes): |
| 460 |
"""Set the vacuum operating mode. This is just a convenience wrapper around `set_property_value`""" |
| 461 |
self.set_property_value(VacuumProperties.OPERATING_MODE, mode) |
| 462 |
|
| 463 |
async def async_set_vacuum_operating_mode(self, mode: VacuumOperatingModes): |
| 464 |
"""Set the vacuum operating mode. This is just a convenience wrapper around `set_property_value`""" |
| 465 |
await self.async_set_property_value(VacuumProperties.OPERATING_MODE, mode) |
| 466 |
|
| 467 |
def find_device(self): |
| 468 |
"""Make the device emit an annoying chirp so you can find it""" |
| 469 |
self.set_property_value(VacuumProperties.FIND_DEVICE, 1) |
| 470 |
|
| 471 |
async def async_find_device(self): |
| 472 |
"""Make the device emit an annoying chirp so you can find it""" |
| 473 |
await self.async_set_property_value(VacuumProperties.FIND_DEVICE, 1) |
| 474 |
|
| 475 |
@property |
| 476 |
def error_code(self) -> Optional[int]: |
| 477 |
"""Error code""" |
| 478 |
return self.get_property_value(VacuumProperties.ERROR_CODE) |
| 479 |
|
| 480 |
@property |
| 481 |
def error_text(self) -> Optional[str]: |
| 482 |
"""Error message""" |
| 483 |
err = self.error_code |
| 484 |
if err: |
| 485 |
return VACUUM_ERROR_MESSAGES.get(err, f'Unknown error ({err})') |
| 486 |
return None |
| 487 |
|
| 488 |
class Softener(Device): |
| 489 |
""" Extend device into a water softener specific device """ |
| 490 |
|
| 491 |
def __init__(self, ayla_api: "AylaApi", device_dct: Dict, europe: bool = False): |
| 492 |
super().__init__(ayla_api, device_dct, europe) |
| 493 |
|
| 494 |
self.alternate_mapping = { |
| 495 |
"aqua_sensor_Zmin" : "aqua_sensor_Zmin_1", |
| 496 |
"aqua_sensor_Zratio_current": "aqua_sensor_Zratio_curr_1", |
| 497 |
"BD_rinse" : "bd_rinse", |
| 498 |
"capacity_remaining_gallons": "capacity_remaining_volume_1", |
| 499 |
"days_since_last_regen" : "days_since_last_regen_1", |
| 500 |
"error_flags" : "system_error_flags", |
| 501 |
"flow_profiles_max_flow" : "flow_profiles_max_flow_lim", |
| 502 |
"flow_profiles_min_flow" : "flow_profiles_min_flow_lim", |
| 503 |
"gbe_fw_version" : "gbx_fw_version", |
| 504 |
"hardness_in_grains_per_gal": "hardness_value", |
| 505 |
"iron_setting" : "iron", |
| 506 |
"last_regen_date_time" : "last_regen_date_time_1", |
| 507 |
"next_regen_on_date" : "next_regen_date_time", |
| 508 |
"regen_interval_days_setting":"regen_interval_days", |
| 509 |
"salt_dosage_in_lbs" : "salt_dosage", |
| 510 |
"sbt_salt_level_low" : "low_salt_level", |
| 511 |
"set_vacation_mode" : "set_away_mode", |
| 512 |
"vacation_mode" : "away_mode", # instead of ensuring it works with 'clean properties', just add this key in addition |
| 513 |
"total_gallons_since_install":"water_usage_since_install_1", |
| 514 |
"total_gallons_today" : "total_water_usage_today_1", |
| 515 |
"unit_status" : "unit_status_1", |
| 516 |
"valve_position" : "valve_position_1" |
| 517 |
} |
| 518 |
|
| 519 |
# # init should call update() and properties should be available |
| 520 |
# self.avg_daily_usage = self.get_property_value("avg_daily_usage") |
| 521 |
# self.current_flow_rate = self.get_property_value("current_flow_rate") |
| 522 |
# self.capacity_remaining_gallons = self.get_property_value("capacity_remaining_gallons") |
| 523 |
# self.hardness_in_grains_per_gal = self.get_property_value("hardness_in_grains_per_gal") |
| 524 |
# self.days_since_last_regen = self.get_property_value("days_since_last_regen") |
| 525 |
# self.last_regen_date_time = self.get_property_value("last_regen_date_time") |
| 526 |
# self.away_mode_water_use = self.get_property_value("away_mode_water_use") |
| 527 |
# self.valve_position = self.get_property_value("valve_position") |
| 528 |
# self.total_gallons_today = self.get_property_value("total_gallons_today") |
| 529 |
# self.error_flags = self.get_property_value("error_flags") |
| 530 |
# self.total_gallons_since_install= self.get_property_value("total_gallons_since_install") |
| 531 |
# self.total_regens_since_install = self.get_property_value("total_regens_since_install") |
| 532 |
self.avg_daily_properties = ["avg_sun","avg_mon","avg_tue","avg_wed","avg_thr","avg_fri","avg_sat"] |
| 533 |
self.daily_usage_properties = ["daily_usage_day_1", "daily_usage_day_2", "daily_usage_day_3", "daily_usage_day_4", "daily_usage_day_5", "daily_usage_day_6", "daily_usage_day_7"] |
| 534 |
self.hourly_usage_properties = ["hourly_usage_hour_1", "hourly_usage_hour_2", "hourly_usage_hour_3", "hourly_usage_hour_4", "hourly_usage_hour_5", "hourly_usage_hour_6", "hourly_usage_hour_7", "hourly_usage_hour_8", "hourly_usage_hour_9", "hourly_usage_hour_10", "hourly_usage_hour_11", "hourly_usage_hour_12", "hourly_usage_hour_13", "hourly_usage_hour_14", "hourly_usage_hour_15", "hourly_usage_hour_16", "hourly_usage_hour_17", "hourly_usage_hour_18", "hourly_usage_hour_19", "hourly_usage_hour_20", "hourly_usage_hour_21", "hourly_usage_hour_22", "hourly_usage_hour_23", "hourly_usage_hour_24"] |
| 535 |
|
| 536 |
@property |
| 537 |
def datapoints_endpoint(self) -> str: |
| 538 |
"Provide the datapoints endpoint, used for polling, property updates, and more" |
| 539 |
return f'{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/batch_datapoints.json' |
| 540 |
|
| 541 |
def set_datapoint_payload(self, property, value) -> Dict: |
| 542 |
"""Create a batch_datapoint update payload""" |
| 543 |
return { |
| 544 |
"batch_datapoints": [ |
| 545 |
{ |
| 546 |
"datapoint": { |
| 547 |
"value": value |
| 548 |
}, |
| 549 |
"dsn": self._device_serial_number, |
| 550 |
"name": property |
| 551 |
} |
| 552 |
] |
| 553 |
} |
| 554 |
|
| 555 |
def get_property_value(self, property_name: PropertyName) -> Any: |
| 556 |
"""Get the value of a property from the properties dictionary""" |
| 557 |
if isinstance(property_name, Enum): |
| 558 |
property_name = property_name.value |
| 559 |
|
| 560 |
if property_name in self.properties_full.keys(): |
| 561 |
return self.property_values[property_name] |
| 562 |
elif self.alternate_mapping: |
| 563 |
if self.alternate_mapping[property_name] in self.properties_full.keys(): |
| 564 |
return self.property_values[self.alternate_mapping[property_name]] |
| 565 |
else: |
| 566 |
return False |
| 567 |
|
| 568 |
def set_property_value(self, property_name: PropertyName, value: PropertyValue): |
| 569 |
"""Update a property, overload from device""" |
| 570 |
if isinstance(property_name, Enum): |
| 571 |
property_name = property_name.value |
| 572 |
if isinstance(value, Enum): |
| 573 |
value = value.value |
| 574 |
|
| 575 |
if self.properties_full.get(property_name, {}).get('read_only'): |
| 576 |
raise AylaReadOnlyPropertyError(f'{property_name} is read only') |
| 577 |
else: |
| 578 |
""" Get the name of the property. Case sizing for 'SET' varies """ |
| 579 |
property_name = self.properties_full.get(property_name).get("name") |
| 580 |
|
| 581 |
resp = self.ayla_api.self_request('post', self.datapoints_endpoint, json=self.set_datapoint_payload(property_name, value)) |
| 582 |
# datapoint is created, but the value is not returned ... |
| 583 |
self.update() |
| 584 |
|
| 585 |
async def async_set_property_value(self, property_name: PropertyName, value: PropertyValue): |
| 586 |
"""Update a property async, overload from device""" |
| 587 |
if isinstance(property_name, Enum): |
| 588 |
property_name = property_name.value |
| 589 |
if isinstance(value, Enum): |
| 590 |
value = value.value |
| 591 |
|
| 592 |
if self.properties_full.get(property_name, {}).get('read_only'): |
| 593 |
raise AylaReadOnlyPropertyError(f'{property_name} is read only') |
| 594 |
else: |
| 595 |
""" Get the name of the property. Case sizing for 'SET' varies """ |
| 596 |
property_name = self.properties_full.get(property_name).get("name") |
| 597 |
|
| 598 |
async with await self.ayla_api.async_request('post', self.datapoints_endpoint, json=self.set_datapoint_payload(property_name, value)) as resp: |
| 599 |
resp_data = await resp.json() |
| 600 |
await self.async_update() |
| 601 |
|
| 602 |
def send_poll(self): |
| 603 |
"""Send a wifi_report to trigger updated properties, this requires an ayla api token""" |
| 604 |
|
| 605 |
resp = self.ayla_api.self_request('post', self.datapoints_endpoint, json=self.set_datapoint_payload("wifi_report", 1)) |
| 606 |
if(resp.json()): |
| 607 |
return True |
| 608 |
else: |
| 609 |
return False |
| 610 |
|
| 611 |
async def async_send_poll(self): |
| 612 |
"""Send a wifi_report to trigger updated properties, this requires an ayla api token""" |
| 613 |
|
| 614 |
datapoints = f'{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/batch_datapoints.json' |
| 615 |
|
| 616 |
async with await self.ayla_api.async_request('post', datapoints, json=self.set_datapoint_payload("wifi_report", 1)) as resp: |
| 617 |
json = await resp.json() |
| 618 |
|
| 619 |
if(json): |
| 620 |
return True |
| 621 |
else: |
| 622 |
return False |
| 623 |
|
| 624 |
def set_avg_daily_properties_list(self, newList): |
| 625 |
"""The default avg_daily_properties are from Culligan data. Allow them to be changed.""" |
| 626 |
self.avg_daily_properties = newList |
| 627 |
|
| 628 |
def set_daily_usage_properties_list(self, newList): |
| 629 |
"""The default daily_usage_properties are from Culligan data. Allow them to be changed.""" |
| 630 |
self.daily_usage_properties = newList |
| 631 |
|
| 632 |
def set_hourly_usage_properties_list(self, newList): |
| 633 |
"""The default hourly_usage_properties are from Culligan data. Allow them to be changed.""" |
| 634 |
self.hourly_usage_properties = newList |
| 635 |
|
| 636 |
def get_average_daily_usage(self): |
| 637 |
"""Convenience wrapper around `get_property_value`""" |
| 638 |
return self.avg_daily_usage |
| 639 |
|
| 640 |
async def async_get_average_daily_usage(self): |
| 641 |
"""Convenience wrapper around `get_property_value`""" |
| 642 |
return self.avg_daily_usage |
| 643 |
|
| 644 |
def get_current_flow_rate(self): |
| 645 |
"""Convenience wrapper around `get_property_value`""" |
| 646 |
return self.current_flow_rate |
| 647 |
|
| 648 |
async def async_get_current_flow_rate(self): |
| 649 |
"""Convenience wrapper around `get_property_value`""" |
| 650 |
return self.current_flow_rate |
| 651 |
|
| 652 |
def get_capacity_remaining_gallons(self): |
| 653 |
"""Convenience wrapper around `get_property_value`""" |
| 654 |
return self.capacity_remaining_gallons |
| 655 |
|
| 656 |
async def async_get_capacity_remaining_gallons(self): |
| 657 |
"""Convenience wrapper around `get_property_value`""" |
| 658 |
return self.capacity_remaining_gallons |
| 659 |
|
| 660 |
def get_hardness_in_grains_per_gal(self): |
| 661 |
"""Convenience wrapper around `get_property_value`""" |
| 662 |
return self.hardness_in_grains_per_gal |
| 663 |
|
| 664 |
async def async_get_hardness_in_grains_per_gal(self): |
| 665 |
"""Convenience wrapper around `get_property_value`""" |
| 666 |
return self.hardness_in_grains_per_gal |
| 667 |
|
| 668 |
def get_days_since_last_regen(self): |
| 669 |
"""Convenience wrapper around `get_property_value`""" |
| 670 |
return self.days_since_last_regen |
| 671 |
|
| 672 |
async def async_get_days_since_last_regen(self): |
| 673 |
"""Convenience wrapper around `get_property_value`""" |
| 674 |
return self.days_since_last_regen |
| 675 |
|
| 676 |
def get_last_regen_date_time(self): |
| 677 |
"""Convenience wrapper around `get_property_value`""" |
| 678 |
return self.last_regen_date_time |
| 679 |
|
| 680 |
async def async_get_last_regen_date_time(self): |
| 681 |
"""Convenience wrapper around `get_property_value`""" |
| 682 |
return self.last_regen_date_time |
| 683 |
|
| 684 |
def get_away_mode_water_use(self): |
| 685 |
"""Convenience wrapper around `get_property_value`""" |
| 686 |
return self.away_mode_water_use |
| 687 |
|
| 688 |
async def async_get_away_mode_water_use(self): |
| 689 |
"""Convenience wrapper around `get_property_value`""" |
| 690 |
return self.away_mode_water_use |
| 691 |
|
| 692 |
def get_valve_position(self): |
| 693 |
"""Convenience wrapper around `get_property_value`""" |
| 694 |
return self.valve_position |
| 695 |
|
| 696 |
async def async_get_valve_position(self): |
| 697 |
"""Convenience wrapper around `get_property_value`""" |
| 698 |
return self.valve_position |
| 699 |
|
| 700 |
def get_total_gallons_today(self): |
| 701 |
"""Convenience wrapper around `get_property_value`""" |
| 702 |
return self.total_gallons_today |
| 703 |
|
| 704 |
async def async_get_total_gallons_today(self): |
| 705 |
"""Convenience wrapper around `get_property_value`""" |
| 706 |
return self.total_gallons_today |
| 707 |
|
| 708 |
def get_error_flags(self): |
| 709 |
"""Convenience wrapper around `get_property_value`""" |
| 710 |
return self.error_flags |
| 711 |
|
| 712 |
async def async_get_error_flags(self): |
| 713 |
"""Convenience wrapper around `get_property_value`""" |
| 714 |
return self.error_flags |
| 715 |
|
| 716 |
def get_total_gallons_since_install(self): |
| 717 |
"""Convenience wrapper around `get_property_value`""" |
| 718 |
return self.total_gallons_since_install |
| 719 |
|
| 720 |
async def async_get_total_gallons_since_install(self): |
| 721 |
"""Convenience wrapper around `get_property_value`""" |
| 722 |
return self.total_gallons_since_install |
| 723 |
|
| 724 |
def get_total_regens_since_install(self): |
| 725 |
"""Convenience wrapper around `get_property_value`""" |
| 726 |
return self.total_regens_since_install |
| 727 |
|
| 728 |
async def async_get_total_regens_since_install(self): |
| 729 |
"""Convenience wrapper around `get_property_value`""" |
| 730 |
return self.total_regens_since_install |
| 731 |
|
| 732 |
def start_vacation_mode(self): |
| 733 |
""" |
| 734 |
Needs testing. Set vacation mode value from 0 (default) to 255 (max). |
| 735 |
Properties and values may vary per manufacturer. |
| 736 |
""" |
| 737 |
if "vacation_mode" in self.properties_full.keys(): |
| 738 |
PropertyName = "vacation_mode" # because _clean property, 'set' is removed ... "set_vacation_mode" |
| 739 |
elif "away_mode" in self.properties_full.keys(): |
| 740 |
PropertyName = "away_mode" # because _clean property, 'set' is removed ... "set_away_mode" |
| 741 |
PropertyValue = 1 |
| 742 |
self.set_property_value(PropertyName, PropertyValue) |
| 743 |
return True |
| 744 |
|
| 745 |
async def async_start_vacation_mode(self): |
| 746 |
""" |
| 747 |
Needs testing. Set vacation mode value from 0 (default) to 255 (max). |
| 748 |
Properties and values may vary per manufacturer. |
| 749 |
""" |
| 750 |
if "vacation_mode" in self.properties_full.keys(): |
| 751 |
PropertyName = "vacation_mode" # because _clean property, 'set' is removed ... "set_vacation_mode" |
| 752 |
elif "away_mode" in self.properties_full.keys(): |
| 753 |
PropertyName = "away_mode" # because _clean property, 'set' is removed ... "set_away_mode" |
| 754 |
PropertyValue = 1 |
| 755 |
await self.async_set_property_value(PropertyName, PropertyValue) |
| 756 |
return True |
| 757 |
|
| 758 |
def stop_vacation_mode(self): |
| 759 |
""" |
| 760 |
Needs testing. Set vacation mode value from 255 (max) to 0 (default). |
| 761 |
Properties and values may vary per manufacturer. |
| 762 |
""" |
| 763 |
if "vacation_mode" in self.properties_full.keys(): |
| 764 |
PropertyName = "vacation_mode" # because _clean property, 'set' is removed ... "set_vacation_mode" |
| 765 |
elif "away_mode" in self.properties_full.keys(): |
| 766 |
PropertyName = "away_mode" # because _clean property, 'set' is removed ... "set_away_mode" |
| 767 |
PropertyValue = 0 |
| 768 |
self.set_property_value(PropertyName, PropertyValue) |
| 769 |
return True |
| 770 |
|
| 771 |
async def async_stop_vacation_mode(self): |
| 772 |
""" |
| 773 |
Needs testing. Set vacation mode value from 255 (max) to 0 (default). |
| 774 |
Properties and values may vary per manufacturer. |
| 775 |
""" |
| 776 |
if "vacation_mode" in self.properties_full.keys(): |
| 777 |
PropertyName = "vacation_mode" # because _clean property, 'set' is removed ... "set_vacation_mode" |
| 778 |
elif "away_mode" in self.properties_full.keys(): |
| 779 |
PropertyName = "away_mode" # because _clean property, 'set' is removed ... "set_away_mode" |
| 780 |
PropertyValue = 0 |
| 781 |
await self.async_set_property_value(PropertyName, PropertyValue) |
| 782 |
return True |
| 783 |
|
| 784 |
def start_bypass_mode(self): |
| 785 |
"""Start indefinite bypass""" |
| 786 |
return self.start_bypass_timed_mode(6) |
| 787 |
|
| 788 |
async def async_start_bypass_mode(self): |
| 789 |
"""Start indefinite bypass""" |
| 790 |
return await self.async_start_bypass_timed_mode(6) |
| 791 |
|
| 792 |
def start_bypass_timed_mode(self, presetTimeCode = 1): |
| 793 |
""" |
| 794 |
Needs testing. Set standard_bypass value from 0 (default) to 255 (max). |
| 795 |
Properties and values may vary per manufacturer. |
| 796 |
1 = 30m |
| 797 |
2 = 60m |
| 798 |
3 = 90m |
| 799 |
4 = 120m |
| 800 |
5 = 180m |
| 801 |
6 = indefinite |
| 802 |
""" |
| 803 |
if "standard_bypass" in self.properties_full.keys(): |
| 804 |
PropertyName = "standard_bypass" # because _clean property, 'set' is removed ... "set_standard_bypass" |
| 805 |
PropertyValue = presetTimeCode |
| 806 |
self.set_property_value(PropertyName, PropertyValue) |
| 807 |
return True |
| 808 |
else: |
| 809 |
return False |
| 810 |
|
| 811 |
async def async_start_bypass_timed_mode(self, presetTimeCode = 1): |
| 812 |
""" |
| 813 |
Needs testing. Set standard_bypass value from 0 (default) to 255 (max). |
| 814 |
Properties and values may vary per manufacturer. |
| 815 |
1 = 30m |
| 816 |
2 = 60m |
| 817 |
3 = 90m |
| 818 |
4 = 120m |
| 819 |
5 = 180m |
| 820 |
6 = indefinite |
| 821 |
""" |
| 822 |
if "standard_bypass" in self.properties_full.keys(): |
| 823 |
PropertyName = "standard_bypass" # because _clean property, 'set' is removed ... "set_standard_bypass" |
| 824 |
PropertyValue = presetTimeCode |
| 825 |
await self.async_set_property_value(PropertyName, PropertyValue) |
| 826 |
return True |
| 827 |
else: |
| 828 |
return False |
| 829 |
|
| 830 |
def stop_bypass_mode(self): |
| 831 |
""" |
| 832 |
Needs testing. Set standard_bypass value to off (0). Value will return automatically to 255. |
| 833 |
Properties and values may vary per manufacturer. |
| 834 |
""" |
| 835 |
if "standard_bypass" in self.properties_full.keys(): |
| 836 |
PropertyName = "standard_bypass" # because _clean property, 'set' is removed ... "set_standard_bypass" |
| 837 |
PropertyValue = 255 |
| 838 |
self.set_property_value(PropertyName, PropertyValue) |
| 839 |
return True |
| 840 |
else: |
| 841 |
return False |
| 842 |
|
| 843 |
async def async_stop_bypass_mode(self): |
| 844 |
""" |
| 845 |
Needs testing. Set standard_bypass value to off (0). Value will return automatically to 255. |
| 846 |
Properties and values may vary per manufacturer. |
| 847 |
""" |
| 848 |
if "standard_bypass" in self.properties_full.keys(): |
| 849 |
PropertyName = "standard_bypass" # because _clean property, 'set' is removed ... "set_standard_bypass" |
| 850 |
PropertyValue = 0 |
| 851 |
await self.async_set_property_value(PropertyName, PropertyValue) |
| 852 |
return True |
| 853 |
else: |
| 854 |
return False |
| 855 |
|
| 856 |
class DevicePropertiesView(abc.Mapping): |
| 857 |
"""Convenience API for device properties""" |
| 858 |
|
| 859 |
@staticmethod |
| 860 |
def _cast_value(value, value_type): |
| 861 |
"""Cast property value to the appropriate type.""" |
| 862 |
if value is None: |
| 863 |
return None |
| 864 |
type_map = { |
| 865 |
'boolean': bool, |
| 866 |
'decimal': float, |
| 867 |
'integer': int, |
| 868 |
'string': str, |
| 869 |
} |
| 870 |
return type_map.get(value_type, lambda x: x)(value) |
| 871 |
|
| 872 |
def __init__(self, device: Device): |
| 873 |
self._device = device |
| 874 |
|
| 875 |
def __getitem__(self, key): |
| 876 |
value = self._device.properties_full[key].get('value') |
| 877 |
value_type = self._device.properties_full[key].get('base_type') |
| 878 |
try: |
| 879 |
return self._cast_value(value, value_type) |
| 880 |
except (TypeError, ValueError) as exc: |
| 881 |
# If we failed to convert the type, just return the raw value |
| 882 |
_LOGGER.warning('Error converting property type (value: %r, type: %r)', value, value_type, exc_info=exc) |
| 883 |
return value |
| 884 |
|
| 885 |
def __iter__(self): |
| 886 |
for k in self._device.properties_full.keys(): |
| 887 |
yield k |
| 888 |
|
| 889 |
def __len__(self) -> int: |
| 890 |
return self._device.properties_full.__len__() |
| 891 |
|
| 892 |
def __str__(self) -> str: |
| 893 |
return pformat(dict(self)) |