dglab-kit-python 0.1.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,783 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ from dglab_kit_python.errors import create_named_error
8
+ from dglab_kit_python.socket.base import DglabSocketBase
9
+ from dglab_kit_python.types import (
10
+ V4ActionType,
11
+ V4AppendPulseDataOptions,
12
+ V4Channel,
13
+ V4ClearOperateOptions,
14
+ V4DeviceInfo,
15
+ V4OperateOptions,
16
+ DglabSocketCloseEvent,
17
+ DglabSocketState,
18
+ )
19
+
20
+ DEFAULT_RESPONSE_TIMEOUT = 8_000
21
+ SERVER_PING_INTERVAL = 2.0
22
+ MAX_MISSED_SERVER_PONGS = 3
23
+
24
+
25
+ def _is_record(value: Any) -> bool:
26
+ return isinstance(value, dict)
27
+
28
+
29
+ _DEVICE_PATCH_UNCHANGED = object()
30
+ _MISSING = object()
31
+
32
+
33
+ def _merge_patch(current: Any, patch: Any) -> Any:
34
+ if not isinstance(current, dict) or not isinstance(patch, dict):
35
+ return patch
36
+
37
+ next_value = dict(current)
38
+ for key, value in patch.items():
39
+ next_value[key] = _merge_patch(current.get(key), value)
40
+ return next_value
41
+
42
+
43
+ def _create_patch_value(previous: Any, current: Any) -> Any:
44
+ if previous == current:
45
+ return _DEVICE_PATCH_UNCHANGED
46
+
47
+ if not isinstance(previous, dict) or not isinstance(current, dict):
48
+ return current
49
+
50
+ patch: dict[str, Any] = {}
51
+ for key in set(previous.keys()) | set(current.keys()):
52
+ value = current.get(key) if key in current else None
53
+ child_patch = _create_patch_value(previous.get(key), value)
54
+ if child_patch is not _DEVICE_PATCH_UNCHANGED:
55
+ patch[key] = child_patch
56
+
57
+ return patch if patch else _DEVICE_PATCH_UNCHANGED
58
+
59
+
60
+ class V4Client:
61
+ def __init__(self, clientId: str, devices: list[V4DeviceInfo] | None = None) -> None:
62
+ self.clientId = clientId
63
+ self.devices: list[V4DeviceInfo] = list(devices or [])
64
+
65
+ def get_device(self, slotId: str) -> V4DeviceInfo | None:
66
+ return next((device for device in self.devices if device.get("slotId") == slotId), None)
67
+
68
+ getDevice = get_device
69
+
70
+ def dispatch(self, data: Any) -> bool:
71
+ if self._update_devices_from_event(data):
72
+ return True
73
+ if not V4Rpc.is_response(data):
74
+ return False
75
+ return self._update_devices_from_response(data.get("result"))
76
+
77
+ def replace_devices(self, devices: list[dict[str, Any]]) -> None:
78
+ self.devices[:] = [dict(device) for device in devices] # type: ignore[list-item]
79
+
80
+ replaceDevices = replace_devices
81
+
82
+ def upsert_device(self, device: V4DeviceInfo) -> None:
83
+ index = self._find_device_index(device["slotId"])
84
+ if index == -1:
85
+ self.devices.append(device)
86
+ else:
87
+ self.devices[index] = device
88
+
89
+ upsertDevice = upsert_device
90
+
91
+ def remove_device(self, slotId: str) -> None:
92
+ index = self._find_device_index(slotId)
93
+ if index != -1:
94
+ self.devices.pop(index)
95
+
96
+ removeDevice = remove_device
97
+
98
+ def patch_devices(
99
+ self, added: list[V4DeviceInfo] | None = None, removed: list[str] | None = None
100
+ ) -> None:
101
+ for device in added or []:
102
+ self.upsert_device(device)
103
+ for slotId in removed or []:
104
+ self.remove_device(slotId)
105
+
106
+ patchDevices = patch_devices
107
+
108
+ def patch_slots(self, slots: list[dict[str, Any]] | None = None) -> None:
109
+ for slot in slots or []:
110
+ slotId = slot.get("slotId")
111
+ if not isinstance(slotId, str):
112
+ continue
113
+ index = self._find_device_index(slotId)
114
+ if index == -1:
115
+ continue
116
+
117
+ current = self.devices[index]
118
+ next_device = dict(current)
119
+ next_device["props"] = _merge_patch(
120
+ current.get("props") or {},
121
+ slot.get("props") or {},
122
+ )
123
+ next_device["slotState"] = _merge_patch(
124
+ current.get("slotState") or {},
125
+ slot.get("slotState") or {},
126
+ )
127
+ self.devices[index] = next_device # type: ignore[assignment]
128
+
129
+ patchSlots = patch_slots
130
+
131
+ def destroy(self) -> None:
132
+ self.devices.clear()
133
+
134
+ def _update_devices_from_event(self, data: Any) -> bool:
135
+ if not (_is_record(data) and data.get("t") == "ev" and isinstance(data.get("ev"), str)):
136
+ return False
137
+
138
+ if data["ev"] == "devices.snapshot":
139
+ self.replace_devices(data.get("devices") or [])
140
+ return True
141
+ if data["ev"] == "devices.patch":
142
+ self.patch_devices(data.get("added") or [], data.get("removed") or [])
143
+ return True
144
+ if data["ev"] == "slots.patch":
145
+ self.patch_slots(data.get("slots") or [])
146
+ return True
147
+ return False
148
+
149
+ def _update_devices_from_response(self, result: Any) -> bool:
150
+ if not (_is_record(result) and isinstance(result.get("devices"), list)):
151
+ return False
152
+ self.replace_devices(result["devices"])
153
+ return True
154
+
155
+ def _find_device_index(self, slotId: str) -> int:
156
+ for index, device in enumerate(self.devices):
157
+ if device.get("slotId") == slotId:
158
+ return index
159
+ return -1
160
+
161
+
162
+ @dataclass
163
+ class _PendingResponse:
164
+ clientId: str
165
+ requestId: str
166
+ future: asyncio.Future[Any]
167
+ timer: asyncio.TimerHandle | None = None
168
+ settled: bool = False
169
+
170
+
171
+ class V4SendFuture(asyncio.Future[Any]):
172
+ """Awaitable V4 result with the same request identifiers as the JS promise."""
173
+
174
+ def __init__(self, request_id: str, client_id: str) -> None:
175
+ super().__init__()
176
+ self.requestId = self.request_id = request_id
177
+ self.clientId = self.client_id = client_id
178
+
179
+
180
+ class V4Rpc:
181
+ def __init__(
182
+ self,
183
+ send_frame: Any,
184
+ *,
185
+ responseTimeout: int | None = None,
186
+ response_timeout: int | None = None,
187
+ **_: Any,
188
+ ) -> None:
189
+ self._pending: dict[str, _PendingResponse] = {}
190
+ self._send_frame = send_frame
191
+ self._request_id_counter = 0
192
+ self._response_timeout = response_timeout if response_timeout is not None else responseTimeout
193
+
194
+ def create_request(self, method: str, data: Any = _MISSING) -> dict[str, Any]:
195
+ requestId = self._create_request_id()
196
+ request = {"t": "req", "reqId": requestId, "m": method}
197
+ if data is not _MISSING:
198
+ request["data"] = data
199
+ return request
200
+
201
+ createRequest = create_request
202
+
203
+ def send(
204
+ self, clientId: str, data: Any, options: dict[str, Any] | None = None
205
+ ) -> V4SendFuture:
206
+ if not clientId:
207
+ raise create_named_error("socket-clientId", "发送协议数据需要指定 clientId")
208
+
209
+ loop = asyncio.get_running_loop()
210
+ requestId = self.get_request_id(data)
211
+ if requestId is None:
212
+ requestId = self._create_request_id()
213
+
214
+ if _is_record(data):
215
+ payload = {**data, "reqId": requestId}
216
+ payload.pop("requestId", None)
217
+ else:
218
+ payload = {
219
+ "t": "req",
220
+ "reqId": requestId,
221
+ "m": "custom",
222
+ "data": data,
223
+ }
224
+
225
+ waitable_request_id = self.get_request_id(payload)
226
+ if waitable_request_id is None:
227
+ future = V4SendFuture(requestId, clientId)
228
+ future.set_exception(create_named_error("socket-command", "当前消息没有可等待响应"))
229
+ return future
230
+
231
+ key = self._pending_key(clientId, waitable_request_id)
232
+ future = V4SendFuture(requestId, clientId)
233
+ pending = _PendingResponse(clientId, waitable_request_id, future)
234
+ pending.timer = loop.call_later(
235
+ self._response_timeout_seconds(options),
236
+ self._timeout_pending,
237
+ key,
238
+ pending,
239
+ )
240
+ self._pending[key] = pending
241
+
242
+ try:
243
+ self._send_frame({"type": "message", "clientId": clientId, "data": payload})
244
+ except Exception as error:
245
+ self._pending.pop(key, None)
246
+ self._reject_pending(pending, error)
247
+
248
+ return future
249
+
250
+ def send_operate(
251
+ self, clientId: str, data: dict[str, Any], options: dict[str, Any] | None = None
252
+ ) -> V4SendFuture:
253
+ timeout = self._operate_response_timeout(data, options)
254
+ return self.send(
255
+ clientId,
256
+ self.create_request("device.op", data),
257
+ None if timeout is None else {"timeout": timeout},
258
+ )
259
+
260
+ sendOperate = send_operate
261
+
262
+ def resolve_response(self, clientId: str, response: dict[str, Any]) -> None:
263
+ requestId = self.get_request_id(response)
264
+ if not requestId:
265
+ return
266
+
267
+ key = self._pending_key(clientId, requestId)
268
+ entry = self._pending.pop(key, None)
269
+ if entry is None:
270
+ return
271
+
272
+ if response.get("error"):
273
+ self._reject_pending(
274
+ entry,
275
+ create_named_error("socket-v4-response", response.get("error") or "V4 指令执行失败"),
276
+ )
277
+ return
278
+
279
+ if entry.settled:
280
+ return
281
+ entry.settled = True
282
+ if entry.timer is not None:
283
+ entry.timer.cancel()
284
+ if not entry.future.done():
285
+ entry.future.set_result(response.get("result"))
286
+
287
+ resolveResponse = resolve_response
288
+
289
+ def reject_client_pending(self, clientId: str) -> None:
290
+ for key, entry in list(self._pending.items()):
291
+ if entry.clientId != clientId:
292
+ continue
293
+ self._pending.pop(key, None)
294
+ self._reject_pending(entry, create_named_error("socket-disconnected", "被控方已断开"))
295
+
296
+ rejectClientPending = reject_client_pending
297
+
298
+ def reject_all_pending(self, error: Exception) -> None:
299
+ for entry in list(self._pending.values()):
300
+ self._reject_pending(entry, error)
301
+ self._pending.clear()
302
+
303
+ rejectAllPending = reject_all_pending
304
+
305
+ @staticmethod
306
+ def is_response(data: Any) -> bool:
307
+ return _is_record(data) and data.get("t") == "resp"
308
+
309
+ isResponse = is_response
310
+
311
+ @staticmethod
312
+ def get_request_id(data: Any) -> str | None:
313
+ if not _is_record(data):
314
+ return None
315
+ requestId = data.get("requestId")
316
+ if isinstance(requestId, str):
317
+ return requestId
318
+ reqId = data.get("reqId")
319
+ return reqId if isinstance(reqId, str) else None
320
+
321
+ getRequestId = get_request_id
322
+
323
+ def _create_request_id(self) -> str:
324
+ self._request_id_counter += 1
325
+ return str(self._request_id_counter)
326
+
327
+ def _response_timeout_seconds(self, options: dict[str, Any] | None = None) -> float:
328
+ option_timeout = (options or {}).get("timeout")
329
+ timeout = (
330
+ option_timeout
331
+ if option_timeout is not None
332
+ else self._response_timeout
333
+ if self._response_timeout is not None
334
+ else DEFAULT_RESPONSE_TIMEOUT
335
+ )
336
+ return timeout / 1000
337
+
338
+ def _operate_response_timeout(
339
+ self, data: dict[str, Any], options: dict[str, Any] | None = None
340
+ ) -> int | float | None:
341
+ option_timeout = (options or {}).get("timeout")
342
+ if option_timeout is not None:
343
+ return option_timeout
344
+ if self._response_timeout is not None:
345
+ return None
346
+
347
+ duration = data.get("d")
348
+ if isinstance(duration, int | float) and duration > DEFAULT_RESPONSE_TIMEOUT:
349
+ return duration + 1000
350
+ return None
351
+
352
+ def _pending_key(self, clientId: str, requestId: str) -> str:
353
+ return f"{clientId}\0{requestId}"
354
+
355
+ def _timeout_pending(self, key: str, pending: _PendingResponse) -> None:
356
+ self._pending.pop(key, None)
357
+ self._reject_pending(pending, create_named_error("socket-response-timeout", "等待响应超时"))
358
+
359
+ @staticmethod
360
+ def _reject_pending(entry: _PendingResponse, error: Exception) -> None:
361
+ if entry.settled:
362
+ return
363
+ entry.settled = True
364
+ if entry.timer is not None:
365
+ entry.timer.cancel()
366
+ if not entry.future.done():
367
+ entry.future.set_exception(error)
368
+
369
+
370
+ class DglabSocketV4(DglabSocketBase):
371
+ def __init__(self, **options: Any) -> None:
372
+ super().__init__(**options)
373
+ self._targetId: str | None = None
374
+ self._client_map: dict[str, V4Client] = {}
375
+ self.rpc = V4Rpc(self.send_frame, **options)
376
+ self._server_ping_task: asyncio.Task[None] | None = None
377
+ self._missed_server_pongs = 0
378
+
379
+ @property
380
+ def targetId(self) -> str | None:
381
+ return self._targetId
382
+
383
+ @property
384
+ def target_id(self) -> str | None:
385
+ return self._targetId
386
+
387
+ @property
388
+ def clientIds(self) -> list[str]:
389
+ return list(self._client_map)
390
+
391
+ @property
392
+ def client_ids(self) -> list[str]:
393
+ return self.clientIds
394
+
395
+ @property
396
+ def clients(self) -> list[V4Client]:
397
+ return list(self._client_map.values())
398
+
399
+ def get_client(self, clientId: str) -> V4Client | None:
400
+ return self._client_map.get(clientId)
401
+
402
+ getClient = get_client
403
+
404
+ async def request_devices(self, clientId: str) -> dict[str, Any]:
405
+ result = await self.rpc.send(clientId, self.rpc.create_request("devices.get"))
406
+ client = self._ensure_client(clientId)
407
+ if client.dispatch({"t": "resp", "result": result}):
408
+ self.emit("devices", client.devices, client.clientId)
409
+ return result
410
+
411
+ requestDevices = request_devices
412
+
413
+ def send(
414
+ self, clientId: str, data: Any, options: dict[str, Any] | None = None
415
+ ) -> V4SendFuture:
416
+ return self.rpc.send(clientId, data, options)
417
+
418
+ def ping(
419
+ self, clientId: str, options: dict[str, Any] | None = None
420
+ ) -> V4SendFuture:
421
+ return self.rpc.send(clientId, self.rpc.create_request("ping"), options)
422
+
423
+ async def disconnect(self, code: int | None = None, reason: str | None = None) -> None:
424
+ self._stop_server_ping()
425
+ await super().disconnect(code, reason)
426
+
427
+ def add_intensity(
428
+ self,
429
+ clientId: str,
430
+ slotId: str,
431
+ channel: V4Channel | int,
432
+ value: int | float,
433
+ options: V4OperateOptions | None = None,
434
+ ) -> V4SendFuture:
435
+ return self.rpc.send_operate(
436
+ clientId,
437
+ {
438
+ **self._create_operate_base(slotId, channel, options),
439
+ "t": V4ActionType.ADD_INTENSITY,
440
+ "v": value,
441
+ },
442
+ options,
443
+ )
444
+
445
+ addIntensity = add_intensity
446
+
447
+ def reduce_strength(
448
+ self,
449
+ clientId: str,
450
+ slotId: str,
451
+ channel: V4Channel | int,
452
+ value: int | float,
453
+ options: V4OperateOptions | None = None,
454
+ ) -> V4SendFuture:
455
+ return self.add_intensity(clientId, slotId, channel, -value, options)
456
+
457
+ reduceStrength = reduce_strength
458
+
459
+ def set_temp_intensity(
460
+ self,
461
+ clientId: str,
462
+ slotId: str,
463
+ channel: V4Channel | int,
464
+ value: int | float,
465
+ duration: int | float,
466
+ options: V4OperateOptions | None = None,
467
+ ) -> V4SendFuture:
468
+ return self.rpc.send_operate(
469
+ clientId,
470
+ {
471
+ **self._create_operate_base(slotId, channel, options),
472
+ "t": V4ActionType.SET_TEMP_INTENSITY,
473
+ "v": value,
474
+ "d": duration,
475
+ },
476
+ options,
477
+ )
478
+
479
+ setTempIntensity = set_temp_intensity
480
+
481
+ def reset_intensity(
482
+ self,
483
+ clientId: str,
484
+ slotId: str,
485
+ channel: V4Channel | int,
486
+ options: V4OperateOptions | None = None,
487
+ ) -> V4SendFuture:
488
+ return self.rpc.send_operate(
489
+ clientId,
490
+ {
491
+ **self._create_operate_base(slotId, channel, options),
492
+ "t": V4ActionType.SET_INTENSITY,
493
+ "v": 0,
494
+ },
495
+ options,
496
+ )
497
+
498
+ resetIntensity = reset_intensity
499
+
500
+ def send_pulse(
501
+ self,
502
+ clientId: str,
503
+ slotId: str,
504
+ channel: V4Channel | int,
505
+ duration: int | float,
506
+ frames: list[list[int]] | list[str],
507
+ options: V4AppendPulseDataOptions | None = None,
508
+ ) -> V4SendFuture:
509
+ options = options or {}
510
+ payload = {
511
+ **self._create_operate_base(slotId, channel, options),
512
+ "t": V4ActionType.APPEND_PULSE_DATA,
513
+ "d": duration,
514
+ "v": frames,
515
+ }
516
+ if "version" in options:
517
+ payload["ver"] = options["version"]
518
+ if "seq" in options:
519
+ payload["seq"] = options["seq"]
520
+ return self.rpc.send_operate(clientId, payload, options)
521
+
522
+ sendPulse = send_pulse
523
+
524
+ def clear_pulse(
525
+ self, clientId: str, slotId: str, channel: V4Channel | int
526
+ ) -> V4SendFuture:
527
+ return self.clear_operate(clientId, {"slotId": slotId, "channel": channel})
528
+
529
+ clearPulse = clear_pulse
530
+
531
+ def clear_operate(
532
+ self, clientId: str, options: V4ClearOperateOptions | None = None
533
+ ) -> V4SendFuture:
534
+ data: Any = _MISSING
535
+ if options:
536
+ slot_id = options.get("slot_id") or options.get("slotId") # type: ignore[typeddict-item]
537
+ if slot_id:
538
+ data = {"s": slot_id}
539
+ if "channel" in options:
540
+ data["c"] = options["channel"]
541
+ return self.rpc.send(clientId, self.rpc.create_request("device.op.clear", data))
542
+
543
+ clearOperate = clear_operate
544
+
545
+ def _handle_protocol_message(self, text: str, raw: Any) -> None:
546
+ try:
547
+ frame = __import__("json").loads(text)
548
+ except Exception:
549
+ return
550
+ if not _is_record(frame):
551
+ return
552
+
553
+ self.emit("frame", frame)
554
+ frame_type = frame.get("type")
555
+
556
+ if frame_type == "hello":
557
+ self._handle_hello(frame)
558
+ elif frame_type == "client_attached":
559
+ clientId = frame.get("clientId")
560
+ if isinstance(clientId, str):
561
+ self._set_state(DglabSocketState.PAIRED)
562
+ self._ensure_client(clientId)
563
+ self.emit("client-attached", clientId)
564
+ elif frame_type == "client_disconnected":
565
+ clientId = frame.get("clientId")
566
+ if isinstance(clientId, str):
567
+ self._handle_client_disconnected(clientId)
568
+ elif frame_type == "message":
569
+ self._handle_message_frame(frame)
570
+ elif frame_type == "pong":
571
+ self._missed_server_pongs = 0
572
+ elif frame_type == "idle_timeout":
573
+ self.handle_error(create_named_error("socket-idle-timeout", "控制方空闲超时"))
574
+ elif frame_type == "error":
575
+ self.handle_error(
576
+ create_named_error(
577
+ "socket-v4-server",
578
+ frame["message"] if frame.get("message") is not None else frame.get("code"),
579
+ )
580
+ )
581
+
582
+ def _on_socket_closed(self, _event: DglabSocketCloseEvent) -> None:
583
+ self._stop_server_ping()
584
+ self._targetId = None
585
+ for client in self._client_map.values():
586
+ client.destroy()
587
+ self._client_map.clear()
588
+ self.rpc.reject_all_pending(create_named_error("socket-disconnected", "WebSocket 已断开"))
589
+
590
+ def _get_connected_result(self) -> dict[str, Any] | None:
591
+ if not self._targetId:
592
+ return None
593
+ return {"targetId": self._targetId}
594
+
595
+ def _handle_hello(self, frame: dict[str, Any]) -> None:
596
+ clientId = frame.get("clientId")
597
+ if not isinstance(clientId, str):
598
+ return
599
+ self._targetId = clientId
600
+ self._set_state(DglabSocketState.WAITING_FOR_PEER)
601
+ self._start_server_ping()
602
+ self._resolve_active_connect({"targetId": clientId})
603
+
604
+ def _handle_client_disconnected(self, clientId: str) -> None:
605
+ self._detach_client(clientId)
606
+ self.rpc.reject_client_pending(clientId)
607
+ if not self._client_map:
608
+ self._set_state(DglabSocketState.WAITING_FOR_PEER)
609
+ self.emit("client-disconnected", clientId)
610
+
611
+ def _handle_message_frame(self, frame: dict[str, Any]) -> None:
612
+ clientId = frame.get("clientId")
613
+ if not isinstance(clientId, str):
614
+ return
615
+ data = frame.get("data")
616
+ self.emit("data", data, clientId)
617
+
618
+ if self._is_custom_action_event(data):
619
+ self.emit("action", data["action"])
620
+
621
+ client = self._client_map.get(clientId)
622
+ for event in self._create_device_events(data, client):
623
+ self.emit("device", event, clientId)
624
+
625
+ if client is not None and client.dispatch(data):
626
+ self.emit("devices", client.devices, client.clientId)
627
+
628
+ if V4Rpc.is_response(data):
629
+ self.rpc.resolve_response(clientId, data)
630
+
631
+ def _ensure_client(self, clientId: str) -> V4Client:
632
+ client = self._client_map.get(clientId)
633
+ if client is None:
634
+ client = V4Client(clientId)
635
+ self._client_map[clientId] = client
636
+ return client
637
+
638
+ def _detach_client(self, clientId: str) -> None:
639
+ client = self._client_map.pop(clientId, None)
640
+ if client is not None:
641
+ client.destroy()
642
+
643
+ def _start_server_ping(self) -> None:
644
+ self._stop_server_ping()
645
+ self._missed_server_pongs = 0
646
+ self._server_ping_task = asyncio.create_task(self._run_server_ping())
647
+
648
+ def _stop_server_ping(self) -> None:
649
+ task = self._server_ping_task
650
+ self._server_ping_task = None
651
+ self._missed_server_pongs = 0
652
+ if task is None or task.done():
653
+ return
654
+
655
+ current_task: asyncio.Task[Any] | None
656
+ try:
657
+ current_task = asyncio.current_task()
658
+ except RuntimeError:
659
+ current_task = None
660
+ if task is not current_task:
661
+ task.cancel()
662
+
663
+ async def _run_server_ping(self) -> None:
664
+ try:
665
+ while True:
666
+ await asyncio.sleep(SERVER_PING_INTERVAL)
667
+ if self._missed_server_pongs >= MAX_MISSED_SERVER_PONGS:
668
+ await self._disconnect_for_server_ping_timeout()
669
+ return
670
+
671
+ try:
672
+ self.send_frame({"type": "ping"})
673
+ self._missed_server_pongs += 1
674
+ except Exception as error:
675
+ self.handle_error(error)
676
+ await self._disconnect_for_server_ping_timeout()
677
+ return
678
+ except asyncio.CancelledError:
679
+ raise
680
+
681
+ async def _disconnect_for_server_ping_timeout(self) -> None:
682
+ self._stop_server_ping()
683
+ self.handle_error(create_named_error("socket-ping-timeout", "服务端 ping 超时"))
684
+ await super().disconnect(1000, "ping_timeout")
685
+
686
+ def _create_device_events(
687
+ self, data: Any, client: V4Client | None
688
+ ) -> list[dict[str, Any]]:
689
+ if not (_is_record(data) and data.get("t") == "ev"):
690
+ return []
691
+
692
+ if data.get("ev") == "devices.snapshot":
693
+ devices = data.get("devices") if isinstance(data.get("devices"), list) else []
694
+ changed = [
695
+ event
696
+ for device in devices
697
+ if isinstance(device, dict)
698
+ for event in [self._create_device_upsert_event(device, client)]
699
+ if event is not None
700
+ ]
701
+ next_slot_ids = {
702
+ device.get("slotId") for device in devices if isinstance(device, dict) and isinstance(device.get("slotId"), str)
703
+ }
704
+ removed = [
705
+ {"slotId": device["slotId"], "removed": True}
706
+ for device in (client.devices if client is not None else [])
707
+ if device.get("slotId") not in next_slot_ids
708
+ ]
709
+ return changed + removed
710
+
711
+ if data.get("ev") == "devices.patch":
712
+ added = data.get("added") if isinstance(data.get("added"), list) else []
713
+ removed = data.get("removed") if isinstance(data.get("removed"), list) else []
714
+ changed = [
715
+ event
716
+ for device in added
717
+ if isinstance(device, dict)
718
+ for event in [self._create_device_upsert_event(device, client)]
719
+ if event is not None
720
+ ]
721
+ return changed + [
722
+ {"slotId": slot_id, "removed": True}
723
+ for slot_id in removed
724
+ if isinstance(slot_id, str)
725
+ ]
726
+
727
+ if data.get("ev") == "slots.patch":
728
+ slots = data.get("slots") if isinstance(data.get("slots"), list) else []
729
+ return [slot for slot in slots if isinstance(slot, dict)]
730
+
731
+ return []
732
+
733
+ def _create_device_upsert_event(
734
+ self, device: dict[str, Any], client: V4Client | None
735
+ ) -> dict[str, Any] | None:
736
+ slotId = device.get("slotId")
737
+ if not isinstance(slotId, str):
738
+ return None
739
+
740
+ previous = client.get_device(slotId) if client is not None else None
741
+ if previous is None:
742
+ return dict(device)
743
+
744
+ event: dict[str, Any] = {"slotId": slotId}
745
+ if previous.get("name") != device.get("name"):
746
+ event["name"] = device.get("name")
747
+ if previous.get("type") != device.get("type"):
748
+ event["type"] = device.get("type")
749
+ props_patch = _create_patch_value(previous.get("props"), device.get("props"))
750
+ if props_patch is not _DEVICE_PATCH_UNCHANGED:
751
+ event["props"] = props_patch
752
+ slot_state_patch = _create_patch_value(
753
+ previous.get("slotState"),
754
+ device.get("slotState"),
755
+ )
756
+ if slot_state_patch is not _DEVICE_PATCH_UNCHANGED:
757
+ event["slotState"] = slot_state_patch
758
+
759
+ return event if len(event) > 1 else None
760
+
761
+ @staticmethod
762
+ def _is_custom_action_event(data: Any) -> bool:
763
+ return (
764
+ _is_record(data)
765
+ and data.get("t") == "ev"
766
+ and data.get("ev") == "custom.action"
767
+ and type(data.get("action")) in (int, float)
768
+ )
769
+
770
+ @staticmethod
771
+ def _create_operate_base(
772
+ slotId: str, channel: V4Channel | int, options: dict[str, Any] | None = None
773
+ ) -> dict[str, Any]:
774
+ options = options or {}
775
+ payload = {
776
+ "s": slotId,
777
+ "c": int(channel),
778
+ }
779
+ if "priority" in options:
780
+ payload["p"] = options["priority"]
781
+ if "immediate" in options:
782
+ payload["im"] = options["immediate"]
783
+ return payload