| 1 |
|
| 2 |
""" |
| 3 |
Example: Enumerate YoLink Devices |
| 4 |
|
| 5 |
This example demonstrates how to list all devices registered to your |
| 6 |
YoLink account. It shows device details including ID, name, type, and model. |
| 7 |
|
| 8 |
Required environment variables: |
| 9 |
YOLINK_UAID - Your YoLink User Access ID |
| 10 |
YOLINK_SECRET_KEY - Your YoLink Secret Key |
| 11 |
|
| 12 |
To obtain credentials: |
| 13 |
1. Go to https://www.yosmart.com and log into your account |
| 14 |
2. Navigate to Settings -> Account -> Advanced Settings -> User Access Credentials |
| 15 |
3. Generate a new UAID/Secret Key pair |
| 16 |
""" |
| 17 |
|
| 18 |
import asyncio |
| 19 |
import os |
| 20 |
import sys |
| 21 |
from datetime import datetime, timedelta, timezone |
| 22 |
|
| 23 |
import aiohttp |
| 24 |
|
| 25 |
|
| 26 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 27 |
|
| 28 |
from yolink.auth_mgr import YoLinkAuthMgr |
| 29 |
from yolink.client import YoLinkClient |
| 30 |
from yolink.const import OAUTH2_TOKEN |
| 31 |
from yolink.endpoint import Endpoints |
| 32 |
|
| 33 |
|
| 34 |
class SimpleAuthManager(YoLinkAuthMgr): |
| 35 |
""" |
| 36 |
A simple authentication manager that handles OAuth2 token management. |
| 37 |
|
| 38 |
This implementation fetches and refreshes access tokens using the |
| 39 |
client credentials grant type with UAID and Secret Key. |
| 40 |
""" |
| 41 |
|
| 42 |
def __init__(self, session: aiohttp.ClientSession, uaid: str, secret_key: str) -> None: |
| 43 |
""" |
| 44 |
Initialize the auth manager. |
| 45 |
|
| 46 |
Args: |
| 47 |
session: An aiohttp ClientSession for making HTTP requests |
| 48 |
uaid: Your YoLink User Access ID |
| 49 |
secret_key: Your YoLink Secret Key |
| 50 |
""" |
| 51 |
super().__init__(session) |
| 52 |
self._uaid = uaid |
| 53 |
self._secret_key = secret_key |
| 54 |
self._access_token: str | None = None |
| 55 |
self._token_expires_at: datetime | None = None |
| 56 |
|
| 57 |
def access_token(self) -> str: |
| 58 |
"""Return the current access token.""" |
| 59 |
return self._access_token or "" |
| 60 |
|
| 61 |
async def check_and_refresh_token(self) -> str: |
| 62 |
""" |
| 63 |
Check if token is valid and refresh if necessary. |
| 64 |
|
| 65 |
Returns: |
| 66 |
The current valid access token |
| 67 |
""" |
| 68 |
|
| 69 |
if ( |
| 70 |
self._access_token is None |
| 71 |
or self._token_expires_at is None |
| 72 |
or datetime.now(timezone.utc) >= self._token_expires_at - timedelta(minutes=5) |
| 73 |
): |
| 74 |
await self._fetch_token() |
| 75 |
return self._access_token |
| 76 |
|
| 77 |
async def _fetch_token(self) -> None: |
| 78 |
"""Fetch a new access token from YoLink OAuth2 endpoint.""" |
| 79 |
async with self._session.post( |
| 80 |
OAUTH2_TOKEN, |
| 81 |
data={ |
| 82 |
"grant_type": "client_credentials", |
| 83 |
"client_id": self._uaid, |
| 84 |
"client_secret": self._secret_key, |
| 85 |
}, |
| 86 |
) as response: |
| 87 |
response.raise_for_status() |
| 88 |
data = await response.json() |
| 89 |
|
| 90 |
self._access_token = data["access_token"] |
| 91 |
|
| 92 |
expires_in = data.get("expires_in", 7200) |
| 93 |
self._token_expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in) |
| 94 |
|
| 95 |
|
| 96 |
async def main() -> None: |
| 97 |
"""Main function demonstrating device enumeration.""" |
| 98 |
|
| 99 |
uaid = os.environ.get("YOLINK_UAID") |
| 100 |
secret_key = os.environ.get("YOLINK_SECRET_KEY") |
| 101 |
|
| 102 |
if not uaid or not secret_key: |
| 103 |
print("Error: Missing credentials!") |
| 104 |
print("Please set the following environment variables:") |
| 105 |
print(" YOLINK_UAID - Your YoLink User Access ID") |
| 106 |
print(" YOLINK_SECRET_KEY - Your YoLink Secret Key") |
| 107 |
sys.exit(1) |
| 108 |
|
| 109 |
|
| 110 |
async with aiohttp.ClientSession() as session: |
| 111 |
auth_mgr = SimpleAuthManager(session, uaid, secret_key) |
| 112 |
client = YoLinkClient(auth_mgr) |
| 113 |
|
| 114 |
print("Connecting to YoLink API...") |
| 115 |
await auth_mgr.check_and_refresh_token() |
| 116 |
print("✓ Successfully authenticated!\n") |
| 117 |
|
| 118 |
|
| 119 |
print("Fetching device list...") |
| 120 |
response = await client.execute( |
| 121 |
url=Endpoints.US.value.url, |
| 122 |
bsdp={"method": "Home.getDeviceList"} |
| 123 |
) |
| 124 |
|
| 125 |
devices = response.data.get("devices", []) |
| 126 |
print(f"✓ Found {len(devices)} device(s)\n") |
| 127 |
|
| 128 |
|
| 129 |
print("-" * 80) |
| 130 |
print(f"{'Name':<25} {'Type':<20} {'Model':<15} {'Device ID':<20}") |
| 131 |
print("-" * 80) |
| 132 |
|
| 133 |
for device in devices: |
| 134 |
name = device.get("name", "Unknown")[:24] |
| 135 |
device_type = device.get("type", "Unknown")[:19] |
| 136 |
model = device.get("modelName", "Unknown")[:14] |
| 137 |
device_id = device.get("deviceId", "Unknown")[:19] |
| 138 |
|
| 139 |
print(f"{name:<25} {device_type:<20} {model:<15} {device_id:<20}") |
| 140 |
|
| 141 |
print("-" * 80) |
| 142 |
|
| 143 |
|
| 144 |
print("\nDevices by type:") |
| 145 |
device_types: dict[str, int] = {} |
| 146 |
for device in devices: |
| 147 |
dtype = device.get("type", "Unknown") |
| 148 |
device_types[dtype] = device_types.get(dtype, 0) + 1 |
| 149 |
|
| 150 |
for dtype, count in sorted(device_types.items()): |
| 151 |
print(f" {dtype}: {count}") |
| 152 |
|
| 153 |
|
| 154 |
if __name__ == "__main__": |
| 155 |
asyncio.run(main()) |
| 156 |
|