| 1 |
""" |
| 2 |
Simple implementation of the Ayla networks API |
| 3 |
|
| 4 |
Some devices use the Ayla networks IoT API integration to provide IoT functionality to the device. |
| 5 |
Documentation can be found at: |
| 6 |
- https://developer.aylanetworks.com/apibrowser/ |
| 7 |
- https://docs.aylanetworks.com/cloud-services/api-browser/ |
| 8 |
""" |
| 9 |
|
| 10 |
from aiohttp import ClientSession, ClientTimeout # async http |
| 11 |
from requests import post, request, Response # http request library |
| 12 |
from datetime import datetime, timedelta # datetime operations |
| 13 |
from typing import Dict, List, Optional # object types |
| 14 |
|
| 15 |
from .const import ( |
| 16 |
EU_USER_FIELD_BASE, |
| 17 |
EU_ADS_BASE, |
| 18 |
EU_RULESSERVICE_BASE, |
| 19 |
USER_FIELD_BASE, |
| 20 |
ADS_BASE, |
| 21 |
RULESSERVICE_BASE, |
| 22 |
DEFAULT_TIMEOUT |
| 23 |
) |
| 24 |
|
| 25 |
# Custom error handling |
| 26 |
from .exc import ( |
| 27 |
AylaError, |
| 28 |
AylaAuthError, |
| 29 |
AylaAuthExpiringError, |
| 30 |
AylaNotAuthedError, |
| 31 |
AylaReadOnlyPropertyError, |
| 32 |
) |
| 33 |
|
| 34 |
from .device import Device, Vacuum, Softener |
| 35 |
from .fujitsu_hvac import FujitsuHVAC |
| 36 |
|
| 37 |
_session = None |
| 38 |
|
| 39 |
def new_ayla_api(username: str, password: str, app_id: str, app_secret: str, websession: Optional[ClientSession] = None, europe: bool = False, timeout=DEFAULT_TIMEOUT): |
| 40 |
"""Get an AylaApi object""" |
| 41 |
if europe: |
| 42 |
return AylaApi(username, password, app_id, app_secret, websession=websession, europe=europe, timeout=timeout) |
| 43 |
else: |
| 44 |
return AylaApi(username, password, app_id, app_secret, websession=websession, timeout=timeout) |
| 45 |
|
| 46 |
def new_ayla_api_sso(sso_token: str, app_id: str, app_secret: str, websession: Optional[ClientSession] = None, europe: bool = False, timeout=DEFAULT_TIMEOUT): |
| 47 |
"""Get an AylaApi object""" |
| 48 |
return AylaApi(None, None, app_id, app_secret, websession=websession, europe=europe, timeout=timeout, sso_token=sso_token) |
| 49 |
|
| 50 |
|
| 51 |
class AylaApi: |
| 52 |
"""Simple Ayla Networks API wrapper""" |
| 53 |
|
| 54 |
def __init__( |
| 55 |
self, |
| 56 |
username: Optional[str], |
| 57 |
password: Optional[str], |
| 58 |
app_id: str, |
| 59 |
app_secret: str, |
| 60 |
websession: Optional[ClientSession] = None, |
| 61 |
europe: bool = False, |
| 62 |
timeout: int=DEFAULT_TIMEOUT, |
| 63 |
sso_token: Optional[str] = None): |
| 64 |
self._email = username # username should always be an email address |
| 65 |
self._password = password |
| 66 |
self._sso_token = sso_token |
| 67 |
self._access_token = None # type: Optional[str] |
| 68 |
self._refresh_token = None # type: Optional[str] |
| 69 |
self._auth_expiration = None # type: Optional[datetime] |
| 70 |
self._is_authed = False # type: bool |
| 71 |
self._app_id = app_id |
| 72 |
self._app_secret = app_secret |
| 73 |
self.websession = websession |
| 74 |
self.europe = europe |
| 75 |
self.eu_user_field_url = EU_USER_FIELD_BASE |
| 76 |
self.eu_ads_url = EU_ADS_BASE |
| 77 |
self.eu_rulesservice_url= EU_RULESSERVICE_BASE |
| 78 |
self.user_field_url = USER_FIELD_BASE |
| 79 |
self.ads_url = ADS_BASE |
| 80 |
self.rulesservice_url = RULESSERVICE_BASE |
| 81 |
self.timeout = timeout |
| 82 |
self._vacuum_devices = ["Vacuum","SharkIQ"] |
| 83 |
self._softener_devices = ["Softener","Smart HE","Water Softener"] |
| 84 |
|
| 85 |
async def ensure_session(self) -> ClientSession: |
| 86 |
"""Ensure that we have an aiohttp ClientSession""" |
| 87 |
if self.websession is None: |
| 88 |
self.websession = ClientSession(timeout=ClientTimeout(total=self.timeout)) |
| 89 |
return self.websession |
| 90 |
|
| 91 |
@property |
| 92 |
def _login_data(self) -> Dict[str, Dict]: |
| 93 |
"""Prettily formatted data for the login flow""" |
| 94 |
return { |
| 95 |
"user": { |
| 96 |
"email": self._email, |
| 97 |
"password": self._password, |
| 98 |
"application": {"app_id": self._app_id, "app_secret": self._app_secret}, |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
@property |
| 103 |
def _login_data_token(self) -> Dict[str, str]: |
| 104 |
"""Prettily formatted data for the login flow using token""" |
| 105 |
return { |
| 106 |
"token": self._sso_token, |
| 107 |
"app_id": self._app_id, |
| 108 |
"app_secret": self._app_secret |
| 109 |
} |
| 110 |
|
| 111 |
@property |
| 112 |
def _sign_out_data(self) -> Dict: |
| 113 |
"""Payload for the sign_out call""" |
| 114 |
return {"user": {"access_token": self._access_token}} |
| 115 |
|
| 116 |
def _set_credentials(self, status_code: int, login_result: Dict): |
| 117 |
"""Update the internal credentials store. This tracks current bearer token and data needed for token refresh.""" |
| 118 |
if status_code in [422, 404, 401]: |
| 119 |
# 422 status with `errors` property in body if SSO token is invalid |
| 120 |
if "errors" in login_result: |
| 121 |
msg = login_result["errors"] |
| 122 |
elif "message" in login_result["error"]: |
| 123 |
msg = login_result["error"]["message"] |
| 124 |
else: |
| 125 |
msg = login_result["error"] |
| 126 |
|
| 127 |
if status_code == 404: |
| 128 |
msg += " (Confirm app_id and app_secret are correct)" |
| 129 |
|
| 130 |
raise AylaAuthError(msg) |
| 131 |
|
| 132 |
self._access_token = login_result["access_token"] |
| 133 |
self._refresh_token = login_result["refresh_token"] |
| 134 |
self._auth_expiration = datetime.now() + timedelta(seconds=login_result["expires_in"]) |
| 135 |
|
| 136 |
if status_code != 200: |
| 137 |
self._is_authed = False |
| 138 |
else: |
| 139 |
self._is_authed = True |
| 140 |
|
| 141 |
def sign_in(self): |
| 142 |
"""Authenticate to Ayla API synchronously using a POST with credentials.""" |
| 143 |
login_data = self._login_data # get a map for JSON formatting |
| 144 |
resp = post(f"{self.eu_user_field_url if self.europe else self.user_field_url:s}/users/sign_in.json", json=login_data) |
| 145 |
self._set_credentials(resp.status_code, resp.json()) |
| 146 |
|
| 147 |
def sso_sign_in(self): |
| 148 |
"""Authenticate to Ayla API synchronously using an SSO token.""" |
| 149 |
endpoint = f"{self.eu_user_field_url if self.europe else self.user_field_url}/api/v1/token_sign_in" |
| 150 |
resp = post(endpoint, data=self._login_data_token) |
| 151 |
self._set_credentials(resp.status_code, resp.json()) |
| 152 |
|
| 153 |
def refresh_auth(self): |
| 154 |
"""Refresh the authentication synchronously using object tracked refresh token.""" |
| 155 |
refresh_data = {"user": {"refresh_token": self._refresh_token}} |
| 156 |
resp = post(f"{self.eu_user_field_url if self.europe else self.user_field_url:s}/users/refresh_token.json", json=refresh_data) |
| 157 |
self._set_credentials(resp.status_code, resp.json()) |
| 158 |
|
| 159 |
async def async_sign_in(self): |
| 160 |
"""Authenticate to Ayla API asynchronously using a POST with credentials..""" |
| 161 |
session = await self.ensure_session() |
| 162 |
login_data = self._login_data |
| 163 |
async with session.post(f"{self.eu_user_field_url if self.europe else self.user_field_url:s}/users/sign_in.json", json=login_data) as resp: |
| 164 |
self._set_credentials(resp.status, await resp.json()) |
| 165 |
|
| 166 |
async def async_sso_sign_in(self): |
| 167 |
"""Authenticate to Ayla API asynchronously using an SSO token.""" |
| 168 |
session = await self.ensure_session() |
| 169 |
endpoint = f"{self.eu_user_field_url if self.europe else self.user_field_url}/api/v1/token_sign_in" |
| 170 |
async with session.post(endpoint, data=self._login_data_token) as resp: |
| 171 |
self._set_credentials(resp.status, await resp.json()) |
| 172 |
|
| 173 |
async def async_refresh_auth(self): |
| 174 |
"""Refresh the authentication asynchronously using object tracked refresh token..""" |
| 175 |
session = await self.ensure_session() |
| 176 |
refresh_data = {"user": {"refresh_token": self._refresh_token}} |
| 177 |
async with session.post(f"{self.eu_user_field_url if self.europe else self.user_field_url:s}/users/refresh_token.json", json=refresh_data) as resp: |
| 178 |
self._set_credentials(resp.status, await resp.json()) |
| 179 |
|
| 180 |
def _clear_auth(self): |
| 181 |
"""Clear authentication state""" |
| 182 |
self._is_authed = False |
| 183 |
self._access_token = None |
| 184 |
self._refresh_token = None |
| 185 |
self._auth_expiration = None |
| 186 |
|
| 187 |
def sign_out(self): |
| 188 |
"""Sign out and invalidate the access token synchronously""" |
| 189 |
post(f"{self.eu_user_field_url if self.europe else self.user_field_url:s}/users/sign_out.json", json=self._sign_out_data) |
| 190 |
self._clear_auth() |
| 191 |
|
| 192 |
async def async_sign_out(self): |
| 193 |
"""Sign out and invalidate the access token asynchronously""" |
| 194 |
session = await self.ensure_session() |
| 195 |
async with session.post(f"{self.eu_user_field_url if self.europe else self.user_field_url:s}/users/sign_out.json", json=self._sign_out_data) as _: |
| 196 |
pass |
| 197 |
self._clear_auth() |
| 198 |
|
| 199 |
@property |
| 200 |
def auth_expiration(self) -> Optional[datetime]: |
| 201 |
"""When does the auth expire""" |
| 202 |
if not self._is_authed: |
| 203 |
return None |
| 204 |
elif self._auth_expiration is None: # This should not happen, but let's be ready if it does... |
| 205 |
raise AylaNotAuthedError("Invalid state. Please reauthorize.") |
| 206 |
else: |
| 207 |
return self._auth_expiration |
| 208 |
|
| 209 |
@property |
| 210 |
def token_expired(self) -> bool: |
| 211 |
"""Return true if the token has already expired""" |
| 212 |
if self.auth_expiration is None: |
| 213 |
return True |
| 214 |
return datetime.now() > self.auth_expiration |
| 215 |
|
| 216 |
@property |
| 217 |
def token_expiring_soon(self) -> bool: |
| 218 |
"""Return true if the token will expire soon""" |
| 219 |
if self.auth_expiration is None: |
| 220 |
return True |
| 221 |
return datetime.now() > self.auth_expiration - timedelta(seconds=600) # Prevent timeout immediately following |
| 222 |
|
| 223 |
def check_auth(self, raise_expiring_soon=True): |
| 224 |
"""Confirm authentication status""" |
| 225 |
if not self._access_token or not self._is_authed or self.token_expired: |
| 226 |
self._is_authed = False |
| 227 |
raise AylaNotAuthedError() |
| 228 |
elif raise_expiring_soon and self.token_expiring_soon: |
| 229 |
raise AylaAuthExpiringError() |
| 230 |
|
| 231 |
@property |
| 232 |
def auth_header(self) -> Dict[str, str]: |
| 233 |
self.check_auth() |
| 234 |
return {"Authorization": f"auth_token {self._access_token:s}"} |
| 235 |
|
| 236 |
def _get_headers(self, fn_kwargs) -> Dict[str, str]: |
| 237 |
""" |
| 238 |
Extract the headers element from fn_kwargs, removing it if it exists |
| 239 |
and updating with self.auth_header. |
| 240 |
""" |
| 241 |
try: |
| 242 |
headers = fn_kwargs['headers'] |
| 243 |
except KeyError: |
| 244 |
headers = {} |
| 245 |
else: |
| 246 |
del fn_kwargs['headers'] |
| 247 |
headers.update(self.auth_header) |
| 248 |
return headers |
| 249 |
|
| 250 |
def self_request(self, method: str, url: str, **kwargs) -> Response: |
| 251 |
"""Perform an arbitrary request using the requests library synchronously""" |
| 252 |
headers = self._get_headers(kwargs) |
| 253 |
return request(method, url, headers=headers, timeout=self.timeout, **kwargs) |
| 254 |
|
| 255 |
async def async_request(self, http_method: str, url: str, **kwargs): |
| 256 |
"""Perform an arbitrary request using the aiohttp library asynchronously""" |
| 257 |
session = await self.ensure_session() |
| 258 |
headers = self._get_headers(kwargs) |
| 259 |
return session.request(http_method, url, headers=headers, **kwargs) |
| 260 |
|
| 261 |
def get_user_profile(self) -> Dict[str, str]: |
| 262 |
"""Get user profile synchronously""" |
| 263 |
resp = self.self_request("get", f"{self.eu_user_field_url if self.europe else self.user_field_url:s}/users/get_user_profile.json") |
| 264 |
response = resp.json() |
| 265 |
if resp.status_code == 401: |
| 266 |
raise AylaAuthError(response) |
| 267 |
return response |
| 268 |
|
| 269 |
async def async_get_user_profile(self) -> Dict[str, str]: |
| 270 |
"""Get user profile asynchronously""" |
| 271 |
async with await self.async_request("get", f"{self.eu_user_field_url if self.europe else self.user_field_url:s}/users/get_user_profile.json") as resp: |
| 272 |
response = await resp.json() |
| 273 |
if resp.status == 401: |
| 274 |
raise AylaAuthError() |
| 275 |
return response |
| 276 |
|
| 277 |
def list_devices(self) -> List[Dict]: |
| 278 |
"""List devices synchronously""" |
| 279 |
resp = self.self_request("get", f"{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/devices.json") |
| 280 |
devices = resp.json() |
| 281 |
if resp.status_code == 401: |
| 282 |
raise AylaAuthError(devices["error"]["message"]) |
| 283 |
return [d["device"] for d in devices] |
| 284 |
|
| 285 |
async def async_list_devices(self) -> List[Dict]: |
| 286 |
"""List devices asynchronously""" |
| 287 |
async with await self.async_request("get", f"{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/devices.json") as resp: |
| 288 |
devices = await resp.json() |
| 289 |
if resp.status == 401: |
| 290 |
raise AylaAuthError(devices["error"]["message"]) |
| 291 |
return [d["device"] for d in devices] |
| 292 |
|
| 293 |
def get_devices(self, update: bool = True) -> List[Device]: |
| 294 |
"""Retrieve a device object of devices. Ability to update with metadata. Synchronous.""" |
| 295 |
devices = list() |
| 296 |
for d in self.list_devices(): |
| 297 |
if d["product_name"] in self._vacuum_devices: |
| 298 |
devices.append(Vacuum (self, d, europe=self.europe)) |
| 299 |
elif d["product_name"] in self._softener_devices or "Softener" in d["product_name"]: |
| 300 |
devices.append(Softener(self, d, europe=self.europe)) |
| 301 |
elif FujitsuHVAC.supports(d): |
| 302 |
devices.append(FujitsuHVAC(self, d, europe=self.europe)) |
| 303 |
else: |
| 304 |
devices.append(Device (self, d, europe=self.europe)) |
| 305 |
# if update: |
| 306 |
# for device in devices: |
| 307 |
# device._update_metadata() # update serial number if needed |
| 308 |
# device.update() # obtain all properties |
| 309 |
return devices |
| 310 |
|
| 311 |
async def async_get_devices(self, update: bool = True) -> List[Device]: |
| 312 |
"""Retrieve a device object of devices. Ability to update with metadata. Asynchronous.""" |
| 313 |
devices = list() |
| 314 |
for d in await self.async_list_devices(): |
| 315 |
if d["product_name"] in self._vacuum_devices: |
| 316 |
devices.append(Vacuum (self, d, europe=self.europe)) |
| 317 |
elif d["product_name"] in self._softener_devices or "Softener" in d["product_name"]: |
| 318 |
devices.append(Softener(self, d, europe=self.europe)) |
| 319 |
elif FujitsuHVAC.supports(d): |
| 320 |
devices.append(FujitsuHVAC(self, d, europe=self.europe)) |
| 321 |
else: |
| 322 |
devices.append(Device (self, d, europe=self.europe)) |
| 323 |
# if update: |
| 324 |
# for device in devices: |
| 325 |
# await device._update_metadata() # update serial number if needed |
| 326 |
# await device.async_update() # obtain all properties |
| 327 |
return devices |
| 328 |
|
| 329 |
def get_actions(self) -> Dict[str, str]: |
| 330 |
"""Get actions synchronously""" |
| 331 |
resp = self.self_request("get", f"{self.eu_rulesservice_url if self.europe else self.rulesservice_url:s}/rulesservice/v1/actions.json") |
| 332 |
response = resp.json()["actions"] |
| 333 |
if resp.status_code == 401: |
| 334 |
raise AylaAuthError(response) |
| 335 |
return response |
| 336 |
|
| 337 |
async def async_get_actions(self) -> Dict[str, str]: |
| 338 |
"""Get actions asynchronously""" |
| 339 |
async with await self.async_request("get", f"{self.eu_rulesservice_url if self.europe else self.rulesservice_url:s}/rulesservice/v1/actions.json") as resp: |
| 340 |
response = await resp.json()["actions"] |
| 341 |
if resp.status == 401: |
| 342 |
raise AylaAuthError() |
| 343 |
return response |
| 344 |
|
| 345 |
def get_rules(self) -> Dict[str, str]: |
| 346 |
"""Get rules synchronously""" |
| 347 |
resp = self.self_request("get", f"{self.eu_rulesservice_url if self.europe else self.rulesservice_url:s}/rulesservice/v1/rules.json") |
| 348 |
response = resp.json()["rules"] |
| 349 |
if resp.status_code == 401: |
| 350 |
raise AylaAuthError(response) |
| 351 |
return response |
| 352 |
|
| 353 |
async def async_get_rules(self) -> Dict[str, str]: |
| 354 |
"""Get rules asynchronously""" |
| 355 |
async with await self.async_request("get", f"{self.eu_rulesservice_url if self.europe else self.rulesservice_url:s}/rulesservice/v1/rules.json") as resp: |
| 356 |
response = await resp.json()["rules"] |
| 357 |
if resp.status == 401: |
| 358 |
raise AylaAuthError() |
| 359 |
return response |
| 360 |
|
| 361 |
def get_rule_action(self, rule_uuid) -> Dict[str, str]: |
| 362 |
"""Get rules synchronously""" |
| 363 |
resp = self.self_request("get", f"{self.eu_rulesservice_url if self.europe else self.rulesservice_url:s}/rulesservice/v1/rules/{rule_uuid}/actions.json") |
| 364 |
response = resp.json()["actions"] |
| 365 |
if resp.status_code == 401: |
| 366 |
raise AylaAuthError(response) |
| 367 |
return response |
| 368 |
|
| 369 |
async def async_get_rule_action(self, rule_uuid) -> Dict[str, str]: |
| 370 |
"""Get rules asynchronously""" |
| 371 |
async with await self.async_request("get", f"{self.eu_rulesservice_url if self.europe else self.rulesservice_url:s}/rulesservice/v1/rules/{rule_uuid}/actions.json") as resp: |
| 372 |
response = await resp.json()["actions"] |
| 373 |
if resp.status == 401: |
| 374 |
raise AylaAuthError() |
| 375 |
return response |
| 376 |
|
| 377 |
def get_commands(self, device_id) -> Dict[str, str]: |
| 378 |
"""Get commands synchronously""" |
| 379 |
resp = self.self_request("get", f"{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/devices/{device_id}/commands.json") |
| 380 |
response = resp.json() |
| 381 |
if resp.status_code == 401: |
| 382 |
raise AylaAuthError(response) |
| 383 |
return response |
| 384 |
|
| 385 |
async def async_get_commands(self, device_id) -> Dict[str, str]: |
| 386 |
"""Get commands asynchronously""" |
| 387 |
async with await self.async_request("get", f"{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/devices/{device_id}/commands.json") as resp: |
| 388 |
response = await resp.json() |
| 389 |
if resp.status == 401: |
| 390 |
raise AylaAuthError() |
| 391 |
return response |
| 392 |
|
| 393 |
def get_all_notifications(self, device_id) -> Dict[str, str]: |
| 394 |
"""Get notifications by all on device synchronously""" |
| 395 |
resp = self.self_request("get", f"{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/devices/{device_id}/notifications/all.json") |
| 396 |
response = resp.json()["notification"] |
| 397 |
if resp.status_code == 401: |
| 398 |
raise AylaAuthError(response) |
| 399 |
return response |
| 400 |
|
| 401 |
async def async_get_all_notifications(self, device_id) -> Dict[str, str]: |
| 402 |
"""Get notifications by all on device asynchronously""" |
| 403 |
async with await self.async_request("get", f"{self.eu_ads_url if self.europe else self.ads_url:s}/apiv1/devices/{device_id}/notifications/all.json") as resp: |
| 404 |
response = await resp.json()["notification"] |
| 405 |
if resp.status == 401: |
| 406 |
raise AylaAuthError() |
| 407 |
return response |