Debian Codegraph @

examples/03_get_device_state.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """
3 Example: Get Device State
4
5 This example demonstrates how to retrieve the current state of a specific
6 YoLink device. It shows how to query device status including online/offline
7 state, sensor readings, or switch states depending on the device type.
8
9 Required environment variables:
10 YOLINK_UAID - Your YoLink User Access ID
11 YOLINK_SECRET_KEY - Your YoLink Secret Key
12
13 Optional environment variables:
14 YOLINK_DEVICE_ID - The device ID to query (if not set, prompts user to select)
15
16 To obtain credentials:
17 1. Go to https://www.yosmart.com and log into your account
18 2. Navigate to Settings -> Account -> Advanced Settings -> User Access Credentials
19 3. Generate a new UAID/Secret Key pair
20 """
21
22 import asyncio
23 import json
24 import os
25 import sys
26 from datetime import datetime, timedelta, timezone
27
28 import aiohttp
29
30 # Add parent directory to path to import yolink module
31 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
32
33 from yolink.auth_mgr import YoLinkAuthMgr
34 from yolink.client import YoLinkClient
35 from yolink.const import OAUTH2_TOKEN
36 from yolink.device import YoLinkDevice, YoLinkDeviceMode
37 from yolink.endpoint import Endpoints
38
39
40 class SimpleAuthManager(YoLinkAuthMgr):
41 """
42 A simple authentication manager that handles OAuth2 token management.
43
44 This implementation fetches and refreshes access tokens using the
45 client credentials grant type with UAID and Secret Key.
46 """
47
48 def __init__(self, session: aiohttp.ClientSession, uaid: str, secret_key: str) -> None:
49 """
50 Initialize the auth manager.
51
52 Args:
53 session: An aiohttp ClientSession for making HTTP requests
54 uaid: Your YoLink User Access ID
55 secret_key: Your YoLink Secret Key
56 """
57 super().__init__(session)
58 self._uaid = uaid
59 self._secret_key = secret_key
60 self._access_token: str | None = None
61 self._token_expires_at: datetime | None = None
62
63 def access_token(self) -> str:
64 """Return the current access token."""
65 return self._access_token or ""
66
67 async def check_and_refresh_token(self) -> str:
68 """
69 Check if token is valid and refresh if necessary.
70
71 Returns:
72 The current valid access token
73 """
74 # Refresh if no token or token expires within 5 minutes
75 if (
76 self._access_token is None
77 or self._token_expires_at is None
78 or datetime.now(timezone.utc) >= self._token_expires_at - timedelta(minutes=5)
79 ):
80 await self._fetch_token()
81 return self._access_token
82
83 async def _fetch_token(self) -> None:
84 """Fetch a new access token from YoLink OAuth2 endpoint."""
85 async with self._session.post(
86 OAUTH2_TOKEN,
87 data={
88 "grant_type": "client_credentials",
89 "client_id": self._uaid,
90 "client_secret": self._secret_key,
91 },
92 ) as response:
93 response.raise_for_status()
94 data = await response.json()
95
96 self._access_token = data["access_token"]
97 # Token typically expires in 7200 seconds (2 hours)
98 expires_in = data.get("expires_in", 7200)
99 self._token_expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in)
100
101
102 async def main() -> None:
103 """Main function demonstrating device state retrieval."""
104 # Get credentials from environment variables
105 uaid = os.environ.get("YOLINK_UAID")
106 secret_key = os.environ.get("YOLINK_SECRET_KEY")
107 device_id = os.environ.get("YOLINK_DEVICE_ID")
108
109 if not uaid or not secret_key:
110 print("Error: Missing credentials!")
111 print("Please set the following environment variables:")
112 print(" YOLINK_UAID - Your YoLink User Access ID")
113 print(" YOLINK_SECRET_KEY - Your YoLink Secret Key")
114 sys.exit(1)
115
116 # Create an aiohttp session and auth manager
117 async with aiohttp.ClientSession() as session:
118 auth_mgr = SimpleAuthManager(session, uaid, secret_key)
119 client = YoLinkClient(auth_mgr)
120
121 print("Connecting to YoLink API...")
122 await auth_mgr.check_and_refresh_token()
123 print("✓ Successfully authenticated!\n")
124
125 # Fetch device list
126 response = await client.execute(
127 url=Endpoints.US.value.url,
128 bsdp={"method": "Home.getDeviceList"}
129 )
130 devices = response.data.get("devices", [])
131
132 if not devices:
133 print("No devices found in your account.")
134 sys.exit(0)
135
136 # If no device ID specified, list devices and let user choose
137 if not device_id:
138 print("Available devices:")
139 for i, dev in enumerate(devices, 1):
140 print(f" {i}. {dev.get('name')} ({dev.get('type')}) - {dev.get('deviceId')}")
141 print()
142
143 # Use the first device for demonstration
144 device_id = devices[0].get("deviceId")
145 print(f"Using first device: {devices[0].get('name')}\n")
146
147 # Find the device in the list
148 device_data = None
149 for dev in devices:
150 if dev.get("deviceId") == device_id:
151 device_data = dev
152 break
153
154 if not device_data:
155 print(f"Error: Device with ID '{device_id}' not found.")
156 sys.exit(1)
157
158 # Create a YoLinkDevice instance
159 device_mode = YoLinkDeviceMode(**device_data)
160 device = YoLinkDevice(device_mode, client)
161
162 print(f"Device: {device.device_name}")
163 print(f" Type: {device.device_type}")
164 print(f" Model: {device.device_model_name}")
165 print(f" ID: {device.device_id}")
166 print()
167
168 # Get device state
169 print("Fetching device state...")
170 try:
171 state_response = await device.get_state()
172
173 print("✓ Device state retrieved:\n")
174 # Pretty print the state data
175 state_data = state_response.data
176 print(json.dumps(state_data, indent=2))
177
178 except Exception as e:
179 print(f"Error fetching state: {e}")
180 print("\nNote: Some devices (like hubs) may not support getState.")
181 print("Try running this example with a sensor or switch device.")
182
183
184 if __name__ == "__main__":
185 asyncio.run(main())
186