ha-xthings-cloud 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ """Async Python client for Xthings Cloud API."""
2
+
3
+ from .client import XthingsCloudApiClient
4
+ from .const import API_BASE_URL, WS_URL
5
+ from .exceptions import XthingsCloudApiError, XthingsCloudAuthError
6
+ from .kvs_signaling import KvsSignalingClient
7
+ from .websocket import XthingsCloudWebSocket
8
+
9
+ __all__ = [
10
+ "XthingsCloudApiClient",
11
+ "XthingsCloudWebSocket",
12
+ "KvsSignalingClient",
13
+ "XthingsCloudApiError",
14
+ "XthingsCloudAuthError",
15
+ "API_BASE_URL",
16
+ "WS_URL",
17
+ ]
@@ -0,0 +1,242 @@
1
+ """Xthings Cloud API client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any
7
+
8
+ import aiohttp
9
+
10
+ from .const import (
11
+ API_BRITE_BRIGHTNESS,
12
+ API_BRITE_COLOR,
13
+ API_BRITE_OFF,
14
+ API_BRITE_ON,
15
+ API_CAMERA_WEBRTC,
16
+ API_DEVICE_STATUS,
17
+ API_DEVICES,
18
+ API_FRP_HTTP,
19
+ API_LOCK_LOCK,
20
+ API_LOCK_UNLOCK,
21
+ API_LOGIN,
22
+ API_PLUG_OFF,
23
+ API_PLUG_ON,
24
+ API_REFRESH_TOKEN,
25
+ API_SWITCH_BRIGHTNESS,
26
+ API_SWITCH_OFF,
27
+ API_SWITCH_ON,
28
+ AUTH_ERROR_CODES,
29
+ )
30
+ from .exceptions import XthingsCloudApiError, XthingsCloudAuthError
31
+
32
+ _LOGGER = logging.getLogger(__name__)
33
+
34
+
35
+ class XthingsCloudApiClient:
36
+ """Async client for Xthings Cloud API.
37
+
38
+ Args:
39
+ session: aiohttp.ClientSession instance (injected, not created internally).
40
+ token: Optional pre-existing auth token.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ session: aiohttp.ClientSession,
46
+ token: str | None = None,
47
+ ) -> None:
48
+ self._session = session
49
+ self._token = token
50
+
51
+ @property
52
+ def token(self) -> str | None:
53
+ """Return current auth token."""
54
+ return self._token
55
+
56
+ @token.setter
57
+ def token(self, value: str | None) -> None:
58
+ """Set auth token."""
59
+ self._token = value
60
+
61
+ def _headers(self) -> dict[str, str]:
62
+ """Build request headers with auth token."""
63
+ headers = {"Content-Type": "application/json"}
64
+ if self._token:
65
+ headers["x-token"] = self._token
66
+ return headers
67
+
68
+ async def _request(
69
+ self,
70
+ url: str,
71
+ json: dict[str, Any] | None = None,
72
+ headers: dict[str, str] | None = None,
73
+ ) -> dict[str, Any]:
74
+ """Send POST request and parse response.
75
+
76
+ Xthings API always uses POST and returns {"code": int, "data": ...}.
77
+ Success is indicated by code=200 in the response body (not HTTP status).
78
+ """
79
+ if headers is None:
80
+ headers = self._headers()
81
+
82
+ _LOGGER.debug("Request: POST %s, body=%s", url, json)
83
+
84
+ try:
85
+ resp = await self._session.request("POST", url, json=json, headers=headers)
86
+ resp.raise_for_status()
87
+ result = await resp.json()
88
+ except aiohttp.ClientError as err:
89
+ raise XthingsCloudApiError(f"Request failed: {err}") from err
90
+
91
+ code = result.get("code")
92
+ data = result.get("data", {})
93
+
94
+ _LOGGER.debug("Response: POST %s, code=%s", url, code)
95
+
96
+ if code == 200:
97
+ return data
98
+
99
+ if code in AUTH_ERROR_CODES:
100
+ raise XthingsCloudAuthError(f"Auth failed (code={code})", code=code)
101
+
102
+ raise XthingsCloudApiError(f"API error (code={code})", code=code)
103
+
104
+ # ---- Auth ----
105
+
106
+ async def async_login(
107
+ self,
108
+ email: str,
109
+ password: str,
110
+ client_id: str | None = None,
111
+ verification_code: str | None = None,
112
+ ) -> dict[str, Any]:
113
+ """Login and obtain token.
114
+
115
+ Returns {"2fa": int} if 2FA verification is required.
116
+ Returns {"token": str, "refresh_token": str, "client_id": str} on success.
117
+ """
118
+ payload: dict[str, Any] = {"email": email, "password": password}
119
+ if client_id:
120
+ payload["client_id"] = client_id
121
+ if verification_code:
122
+ payload["code"] = verification_code
123
+
124
+ data = await self._request(
125
+ API_LOGIN, json=payload,
126
+ headers={"Content-Type": "application/json"},
127
+ )
128
+
129
+ if data.get("2fa"):
130
+ return {"2fa": data["2fa"]}
131
+
132
+ self._token = data["token"]
133
+ return {
134
+ "token": data["token"],
135
+ "refresh_token": data.get("refresh_token", ""),
136
+ "client_id": data.get("client_id", ""),
137
+ }
138
+
139
+ async def async_refresh_token(self, refresh_token: str) -> dict[str, Any]:
140
+ """Refresh auth token using refresh_token."""
141
+ data = await self._request(
142
+ API_REFRESH_TOKEN,
143
+ json={"refresh_token": refresh_token},
144
+ headers={"Content-Type": "application/json"},
145
+ )
146
+ self._token = data["token"]
147
+ return {
148
+ "token": data["token"],
149
+ "refresh_token": data.get("refresh_token", ""),
150
+ }
151
+
152
+ # ---- Devices ----
153
+
154
+ async def async_get_devices(self) -> list[dict[str, Any]]:
155
+ """Get device list."""
156
+ data = await self._request(API_DEVICES)
157
+ return data.get("devices", [])
158
+
159
+ async def async_get_device_status(self, device_id: str) -> dict[str, Any]:
160
+ """Get single device status."""
161
+ return await self._request(API_DEVICE_STATUS, json={"id": device_id})
162
+
163
+ # ---- Switch ----
164
+
165
+ async def async_switch_on(self, device_id: str) -> dict[str, Any]:
166
+ """Turn on switch."""
167
+ return await self._request(API_SWITCH_ON, json={"uuid": device_id})
168
+
169
+ async def async_switch_off(self, device_id: str) -> dict[str, Any]:
170
+ """Turn off switch."""
171
+ return await self._request(API_SWITCH_OFF, json={"uuid": device_id})
172
+
173
+ async def async_switch_brightness(
174
+ self, device_id: str, brightness: int
175
+ ) -> dict[str, Any]:
176
+ """Set switch brightness (0-100)."""
177
+ return await self._request(
178
+ API_SWITCH_BRIGHTNESS, json={"uuid": device_id, "brightness": brightness}
179
+ )
180
+
181
+ # ---- Plug ----
182
+
183
+ async def async_plug_on(self, device_id: str) -> dict[str, Any]:
184
+ """Turn on plug."""
185
+ return await self._request(API_PLUG_ON, json={"uuid": device_id})
186
+
187
+ async def async_plug_off(self, device_id: str) -> dict[str, Any]:
188
+ """Turn off plug."""
189
+ return await self._request(API_PLUG_OFF, json={"uuid": device_id})
190
+
191
+ # ---- Light (Brite) ----
192
+
193
+ async def async_brite_on(self, device_id: str) -> dict[str, Any]:
194
+ """Turn on light."""
195
+ return await self._request(API_BRITE_ON, json={"uuid": device_id})
196
+
197
+ async def async_brite_off(self, device_id: str) -> dict[str, Any]:
198
+ """Turn off light."""
199
+ return await self._request(API_BRITE_OFF, json={"uuid": device_id})
200
+
201
+ async def async_brite_brightness(
202
+ self, device_id: str, brightness: int
203
+ ) -> dict[str, Any]:
204
+ """Set light brightness (0-100)."""
205
+ return await self._request(
206
+ API_BRITE_BRIGHTNESS, json={"uuid": device_id, "brightness": brightness}
207
+ )
208
+
209
+ async def async_brite_color(
210
+ self, device_id: str, color: dict[str, Any]
211
+ ) -> dict[str, Any]:
212
+ """Set light color.
213
+
214
+ Args:
215
+ color: Dict with keys like colortype, hue, saturation, lightness,
216
+ brightness, temperature depending on color mode.
217
+ """
218
+ return await self._request(
219
+ API_BRITE_COLOR, json={"uuid": device_id, "color": color}
220
+ )
221
+
222
+ # ---- Lock ----
223
+
224
+ async def async_lock_lock(self, device_id: str) -> dict[str, Any]:
225
+ """Lock the device."""
226
+ return await self._request(API_LOCK_LOCK, json={"uuid": device_id})
227
+
228
+ async def async_lock_unlock(self, device_id: str) -> dict[str, Any]:
229
+ """Unlock the device."""
230
+ return await self._request(API_LOCK_UNLOCK, json={"uuid": device_id})
231
+
232
+ # ---- Camera ----
233
+
234
+ async def async_get_camera_webrtc(self, device_id: str) -> dict[str, Any]:
235
+ """Get camera KVS WebRTC credentials."""
236
+ return await self._request(API_CAMERA_WEBRTC, json={"uuid": device_id})
237
+
238
+ # ---- FRP Remote Access ----
239
+
240
+ async def async_get_frp_config(self, client_id: str) -> dict[str, Any]:
241
+ """Get FRP remote access configuration."""
242
+ return await self._request(API_FRP_HTTP, json={"uuid": client_id})
@@ -0,0 +1,42 @@
1
+ """Constants for Xthings Cloud API."""
2
+
3
+ API_BASE_URL = "https://api.cloud.xthings.com/ha"
4
+
5
+ # Auth endpoints
6
+ API_LOGIN = f"{API_BASE_URL}/auth/login"
7
+ API_REFRESH_TOKEN = f"{API_BASE_URL}/auth/refresh"
8
+
9
+ # Device endpoints
10
+ API_DEVICES = f"{API_BASE_URL}/device"
11
+ API_DEVICE_STATUS = f"{API_BASE_URL}/device/status"
12
+
13
+ # Switch control
14
+ API_SWITCH_ON = f"{API_BASE_URL}/device/switch/command/on"
15
+ API_SWITCH_OFF = f"{API_BASE_URL}/device/switch/command/off"
16
+ API_SWITCH_BRIGHTNESS = f"{API_BASE_URL}/device/switch/command/brightness"
17
+
18
+ # Plug control
19
+ API_PLUG_ON = f"{API_BASE_URL}/device/plug/command/on"
20
+ API_PLUG_OFF = f"{API_BASE_URL}/device/plug/command/off"
21
+
22
+ # Light (Brite) control
23
+ API_BRITE_ON = f"{API_BASE_URL}/device/brite/command/on"
24
+ API_BRITE_OFF = f"{API_BASE_URL}/device/brite/command/off"
25
+ API_BRITE_BRIGHTNESS = f"{API_BASE_URL}/device/brite/command/brightness"
26
+ API_BRITE_COLOR = f"{API_BASE_URL}/device/brite/command/color"
27
+
28
+ # Lock control
29
+ API_LOCK_LOCK = f"{API_BASE_URL}/device/lock/command/lock"
30
+ API_LOCK_UNLOCK = f"{API_BASE_URL}/device/lock/command/unlock"
31
+
32
+ # Camera
33
+ API_CAMERA_WEBRTC = f"{API_BASE_URL}/device/camera/command/webrtc"
34
+
35
+ # FRP remote access
36
+ API_FRP_HTTP = f"{API_BASE_URL}/frp/get/http"
37
+
38
+ # Auth error codes that trigger re-login
39
+ AUTH_ERROR_CODES = {20001, 20011, 20012, 21022}
40
+
41
+ # WebSocket
42
+ WS_URL = "wss://api.cloud.xthings.com/api/ws"
@@ -0,0 +1,15 @@
1
+ """Exceptions for Xthings Cloud API."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class XthingsCloudApiError(Exception):
7
+ """API call error."""
8
+
9
+ def __init__(self, message: str, code: int = 0) -> None:
10
+ super().__init__(message)
11
+ self.code = code
12
+
13
+
14
+ class XthingsCloudAuthError(XthingsCloudApiError):
15
+ """Authentication error (token invalid/expired)."""
@@ -0,0 +1,332 @@
1
+ """AWS Kinesis Video Streams WebRTC signaling client.
2
+
3
+ Handles SDP offer/answer exchange and ICE candidate forwarding
4
+ via KVS signaling channels with AWS SigV4 authentication.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import base64
11
+ import hashlib
12
+ import hmac
13
+ import json
14
+ import logging
15
+ from datetime import datetime, timezone
16
+ from typing import Any, Callable
17
+ from urllib.parse import quote, urlparse
18
+
19
+ import aiohttp
20
+
21
+ _LOGGER = logging.getLogger(__name__)
22
+
23
+
24
+ class KvsSignalingClient:
25
+ """KVS WebRTC signaling client for SDP exchange via AWS API.
26
+
27
+ Args:
28
+ session: aiohttp.ClientSession instance (injected).
29
+ region: AWS region (e.g. "us-west-2").
30
+ channel_arn: KVS signaling channel ARN.
31
+ credentials: Dict with AccessKeyId, SecretAccessKey, SessionToken.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ session: aiohttp.ClientSession,
37
+ region: str,
38
+ channel_arn: str,
39
+ credentials: dict[str, str],
40
+ ) -> None:
41
+ self._session = session
42
+ self._region = region
43
+ self._channel_arn = channel_arn
44
+ self._access_key = credentials["AccessKeyId"]
45
+ self._secret_key = credentials["SecretAccessKey"]
46
+ self._session_token = credentials.get("SessionToken", "")
47
+ self._ws: aiohttp.ClientWebSocketResponse | None = None
48
+ self._listen_task: asyncio.Task | None = None
49
+
50
+ async def async_get_answer_sdp(
51
+ self,
52
+ offer_sdp: str,
53
+ on_ice_candidate: Callable[[dict[str, Any]], None] | None = None,
54
+ ) -> str | None:
55
+ """Exchange SDP offer for answer via KVS signaling.
56
+
57
+ Args:
58
+ offer_sdp: WebRTC SDP offer string.
59
+ on_ice_candidate: Optional callback receiving ICE candidate dicts
60
+ with keys: candidate, sdpMid, sdpMLineIndex.
61
+
62
+ Returns:
63
+ SDP answer string, or None on failure.
64
+ """
65
+ endpoints = await self._async_get_signaling_endpoints()
66
+ if not endpoints:
67
+ return None
68
+ wss_endpoint = endpoints.get("WSS")
69
+ if not wss_endpoint:
70
+ _LOGGER.error("KVS: No WSS endpoint found")
71
+ return None
72
+
73
+ signed_url = self._build_signed_wss_url(wss_endpoint)
74
+ _LOGGER.debug("KVS: Connecting to signaling channel")
75
+ try:
76
+ self._ws = await self._session.ws_connect(signed_url)
77
+ except Exception as err: # noqa: BLE001
78
+ _LOGGER.error("KVS: Signaling connection failed: %s", err)
79
+ return None
80
+
81
+ # Send SDP offer
82
+ offer_msg = json.dumps({
83
+ "action": "SDP_OFFER",
84
+ "messagePayload": base64.b64encode(
85
+ json.dumps({"type": "offer", "sdp": offer_sdp}).encode()
86
+ ).decode(),
87
+ })
88
+ await self._ws.send_str(offer_msg)
89
+ _LOGGER.debug("KVS: SDP offer sent")
90
+
91
+ # Wait for SDP answer, forward ICE candidates
92
+ answer_sdp = None
93
+ try:
94
+ async for msg in self._ws:
95
+ if msg.type in (aiohttp.WSMsgType.TEXT, aiohttp.WSMsgType.BINARY):
96
+ raw = msg.data if isinstance(msg.data, str) else (
97
+ msg.data.decode() if msg.data else None
98
+ )
99
+ if not raw:
100
+ continue
101
+ _LOGGER.debug("KVS: Message: %s", raw[:200])
102
+ data = json.loads(raw)
103
+ msg_type = data.get("messageType")
104
+
105
+ if msg_type == "SDP_ANSWER":
106
+ payload = json.loads(
107
+ base64.b64decode(data["messagePayload"]).decode()
108
+ )
109
+ answer_sdp = payload.get("sdp")
110
+ _LOGGER.debug("KVS: SDP answer received")
111
+ # Start background ICE listener
112
+ self._listen_task = asyncio.create_task(
113
+ self._async_listen_ice(on_ice_candidate)
114
+ )
115
+ return answer_sdp
116
+
117
+ elif msg_type == "ICE_CANDIDATE" and on_ice_candidate:
118
+ self._parse_and_forward_ice(data, on_ice_candidate)
119
+
120
+ elif msg.type in (aiohttp.WSMsgType.ERROR, aiohttp.WSMsgType.CLOSED):
121
+ break
122
+ except Exception as err: # noqa: BLE001
123
+ _LOGGER.error("KVS: SDP exchange failed: %s", err)
124
+ return answer_sdp
125
+
126
+ async def _async_listen_ice(
127
+ self, on_ice_candidate: Callable[[dict[str, Any]], None] | None,
128
+ ) -> None:
129
+ """Listen and forward ICE candidates in background."""
130
+ if not on_ice_candidate:
131
+ return
132
+ try:
133
+ async for msg in self._ws:
134
+ if msg.type in (aiohttp.WSMsgType.TEXT, aiohttp.WSMsgType.BINARY):
135
+ raw = msg.data if isinstance(msg.data, str) else (
136
+ msg.data.decode() if msg.data else None
137
+ )
138
+ if not raw:
139
+ continue
140
+ data = json.loads(raw)
141
+ if data.get("messageType") == "ICE_CANDIDATE":
142
+ self._parse_and_forward_ice(data, on_ice_candidate)
143
+ elif msg.type in (aiohttp.WSMsgType.ERROR, aiohttp.WSMsgType.CLOSED):
144
+ break
145
+ except asyncio.CancelledError:
146
+ pass
147
+ except Exception: # noqa: BLE001
148
+ _LOGGER.debug("KVS: ICE listener ended")
149
+
150
+ @staticmethod
151
+ def _parse_and_forward_ice(
152
+ data: dict, on_ice_candidate: Callable[[dict[str, Any]], None],
153
+ ) -> None:
154
+ """Parse ICE candidate from signaling message and forward via callback."""
155
+ try:
156
+ payload = json.loads(
157
+ base64.b64decode(data["messagePayload"]).decode()
158
+ )
159
+ on_ice_candidate({
160
+ "candidate": payload.get("candidate", ""),
161
+ "sdpMid": payload.get("sdpMid", ""),
162
+ "sdpMLineIndex": payload.get("sdpMLineIndex", 0),
163
+ })
164
+ except Exception: # noqa: BLE001
165
+ _LOGGER.debug("KVS: Failed to parse ICE candidate")
166
+
167
+ async def async_send_ice_candidate(
168
+ self, candidate: str, sdp_mid: str | None, sdp_mline_index: int | None,
169
+ ) -> None:
170
+ """Send ICE candidate to master via signaling channel."""
171
+ if not self._ws or self._ws.closed:
172
+ return
173
+ payload = json.dumps({
174
+ "candidate": candidate,
175
+ "sdpMid": sdp_mid or "0",
176
+ "sdpMLineIndex": sdp_mline_index or 0,
177
+ })
178
+ msg = json.dumps({
179
+ "action": "ICE_CANDIDATE",
180
+ "messagePayload": base64.b64encode(payload.encode()).decode(),
181
+ })
182
+ await self._ws.send_str(msg)
183
+
184
+ async def async_close(self) -> None:
185
+ """Close signaling connection and cleanup."""
186
+ if self._listen_task and not self._listen_task.done():
187
+ self._listen_task.cancel()
188
+ self._listen_task = None
189
+ if self._ws and not self._ws.closed:
190
+ await self._ws.close()
191
+ self._ws = None
192
+
193
+ # ---- AWS KVS API ----
194
+
195
+ async def _async_get_signaling_endpoints(self) -> dict[str, str]:
196
+ """Get KVS signaling channel endpoints (WSS, HTTPS)."""
197
+ url = (
198
+ f"https://kinesisvideo.{self._region}.amazonaws.com"
199
+ "/getSignalingChannelEndpoint"
200
+ )
201
+ body = json.dumps({
202
+ "ChannelARN": self._channel_arn,
203
+ "SingleMasterChannelEndpointConfiguration": {
204
+ "Protocols": ["WSS", "HTTPS"],
205
+ "Role": "VIEWER",
206
+ },
207
+ }, separators=(",", ":"))
208
+ headers = self._sign_request("POST", url, body)
209
+ try:
210
+ resp = await self._session.post(url, data=body, headers=headers)
211
+ data = await resp.json()
212
+ return {
213
+ ep["Protocol"]: ep["ResourceEndpoint"]
214
+ for ep in data.get("ResourceEndpointList", [])
215
+ }
216
+ except Exception as err: # noqa: BLE001
217
+ _LOGGER.error("KVS: Failed to get signaling endpoints: %s", err)
218
+ return {}
219
+
220
+ async def async_get_ice_server_config(self) -> list[dict[str, Any]]:
221
+ """Get KVS ICE server config (TURN/STUN)."""
222
+ endpoints = await self._async_get_signaling_endpoints()
223
+ https_endpoint = endpoints.get("HTTPS")
224
+ if not https_endpoint:
225
+ return []
226
+ url = f"{https_endpoint}/v1/get-ice-server-config"
227
+ body = json.dumps(
228
+ {"ChannelARN": self._channel_arn}, separators=(",", ":")
229
+ )
230
+ headers = self._sign_request("POST", url, body)
231
+ try:
232
+ resp = await self._session.post(url, data=body, headers=headers)
233
+ data = await resp.json()
234
+ return data.get("IceServerList", [])
235
+ except Exception as err: # noqa: BLE001
236
+ _LOGGER.error("KVS: Failed to get ICE servers: %s", err)
237
+ return []
238
+
239
+ # ---- AWS SigV4 ----
240
+
241
+ def _sign_request(self, method: str, url: str, body: str) -> dict[str, str]:
242
+ """AWS SigV4 sign HTTP request."""
243
+ now = datetime.now(timezone.utc)
244
+ datestamp = now.strftime("%Y%m%d")
245
+ amz_date = now.strftime("%Y%m%dT%H%M%SZ")
246
+ parsed = urlparse(url)
247
+ host = parsed.hostname
248
+ path = parsed.path or "/"
249
+ service = "kinesisvideo"
250
+ credential_scope = f"{datestamp}/{self._region}/{service}/aws4_request"
251
+
252
+ headers_to_sign = {"host": host, "x-amz-date": amz_date}
253
+ if self._session_token:
254
+ headers_to_sign["x-amz-security-token"] = self._session_token
255
+ signed_headers = ";".join(sorted(headers_to_sign.keys()))
256
+ canonical_headers = "".join(
257
+ f"{k}:{v}\n" for k, v in sorted(headers_to_sign.items())
258
+ )
259
+ payload_hash = hashlib.sha256(body.encode()).hexdigest()
260
+ canonical_request = (
261
+ f"{method}\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}"
262
+ )
263
+ string_to_sign = (
264
+ f"AWS4-HMAC-SHA256\n{amz_date}\n{credential_scope}\n"
265
+ f"{hashlib.sha256(canonical_request.encode()).hexdigest()}"
266
+ )
267
+ signing_key = self._get_signature_key(datestamp, service)
268
+ signature = hmac.new(
269
+ signing_key, string_to_sign.encode(), hashlib.sha256
270
+ ).hexdigest()
271
+
272
+ result = {
273
+ "Authorization": (
274
+ f"AWS4-HMAC-SHA256 Credential={self._access_key}/{credential_scope}, "
275
+ f"SignedHeaders={signed_headers}, Signature={signature}"
276
+ ),
277
+ "x-amz-date": amz_date,
278
+ "Content-Type": "application/json",
279
+ }
280
+ if self._session_token:
281
+ result["x-amz-security-token"] = self._session_token
282
+ return result
283
+
284
+ def _build_signed_wss_url(self, wss_endpoint: str) -> str:
285
+ """Build SigV4 signed WSS URL for viewer connection."""
286
+ now = datetime.now(timezone.utc)
287
+ datestamp = now.strftime("%Y%m%d")
288
+ amz_date = now.strftime("%Y%m%dT%H%M%SZ")
289
+ parsed = urlparse(wss_endpoint)
290
+ host = parsed.hostname
291
+ path = parsed.path or "/"
292
+ service = "kinesisvideo"
293
+ credential_scope = f"{datestamp}/{self._region}/{service}/aws4_request"
294
+
295
+ query_params = {
296
+ "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
297
+ "X-Amz-ChannelARN": self._channel_arn,
298
+ "X-Amz-ClientId": "ha-viewer",
299
+ "X-Amz-Credential": f"{self._access_key}/{credential_scope}",
300
+ "X-Amz-Date": amz_date,
301
+ "X-Amz-Expires": "300",
302
+ "X-Amz-SignedHeaders": "host",
303
+ }
304
+ if self._session_token:
305
+ query_params["X-Amz-Security-Token"] = self._session_token
306
+
307
+ canonical_qs = "&".join(
308
+ f"{quote(k, safe='')}={quote(v, safe='')}"
309
+ for k, v in sorted(query_params.items())
310
+ )
311
+ empty_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
312
+ canonical_request = (
313
+ f"GET\n{path}\n{canonical_qs}\nhost:{host}\n\nhost\n{empty_hash}"
314
+ )
315
+ string_to_sign = (
316
+ f"AWS4-HMAC-SHA256\n{amz_date}\n{credential_scope}\n"
317
+ f"{hashlib.sha256(canonical_request.encode()).hexdigest()}"
318
+ )
319
+ signing_key = self._get_signature_key(datestamp, service)
320
+ signature = hmac.new(
321
+ signing_key, string_to_sign.encode(), hashlib.sha256
322
+ ).hexdigest()
323
+ return f"{wss_endpoint}?{canonical_qs}&X-Amz-Signature={signature}"
324
+
325
+ def _get_signature_key(self, datestamp: str, service: str) -> bytes:
326
+ """Generate AWS SigV4 signing key."""
327
+ k_date = hmac.new(
328
+ f"AWS4{self._secret_key}".encode(), datestamp.encode(), hashlib.sha256
329
+ ).digest()
330
+ k_region = hmac.new(k_date, self._region.encode(), hashlib.sha256).digest()
331
+ k_service = hmac.new(k_region, service.encode(), hashlib.sha256).digest()
332
+ return hmac.new(k_service, b"aws4_request", hashlib.sha256).digest()
@@ -0,0 +1,211 @@
1
+ """WebSocket client for receiving real-time device status from Xthings Cloud."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ from typing import Any, Callable
8
+
9
+ import aiohttp
10
+
11
+ from .const import WS_URL
12
+
13
+ _LOGGER = logging.getLogger(__name__)
14
+
15
+ RECONNECT_MIN_DELAY = 5
16
+ RECONNECT_MAX_DELAY = 300
17
+
18
+
19
+ class XthingsCloudWebSocket:
20
+ """Xthings Cloud WebSocket client with auto-reconnect.
21
+
22
+ Args:
23
+ session: aiohttp.ClientSession instance (injected).
24
+ token: Auth token for WebSocket login.
25
+ on_device_status: Callback(device_uuid, status_dict) for device updates.
26
+ on_token_expired: Async callback when auth error is received.
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ session: aiohttp.ClientSession,
32
+ token: str,
33
+ on_device_status: Callable[[str, dict[str, Any]], None],
34
+ on_token_expired: Callable[[], Any],
35
+ ) -> None:
36
+ self._session = session
37
+ self._token = token
38
+ self._on_device_status = on_device_status
39
+ self._on_token_expired = on_token_expired
40
+ self._ws: aiohttp.ClientWebSocketResponse | None = None
41
+ self._task: asyncio.Task | None = None
42
+ self._ping_task: asyncio.Task | None = None
43
+ self._reconnect_delay = RECONNECT_MIN_DELAY
44
+ self._stopping = False
45
+
46
+ @property
47
+ def token(self) -> str:
48
+ """Return current auth token."""
49
+ return self._token
50
+
51
+ @token.setter
52
+ def token(self, value: str) -> None:
53
+ """Update auth token (e.g. after refresh)."""
54
+ self._token = value
55
+
56
+ async def async_start(self) -> None:
57
+ """Start WebSocket connection loop."""
58
+ self._stopping = False
59
+ self._task = asyncio.create_task(self._async_run())
60
+
61
+ async def async_stop(self) -> None:
62
+ """Stop WebSocket connection and cleanup."""
63
+ self._stopping = True
64
+ if self._ws and not self._ws.closed:
65
+ await self._ws.close()
66
+ if self._task and not self._task.done():
67
+ self._task.cancel()
68
+ try:
69
+ await self._task
70
+ except asyncio.CancelledError:
71
+ pass
72
+ self._task = None
73
+
74
+ async def _async_run(self) -> None:
75
+ """Main loop with exponential backoff reconnect."""
76
+ while not self._stopping:
77
+ try:
78
+ await self._async_connect()
79
+ except asyncio.CancelledError:
80
+ break
81
+ except Exception: # noqa: BLE001
82
+ _LOGGER.exception("WebSocket unexpected error")
83
+ if self._stopping:
84
+ break
85
+ _LOGGER.info("WebSocket reconnecting in %s seconds", self._reconnect_delay)
86
+ await asyncio.sleep(self._reconnect_delay)
87
+ self._reconnect_delay = min(self._reconnect_delay * 2, RECONNECT_MAX_DELAY)
88
+
89
+ async def _async_connect(self) -> None:
90
+ """Establish connection, authenticate, and process messages."""
91
+ _LOGGER.info("WebSocket connecting to %s", WS_URL)
92
+ try:
93
+ self._ws = await self._session.ws_connect(WS_URL, heartbeat=30)
94
+ except Exception as err:
95
+ _LOGGER.error("WebSocket connection failed: %s (%s)", err, type(err).__name__)
96
+ return
97
+
98
+ _LOGGER.info("WebSocket connected")
99
+ self._reconnect_delay = RECONNECT_MIN_DELAY
100
+
101
+ # Authenticate
102
+ await self._ws.send_json({"cmd": "login", "data": {"x-token": self._token}})
103
+ _LOGGER.info("WebSocket login sent")
104
+ self._ping_task = asyncio.create_task(self._async_ping_loop())
105
+
106
+ try:
107
+ async for msg in self._ws:
108
+ if msg.type == aiohttp.WSMsgType.TEXT:
109
+ _LOGGER.debug("WebSocket raw message: %s", msg.data)
110
+ await self._async_handle_message(msg.json())
111
+ elif msg.type == aiohttp.WSMsgType.ERROR:
112
+ _LOGGER.error("WebSocket error: %s", self._ws.exception())
113
+ break
114
+ elif msg.type in (
115
+ aiohttp.WSMsgType.CLOSE,
116
+ aiohttp.WSMsgType.CLOSING,
117
+ aiohttp.WSMsgType.CLOSED,
118
+ ):
119
+ _LOGGER.debug("WebSocket closed by server")
120
+ break
121
+ except aiohttp.ClientError as err:
122
+ _LOGGER.error("WebSocket read error: %s", err)
123
+ finally:
124
+ self._stop_ping()
125
+ if self._ws and not self._ws.closed:
126
+ await self._ws.close()
127
+
128
+ def _stop_ping(self) -> None:
129
+ """Cancel ping task."""
130
+ if self._ping_task and not self._ping_task.done():
131
+ self._ping_task.cancel()
132
+ self._ping_task = None
133
+
134
+ async def _async_ping_loop(self) -> None:
135
+ """Send application-level ping every 55 seconds."""
136
+ try:
137
+ while self._ws and not self._ws.closed:
138
+ await asyncio.sleep(55)
139
+ if self._ws and not self._ws.closed:
140
+ await self._ws.send_json({"cmd": "ping"})
141
+ _LOGGER.debug("WebSocket ping sent")
142
+ except asyncio.CancelledError:
143
+ pass
144
+ except aiohttp.ClientError as err:
145
+ _LOGGER.error("WebSocket ping failed: %s", err)
146
+
147
+ async def _async_handle_message(self, message: dict[str, Any]) -> None:
148
+ """Handle incoming WebSocket message and dispatch to callbacks."""
149
+ cmd = message.get("cmd")
150
+ data = message.get("data", [])
151
+ _LOGGER.debug("WebSocket message: cmd=%s", cmd)
152
+
153
+ if cmd == "report.device.status":
154
+ self._handle_device_status(data)
155
+
156
+ elif cmd == "report.device.photo":
157
+ self._handle_device_photo(data)
158
+
159
+ elif cmd == "report.device.connected":
160
+ self._handle_device_connected(data)
161
+
162
+ elif cmd == "auth_error":
163
+ _LOGGER.warning("WebSocket auth error, triggering token refresh")
164
+ await self._on_token_expired()
165
+
166
+ elif cmd == "pong":
167
+ _LOGGER.debug("WebSocket pong received")
168
+
169
+ else:
170
+ _LOGGER.debug("WebSocket unknown cmd: %s", cmd)
171
+
172
+ def _handle_device_status(self, data: Any) -> None:
173
+ """Process device status report with field conversions."""
174
+ if not isinstance(data, list):
175
+ _LOGGER.warning("report.device.status data is not a list")
176
+ return
177
+ for device in data:
178
+ device_uuid = device.get("uuid")
179
+ status = device.get("status")
180
+ if not device_uuid or not status:
181
+ continue
182
+ # Field conversions
183
+ if "power" in status:
184
+ status["on"] = status["power"] == 1
185
+ if "is_locked" in status:
186
+ is_locked = status["is_locked"]
187
+ status["locked"] = is_locked == 2
188
+ status["jammed"] = is_locked == 3
189
+ if "battery_percent" in status:
190
+ status["battery"] = status["battery_percent"]
191
+ self._on_device_status(device_uuid, status)
192
+
193
+ def _handle_device_photo(self, data: Any) -> None:
194
+ """Process device photo/snapshot report."""
195
+ if not isinstance(data, list):
196
+ return
197
+ for device in data:
198
+ device_uuid = device.get("uuid")
199
+ photo = device.get("status", {}).get("photo")
200
+ if device_uuid and photo:
201
+ self._on_device_status(device_uuid, {"snapshot_url": photo})
202
+
203
+ def _handle_device_connected(self, data: Any) -> None:
204
+ """Process device online/offline report."""
205
+ if not isinstance(data, list):
206
+ return
207
+ for device in data:
208
+ device_uuid = device.get("uuid")
209
+ online = device.get("status", {}).get("online")
210
+ if device_uuid and online is not None:
211
+ self._on_device_status(device_uuid, {"online": online})
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: ha-xthings-cloud
3
+ Version: 1.0.0
4
+ Summary: Async Python client for Xthings Cloud API
5
+ Author-email: Xthings <dev@xthings.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/XthingsJacobs/ha-xthings-cloud
8
+ Project-URL: Repository, https://github.com/XthingsJacobs/ha-xthings-cloud
9
+ Project-URL: Issues, https://github.com/XthingsJacobs/ha-xthings-cloud/issues
10
+ Keywords: xthings,iot,smart-home,home-assistant
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Framework :: AsyncIO
20
+ Classifier: Topic :: Home Automation
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: aiohttp>=3.8.0
25
+ Dynamic: license-file
26
+
27
+ # ha-xthings-cloud
28
+
29
+ Async Python client for the [Xthings Cloud](https://cloud.xthings.com) API, designed for [Home Assistant](https://www.home-assistant.io/) integration.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install ha-xthings-cloud
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ### API Client
40
+
41
+ ```python
42
+ import aiohttp
43
+ from ha_xthings_cloud import XthingsCloudApiClient
44
+
45
+ async with aiohttp.ClientSession() as session:
46
+ client = XthingsCloudApiClient(session)
47
+
48
+ # Login (supports 2FA)
49
+ result = await client.async_login("user@example.com", "password")
50
+
51
+ # Get devices
52
+ devices = await client.async_get_devices()
53
+
54
+ # Control devices
55
+ await client.async_switch_on("device-uuid")
56
+ await client.async_brite_brightness("device-uuid", 80)
57
+ await client.async_lock_lock("device-uuid")
58
+ ```
59
+
60
+ ### WebSocket (Real-time Push)
61
+
62
+ ```python
63
+ from ha_xthings_cloud import XthingsCloudWebSocket
64
+
65
+ def on_status(device_uuid, status):
66
+ print(f"Device {device_uuid}: {status}")
67
+
68
+ async def on_token_expired():
69
+ # refresh token logic
70
+ pass
71
+
72
+ ws = XthingsCloudWebSocket(session, token, on_status, on_token_expired)
73
+ await ws.async_start()
74
+ ```
75
+
76
+ ### KVS Signaling (Camera WebRTC)
77
+
78
+ ```python
79
+ from ha_xthings_cloud import KvsSignalingClient
80
+
81
+ kvs = KvsSignalingClient(session, region, channel_arn, credentials)
82
+ answer_sdp = await kvs.async_get_answer_sdp(offer_sdp, on_ice_candidate=callback)
83
+ ```
84
+
85
+ ## Features
86
+
87
+ - Async HTTP client with `aiohttp.ClientSession` injection
88
+ - Authentication: login, token refresh, 2FA (email/phone)
89
+ - Device control: Switch, Plug, Light (brightness/HS color/color temp), Lock, Camera
90
+ - WebSocket: real-time device status push with auto-reconnect
91
+ - KVS Signaling: AWS Kinesis Video Streams WebRTC SDP exchange with SigV4 auth
92
+ - FRP remote access configuration
93
+
94
+ ## API Reference
95
+
96
+ ### XthingsCloudApiClient
97
+
98
+ | Method | Description |
99
+ |--------|-------------|
100
+ | `async_login(email, password, ...)` | Login with optional 2FA |
101
+ | `async_refresh_token(refresh_token)` | Refresh auth token |
102
+ | `async_get_devices()` | Get device list |
103
+ | `async_get_device_status(device_id)` | Get single device status |
104
+ | `async_switch_on/off(device_id)` | Switch control |
105
+ | `async_plug_on/off(device_id)` | Plug control |
106
+ | `async_brite_on/off(device_id)` | Light on/off |
107
+ | `async_brite_brightness(device_id, brightness)` | Light brightness (0-100) |
108
+ | `async_brite_color(device_id, color)` | Light color (HS/color temp) |
109
+ | `async_lock_lock/unlock(device_id)` | Lock control |
110
+ | `async_get_camera_webrtc(device_id)` | Get camera KVS credentials |
111
+ | `async_get_frp_config(client_id)` | Get FRP remote access config |
112
+
113
+ ### XthingsCloudWebSocket
114
+
115
+ | Method | Description |
116
+ |--------|-------------|
117
+ | `async_start()` | Start WebSocket with auto-reconnect |
118
+ | `async_stop()` | Stop WebSocket connection |
119
+
120
+ ### KvsSignalingClient
121
+
122
+ | Method | Description |
123
+ |--------|-------------|
124
+ | `async_get_answer_sdp(offer_sdp, on_ice_candidate)` | SDP offer/answer exchange |
125
+ | `async_send_ice_candidate(candidate, sdp_mid, sdp_mline_index)` | Send ICE candidate |
126
+ | `async_get_ice_server_config()` | Get TURN/STUN servers |
127
+ | `async_close()` | Close signaling connection |
128
+
129
+ ## License
130
+
131
+ Apache-2.0
@@ -0,0 +1,11 @@
1
+ ha_xthings_cloud/__init__.py,sha256=LBtPLU78LFhXVxFoGXOaZLG2qtKh7LTcXH-mYJKa2fk,481
2
+ ha_xthings_cloud/client.py,sha256=IfUD6f9zzxN9clkqTbKayh8aI1hl8rAUVMbE724_6cM,7638
3
+ ha_xthings_cloud/const.py,sha256=KgZuVIPA9a8wSmSQVPmql6hQARgle46-bvj1S5jWsRQ,1360
4
+ ha_xthings_cloud/exceptions.py,sha256=Umo9Nw575qHqGHywcYrmsiX9BeFd-MCAsrNasVMIlY4,373
5
+ ha_xthings_cloud/kvs_signaling.py,sha256=ILTyxwByESh2qn9nFZeW1ADUTh5MNQkUdlCj4VFwqf8,13057
6
+ ha_xthings_cloud/websocket.py,sha256=DuMIIcbbcMvZrE-P08qj_niXHBkW18pPaSNNHhbiNzg,7821
7
+ ha_xthings_cloud-1.0.0.dist-info/licenses/LICENSE,sha256=T2jgFVW-N7KOwRL0tcc5EWZptSRIbfbAtklA7qTwEKo,741
8
+ ha_xthings_cloud-1.0.0.dist-info/METADATA,sha256=FBH45vIJhnQbl6be4fTK8h5nCOYXLqLNajeyA8NH7nA,4209
9
+ ha_xthings_cloud-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ ha_xthings_cloud-1.0.0.dist-info/top_level.txt,sha256=mkSddGmzBPXYWKAuRcVjNi1IwNlP94CzqT82jeWsuyA,17
11
+ ha_xthings_cloud-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,17 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+
17
+ Copyright 2026 Xthings Inc.
@@ -0,0 +1 @@
1
+ ha_xthings_cloud