| 1 |
|
| 2 |
""" |
| 3 |
Example: Subscribe to MQTT Events |
| 4 |
|
| 5 |
This example demonstrates how to connect to YoLink's MQTT broker to receive |
| 6 |
real-time device events. It shows: |
| 7 |
- How to retrieve your home ID (required for MQTT subscription) |
| 8 |
- How to connect to the MQTT broker using your access token |
| 9 |
- How to process incoming device events |
| 10 |
|
| 11 |
Required environment variables: |
| 12 |
YOLINK_UAID - Your YoLink User Access ID |
| 13 |
YOLINK_SECRET_KEY - Your YoLink Secret Key |
| 14 |
|
| 15 |
To obtain credentials: |
| 16 |
1. Go to https://www.yosmart.com and log into your account |
| 17 |
2. Navigate to Settings -> Account -> Advanced Settings -> User Access Credentials |
| 18 |
3. Generate a new UAID/Secret Key pair |
| 19 |
|
| 20 |
Note: This example uses the aiomqtt library which is included in the yolink-api |
| 21 |
dependencies. Events will be displayed as they are received from your devices. |
| 22 |
Press Ctrl+C to stop listening. |
| 23 |
""" |
| 24 |
|
| 25 |
import asyncio |
| 26 |
import json |
| 27 |
import os |
| 28 |
import signal |
| 29 |
import sys |
| 30 |
from datetime import datetime, timedelta, timezone |
| 31 |
|
| 32 |
import aiohttp |
| 33 |
import aiomqtt |
| 34 |
|
| 35 |
|
| 36 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 37 |
|
| 38 |
from yolink.auth_mgr import YoLinkAuthMgr |
| 39 |
from yolink.client import YoLinkClient |
| 40 |
from yolink.const import OAUTH2_TOKEN |
| 41 |
from yolink.endpoint import Endpoints |
| 42 |
|
| 43 |
|
| 44 |
class SimpleAuthManager(YoLinkAuthMgr): |
| 45 |
""" |
| 46 |
A simple authentication manager that handles OAuth2 token management. |
| 47 |
|
| 48 |
This implementation fetches and refreshes access tokens using the |
| 49 |
client credentials grant type with UAID and Secret Key. |
| 50 |
""" |
| 51 |
|
| 52 |
def __init__(self, session: aiohttp.ClientSession, uaid: str, secret_key: str) -> None: |
| 53 |
""" |
| 54 |
Initialize the auth manager. |
| 55 |
|
| 56 |
Args: |
| 57 |
session: An aiohttp ClientSession for making HTTP requests |
| 58 |
uaid: Your YoLink User Access ID |
| 59 |
secret_key: Your YoLink Secret Key |
| 60 |
""" |
| 61 |
super().__init__(session) |
| 62 |
self._uaid = uaid |
| 63 |
self._secret_key = secret_key |
| 64 |
self._access_token: str | None = None |
| 65 |
self._token_expires_at: datetime | None = None |
| 66 |
|
| 67 |
def access_token(self) -> str: |
| 68 |
"""Return the current access token.""" |
| 69 |
return self._access_token or "" |
| 70 |
|
| 71 |
async def check_and_refresh_token(self) -> str: |
| 72 |
""" |
| 73 |
Check if token is valid and refresh if necessary. |
| 74 |
|
| 75 |
Returns: |
| 76 |
The current valid access token |
| 77 |
""" |
| 78 |
|
| 79 |
if ( |
| 80 |
self._access_token is None |
| 81 |
or self._token_expires_at is None |
| 82 |
or datetime.now(timezone.utc) >= self._token_expires_at - timedelta(minutes=5) |
| 83 |
): |
| 84 |
await self._fetch_token() |
| 85 |
return self._access_token |
| 86 |
|
| 87 |
async def _fetch_token(self) -> None: |
| 88 |
"""Fetch a new access token from YoLink OAuth2 endpoint.""" |
| 89 |
async with self._session.post( |
| 90 |
OAUTH2_TOKEN, |
| 91 |
data={ |
| 92 |
"grant_type": "client_credentials", |
| 93 |
"client_id": self._uaid, |
| 94 |
"client_secret": self._secret_key, |
| 95 |
}, |
| 96 |
) as response: |
| 97 |
response.raise_for_status() |
| 98 |
data = await response.json() |
| 99 |
|
| 100 |
self._access_token = data["access_token"] |
| 101 |
|
| 102 |
expires_in = data.get("expires_in", 7200) |
| 103 |
self._token_expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in) |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
running = True |
| 108 |
|
| 109 |
|
| 110 |
def handle_shutdown(signum, frame): |
| 111 |
"""Handle shutdown signals gracefully.""" |
| 112 |
global running |
| 113 |
print("\n\nShutting down...") |
| 114 |
running = False |
| 115 |
|
| 116 |
|
| 117 |
async def main() -> None: |
| 118 |
"""Main function demonstrating MQTT event subscription.""" |
| 119 |
global running |
| 120 |
|
| 121 |
|
| 122 |
signal.signal(signal.SIGINT, handle_shutdown) |
| 123 |
signal.signal(signal.SIGTERM, handle_shutdown) |
| 124 |
|
| 125 |
|
| 126 |
uaid = os.environ.get("YOLINK_UAID") |
| 127 |
secret_key = os.environ.get("YOLINK_SECRET_KEY") |
| 128 |
|
| 129 |
if not uaid or not secret_key: |
| 130 |
print("Error: Missing credentials!") |
| 131 |
print("Please set the following environment variables:") |
| 132 |
print(" YOLINK_UAID - Your YoLink User Access ID") |
| 133 |
print(" YOLINK_SECRET_KEY - Your YoLink Secret Key") |
| 134 |
sys.exit(1) |
| 135 |
|
| 136 |
|
| 137 |
async with aiohttp.ClientSession() as session: |
| 138 |
auth_mgr = SimpleAuthManager(session, uaid, secret_key) |
| 139 |
client = YoLinkClient(auth_mgr) |
| 140 |
|
| 141 |
print("Connecting to YoLink API...") |
| 142 |
await auth_mgr.check_and_refresh_token() |
| 143 |
print("✓ Successfully authenticated!\n") |
| 144 |
|
| 145 |
|
| 146 |
print("Retrieving home information...") |
| 147 |
home_response = await client.execute( |
| 148 |
url=Endpoints.US.value.url, |
| 149 |
bsdp={"method": "Home.getGeneralInfo"} |
| 150 |
) |
| 151 |
home_id = home_response.data.get("id") |
| 152 |
home_name = home_response.data.get("name", "Unknown") |
| 153 |
print(f"✓ Home: {home_name}") |
| 154 |
print(f" Home ID: {home_id}\n") |
| 155 |
|
| 156 |
|
| 157 |
device_response = await client.execute( |
| 158 |
url=Endpoints.US.value.url, |
| 159 |
bsdp={"method": "Home.getDeviceList"} |
| 160 |
) |
| 161 |
devices = { |
| 162 |
d.get("deviceId"): d.get("name", "Unknown") |
| 163 |
for d in device_response.data.get("devices", []) |
| 164 |
} |
| 165 |
print(f"Loaded {len(devices)} device(s) for event lookup\n") |
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
mqtt_topic = f"yl-home/{home_id}/+/report" |
| 171 |
|
| 172 |
print("Connecting to MQTT broker...") |
| 173 |
print(f" Broker: {Endpoints.US.value.mqtt_broker_host}:{Endpoints.US.value.mqtt_broker_port}") |
| 174 |
print(f" Topic: {mqtt_topic}") |
| 175 |
print() |
| 176 |
|
| 177 |
try: |
| 178 |
async with aiomqtt.Client( |
| 179 |
hostname=Endpoints.US.value.mqtt_broker_host, |
| 180 |
port=Endpoints.US.value.mqtt_broker_port, |
| 181 |
username=auth_mgr.access_token(), |
| 182 |
password="", |
| 183 |
keepalive=60, |
| 184 |
) as mqtt_client: |
| 185 |
print("✓ Connected to MQTT broker!") |
| 186 |
await mqtt_client.subscribe(mqtt_topic) |
| 187 |
print("✓ Subscribed to device events\n") |
| 188 |
print("=" * 60) |
| 189 |
print("Listening for events... Press Ctrl+C to stop") |
| 190 |
print("=" * 60) |
| 191 |
print() |
| 192 |
|
| 193 |
|
| 194 |
async for message in mqtt_client.messages: |
| 195 |
if not running: |
| 196 |
break |
| 197 |
|
| 198 |
try: |
| 199 |
|
| 200 |
|
| 201 |
topic_parts = str(message.topic).split("/") |
| 202 |
device_id = topic_parts[2] if len(topic_parts) >= 4 else "unknown" |
| 203 |
device_name = devices.get(device_id, "Unknown Device") |
| 204 |
|
| 205 |
|
| 206 |
payload = json.loads(message.payload.decode("UTF-8")) |
| 207 |
|
| 208 |
|
| 209 |
event = payload.get("event", "unknown") |
| 210 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 211 |
|
| 212 |
|
| 213 |
print(f"[{timestamp}] {device_name} ({device_id})") |
| 214 |
print(f" Event: {event}") |
| 215 |
|
| 216 |
|
| 217 |
if "data" in payload: |
| 218 |
data = payload["data"] |
| 219 |
|
| 220 |
|
| 221 |
if "state" in data: |
| 222 |
print(f" State: {json.dumps(data['state'], indent=4)}") |
| 223 |
|
| 224 |
|
| 225 |
for key, value in data.items(): |
| 226 |
if key not in ["state", "loraInfo", "deviceId"]: |
| 227 |
print(f" {key}: {value}") |
| 228 |
|
| 229 |
print() |
| 230 |
|
| 231 |
except json.JSONDecodeError: |
| 232 |
print(f"Could not parse message: {message.payload[:100]}") |
| 233 |
except Exception as e: |
| 234 |
print(f"Error processing message: {e}") |
| 235 |
|
| 236 |
except aiomqtt.MqttError as e: |
| 237 |
print(f"MQTT Error: {e}") |
| 238 |
sys.exit(1) |
| 239 |
|
| 240 |
|
| 241 |
if __name__ == "__main__": |
| 242 |
asyncio.run(main()) |
| 243 |
|