Debian Codegraph @

examples/01_connect_to_api.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """
3 Example: Connect to YoLink API
4
5 This example demonstrates how to establish a connection to the YoLink API
6 using OAuth2 credentials. It shows the basic setup required to authenticate
7 and make API requests.
8
9 Required environment variables:
10 YOLINK_UAID - Your YoLink User Access ID
11 YOLINK_SECRET_KEY - Your YoLink Secret Key
12
13 To obtain credentials:
14 1. Go to https://www.yosmart.com and log into your account
15 2. Navigate to Settings -> Account -> Advanced Settings -> User Access Credentials
16 3. Generate a new UAID/Secret Key pair
17 """
18
19 import asyncio
20 import os
21 import sys
22 from datetime import datetime, timedelta, timezone
23
24 import aiohttp
25
26 # Add parent directory to path to import yolink module
27 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
28
29 from yolink.auth_mgr import YoLinkAuthMgr
30 from yolink.client import YoLinkClient
31 from yolink.const import OAUTH2_TOKEN
32 from yolink.endpoint import Endpoints
33
34
35 class SimpleAuthManager(YoLinkAuthMgr):
36 """
37 A simple authentication manager that handles OAuth2 token management.
38
39 This implementation fetches and refreshes access tokens using the
40 client credentials grant type with UAID and Secret Key.
41 """
42
43 def __init__(self, session: aiohttp.ClientSession, uaid: str, secret_key: str) -> None:
44 """
45 Initialize the auth manager.
46
47 Args:
48 session: An aiohttp ClientSession for making HTTP requests
49 uaid: Your YoLink User Access ID
50 secret_key: Your YoLink Secret Key
51 """
52 super().__init__(session)
53 self._uaid = uaid
54 self._secret_key = secret_key
55 self._access_token: str | None = None
56 self._token_expires_at: datetime | None = None
57
58 def access_token(self) -> str:
59 """Return the current access token."""
60 return self._access_token or ""
61
62 async def check_and_refresh_token(self) -> str:
63 """
64 Check if token is valid and refresh if necessary.
65
66 Returns:
67 The current valid access token
68 """
69 # Refresh if no token or token expires within 5 minutes
70 if (
71 self._access_token is None
72 or self._token_expires_at is None
73 or datetime.now(timezone.utc) >= self._token_expires_at - timedelta(minutes=5)
74 ):
75 await self._fetch_token()
76 return self._access_token
77
78 async def _fetch_token(self) -> None:
79 """Fetch a new access token from YoLink OAuth2 endpoint."""
80 async with self._session.post(
81 OAUTH2_TOKEN,
82 data={
83 "grant_type": "client_credentials",
84 "client_id": self._uaid,
85 "client_secret": self._secret_key,
86 },
87 ) as response:
88 response.raise_for_status()
89 data = await response.json()
90
91 self._access_token = data["access_token"]
92 # Token typically expires in 7200 seconds (2 hours)
93 expires_in = data.get("expires_in", 7200)
94 self._token_expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in)
95
96
97 async def main() -> None:
98 """Main function demonstrating API connection."""
99 # Get credentials from environment variables
100 uaid = os.environ.get("YOLINK_UAID")
101 secret_key = os.environ.get("YOLINK_SECRET_KEY")
102
103 if not uaid or not secret_key:
104 print("Error: Missing credentials!")
105 print("Please set the following environment variables:")
106 print(" YOLINK_UAID - Your YoLink User Access ID")
107 print(" YOLINK_SECRET_KEY - Your YoLink Secret Key")
108 sys.exit(1)
109
110 # Create an aiohttp session and auth manager
111 async with aiohttp.ClientSession() as session:
112 auth_mgr = SimpleAuthManager(session, uaid, secret_key)
113
114 # Authenticate and get token
115 print("Connecting to YoLink API...")
116 await auth_mgr.check_and_refresh_token()
117 print(f"✓ Successfully authenticated!")
118 print(f" Token expires at: {auth_mgr._token_expires_at}")
119
120 # Create a client and make a test request
121 client = YoLinkClient(auth_mgr)
122
123 # Fetch home info to verify connection
124 print("\nFetching home information...")
125 response = await client.execute(
126 url=Endpoints.US.value.url,
127 bsdp={"method": "Home.getGeneralInfo"}
128 )
129
130 print(f"✓ Connected to home: {response.data.get('name', 'Unknown')}")
131 print(f" Home ID: {response.data.get('id')}")
132
133
134 if __name__ == "__main__":
135 asyncio.run(main())
136