| 1 |
|
| 2 |
""" |
| 3 |
Example: Control a Switch/Outlet |
| 4 |
|
| 5 |
This example demonstrates how to control YoLink switches and outlets, |
| 6 |
including turning them on/off. It works with Switch, Outlet, and MultiOutlet |
| 7 |
device types. |
| 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 switch/outlet device ID to control |
| 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 os |
| 24 |
import sys |
| 25 |
from datetime import datetime, timedelta, timezone |
| 26 |
|
| 27 |
import aiohttp |
| 28 |
|
| 29 |
|
| 30 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 31 |
|
| 32 |
from yolink.auth_mgr import YoLinkAuthMgr |
| 33 |
from yolink.client import YoLinkClient |
| 34 |
from yolink.client_request import ClientRequest |
| 35 |
from yolink.const import OAUTH2_TOKEN |
| 36 |
from yolink.device import YoLinkDevice, YoLinkDeviceMode |
| 37 |
from yolink.endpoint import Endpoints |
| 38 |
from yolink.outlet_request_builder import OutletRequestBuilder |
| 39 |
|
| 40 |
|
| 41 |
class SimpleAuthManager(YoLinkAuthMgr): |
| 42 |
""" |
| 43 |
A simple authentication manager that handles OAuth2 token management. |
| 44 |
|
| 45 |
This implementation fetches and refreshes access tokens using the |
| 46 |
client credentials grant type with UAID and Secret Key. |
| 47 |
""" |
| 48 |
|
| 49 |
def __init__(self, session: aiohttp.ClientSession, uaid: str, secret_key: str) -> None: |
| 50 |
""" |
| 51 |
Initialize the auth manager. |
| 52 |
|
| 53 |
Args: |
| 54 |
session: An aiohttp ClientSession for making HTTP requests |
| 55 |
uaid: Your YoLink User Access ID |
| 56 |
secret_key: Your YoLink Secret Key |
| 57 |
""" |
| 58 |
super().__init__(session) |
| 59 |
self._uaid = uaid |
| 60 |
self._secret_key = secret_key |
| 61 |
self._access_token: str | None = None |
| 62 |
self._token_expires_at: datetime | None = None |
| 63 |
|
| 64 |
def access_token(self) -> str: |
| 65 |
"""Return the current access token.""" |
| 66 |
return self._access_token or "" |
| 67 |
|
| 68 |
async def check_and_refresh_token(self) -> str: |
| 69 |
""" |
| 70 |
Check if token is valid and refresh if necessary. |
| 71 |
|
| 72 |
Returns: |
| 73 |
The current valid access token |
| 74 |
""" |
| 75 |
|
| 76 |
if ( |
| 77 |
self._access_token is None |
| 78 |
or self._token_expires_at is None |
| 79 |
or datetime.now(timezone.utc) >= self._token_expires_at - timedelta(minutes=5) |
| 80 |
): |
| 81 |
await self._fetch_token() |
| 82 |
return self._access_token |
| 83 |
|
| 84 |
async def _fetch_token(self) -> None: |
| 85 |
"""Fetch a new access token from YoLink OAuth2 endpoint.""" |
| 86 |
async with self._session.post( |
| 87 |
OAUTH2_TOKEN, |
| 88 |
data={ |
| 89 |
"grant_type": "client_credentials", |
| 90 |
"client_id": self._uaid, |
| 91 |
"client_secret": self._secret_key, |
| 92 |
}, |
| 93 |
) as response: |
| 94 |
response.raise_for_status() |
| 95 |
data = await response.json() |
| 96 |
|
| 97 |
self._access_token = data["access_token"] |
| 98 |
|
| 99 |
expires_in = data.get("expires_in", 7200) |
| 100 |
self._token_expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in) |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
CONTROLLABLE_TYPES = ["Switch", "Outlet", "MultiOutlet", "Manipulator"] |
| 105 |
|
| 106 |
|
| 107 |
async def main() -> None: |
| 108 |
"""Main function demonstrating switch control.""" |
| 109 |
|
| 110 |
uaid = os.environ.get("YOLINK_UAID") |
| 111 |
secret_key = os.environ.get("YOLINK_SECRET_KEY") |
| 112 |
device_id = os.environ.get("YOLINK_DEVICE_ID") |
| 113 |
|
| 114 |
if not uaid or not secret_key: |
| 115 |
print("Error: Missing credentials!") |
| 116 |
print("Please set the following environment variables:") |
| 117 |
print(" YOLINK_UAID - Your YoLink User Access ID") |
| 118 |
print(" YOLINK_SECRET_KEY - Your YoLink Secret Key") |
| 119 |
sys.exit(1) |
| 120 |
|
| 121 |
|
| 122 |
async with aiohttp.ClientSession() as session: |
| 123 |
auth_mgr = SimpleAuthManager(session, uaid, secret_key) |
| 124 |
client = YoLinkClient(auth_mgr) |
| 125 |
|
| 126 |
print("Connecting to YoLink API...") |
| 127 |
await auth_mgr.check_and_refresh_token() |
| 128 |
print("✓ Successfully authenticated!\n") |
| 129 |
|
| 130 |
|
| 131 |
response = await client.execute( |
| 132 |
url=Endpoints.US.value.url, |
| 133 |
bsdp={"method": "Home.getDeviceList"} |
| 134 |
) |
| 135 |
devices = response.data.get("devices", []) |
| 136 |
|
| 137 |
|
| 138 |
controllable_devices = [ |
| 139 |
d for d in devices if d.get("type") in CONTROLLABLE_TYPES |
| 140 |
] |
| 141 |
|
| 142 |
if not controllable_devices: |
| 143 |
print("No controllable switch/outlet devices found in your account.") |
| 144 |
print(f"This example works with: {', '.join(CONTROLLABLE_TYPES)}") |
| 145 |
sys.exit(0) |
| 146 |
|
| 147 |
|
| 148 |
if not device_id: |
| 149 |
print("Available controllable devices:") |
| 150 |
for i, dev in enumerate(controllable_devices, 1): |
| 151 |
print(f" {i}. {dev.get('name')} ({dev.get('type')}) - {dev.get('deviceId')}") |
| 152 |
print() |
| 153 |
|
| 154 |
|
| 155 |
device_id = controllable_devices[0].get("deviceId") |
| 156 |
print(f"Using: {controllable_devices[0].get('name')}\n") |
| 157 |
|
| 158 |
|
| 159 |
device_data = None |
| 160 |
for dev in devices: |
| 161 |
if dev.get("deviceId") == device_id: |
| 162 |
device_data = dev |
| 163 |
break |
| 164 |
|
| 165 |
if not device_data: |
| 166 |
print(f"Error: Device with ID '{device_id}' not found.") |
| 167 |
sys.exit(1) |
| 168 |
|
| 169 |
if device_data.get("type") not in CONTROLLABLE_TYPES: |
| 170 |
print(f"Error: Device '{device_data.get('name')}' is not a controllable device.") |
| 171 |
print(f"Type: {device_data.get('type')}") |
| 172 |
print(f"This example works with: {', '.join(CONTROLLABLE_TYPES)}") |
| 173 |
sys.exit(1) |
| 174 |
|
| 175 |
|
| 176 |
device_mode = YoLinkDeviceMode(**device_data) |
| 177 |
device = YoLinkDevice(device_mode, client) |
| 178 |
|
| 179 |
print(f"Device: {device.device_name}") |
| 180 |
print(f" Type: {device.device_type}") |
| 181 |
print(f" Model: {device.device_model_name}") |
| 182 |
print() |
| 183 |
|
| 184 |
|
| 185 |
print("Getting current state...") |
| 186 |
try: |
| 187 |
state_response = await device.get_state() |
| 188 |
current_state = state_response.data.get("state", {}).get("state", "unknown") |
| 189 |
print(f" Current state: {current_state}") |
| 190 |
except Exception as e: |
| 191 |
print(f" Could not get state: {e}") |
| 192 |
current_state = "unknown" |
| 193 |
|
| 194 |
print() |
| 195 |
|
| 196 |
|
| 197 |
new_state = "close" if current_state == "open" else "open" |
| 198 |
state_label = "ON" if new_state == "open" else "OFF" |
| 199 |
|
| 200 |
print(f"Turning switch {state_label}...") |
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
request = OutletRequestBuilder.set_state_request(state=new_state, plug_indx=None) |
| 206 |
|
| 207 |
try: |
| 208 |
result = await device.call_device(request) |
| 209 |
|
| 210 |
if result.code == "000000": |
| 211 |
print(f"✓ Successfully turned {state_label}!") |
| 212 |
|
| 213 |
|
| 214 |
new_state_data = result.data.get("state", {}) |
| 215 |
print(f" New state: {new_state_data.get('state', 'unknown')}") |
| 216 |
else: |
| 217 |
print(f"✗ Failed to change state: {result.desc}") |
| 218 |
|
| 219 |
except Exception as e: |
| 220 |
print(f"✗ Error: {e}") |
| 221 |
|
| 222 |
print() |
| 223 |
print("Note: For MultiOutlet devices (power strips), you can control individual outlets") |
| 224 |
print(" by passing the outlet index (0-based) to OutletRequestBuilder.set_state_request()") |
| 225 |
|
| 226 |
|
| 227 |
if __name__ == "__main__": |
| 228 |
asyncio.run(main()) |
| 229 |
|