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,248 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ from dglab_kit_python.errors import create_named_error
7
+ from dglab_kit_python.socket.base import DglabSocketBase
8
+ from dglab_kit_python.types import (
9
+ DglabSocketCloseEvent,
10
+ DglabSocketDeviceType,
11
+ DglabSocketState,
12
+ V3Channel,
13
+ V3WaveOptions,
14
+ )
15
+
16
+
17
+ class DglabSocketV3(DglabSocketBase):
18
+ def __init__(self, **options: Any) -> None:
19
+ super().__init__(**options)
20
+ self._targetId: str | None = None
21
+ self._paired_target_id: str | None = None
22
+ self._device: dict[str, Any] | None = None
23
+
24
+ @property
25
+ def targetId(self) -> str | None:
26
+ return self._targetId
27
+
28
+ @property
29
+ def target_id(self) -> str | None:
30
+ return self._targetId
31
+
32
+ @property
33
+ def pairedClientId(self) -> str | None:
34
+ return self._paired_target_id
35
+
36
+ @property
37
+ def paired_client_id(self) -> str | None:
38
+ return self._paired_target_id
39
+
40
+ def send(self, data: Any) -> None:
41
+ if not self._targetId or not self._paired_target_id:
42
+ raise create_named_error("socket-target", "V3 尚未完成配对")
43
+
44
+ # TS spreads the supplied value into the outgoing command object.
45
+ if isinstance(data, dict):
46
+ payload = dict(data)
47
+ elif isinstance(data, (str, list, tuple)):
48
+ payload = {str(index): value for index, value in enumerate(data)}
49
+ else:
50
+ payload = {}
51
+ payload.update({"clientId": self._targetId, "targetId": self._paired_target_id})
52
+ self.send_frame(payload)
53
+
54
+ def add_strength(self, channel: V3Channel | int, step: int = 1) -> None:
55
+ command_type = 2 if step >= 0 else 1
56
+ count = max(1, abs(step))
57
+ channel_value = int(channel)
58
+
59
+ if count > 200:
60
+ raise create_named_error("socket-v3", "单次调整强度过大")
61
+
62
+ for _ in range(count):
63
+ self.send({"type": command_type, "channel": channel_value, "message": "set channel"})
64
+
65
+ addStrength = add_strength
66
+
67
+ def reduce_strength(self, channel: V3Channel | int, step: int = 1) -> None:
68
+ self.add_strength(channel, -step)
69
+
70
+ reduceStrength = reduce_strength
71
+
72
+ def set_strength(self, channel: V3Channel | int, strength: int | float) -> None:
73
+ self.send(
74
+ {
75
+ "type": 3,
76
+ "channel": int(channel),
77
+ "strength": strength,
78
+ "message": "set channel",
79
+ }
80
+ )
81
+
82
+ setStrength = set_strength
83
+
84
+ def clear_pulse(self, channel: V3Channel | int) -> None:
85
+ self.send({"type": 4, "channel": int(channel), "message": "clear"})
86
+
87
+ clearPulse = clear_pulse
88
+
89
+ def send_pulse(self, options: V3WaveOptions) -> None:
90
+ data = options["data"]
91
+ payload = json.dumps(data, ensure_ascii=False, separators=(",", ":")) if isinstance(data, list) else data
92
+ channel = options["channel"]
93
+ self.send(
94
+ {
95
+ "type": "clientMsg",
96
+ "channel": channel,
97
+ "time": options["time"],
98
+ "message": f"{channel}:{payload}",
99
+ }
100
+ )
101
+
102
+ sendPulse = send_pulse
103
+
104
+ def _handle_protocol_message(self, text: str, raw: Any) -> None:
105
+ try:
106
+ frame = json.loads(text)
107
+ except Exception:
108
+ self.emit("data", text)
109
+ return
110
+
111
+ if not isinstance(frame, dict):
112
+ self.emit("data", frame)
113
+ return
114
+
115
+ self.emit("frame", frame)
116
+ frame_type = frame.get("type")
117
+
118
+ if frame_type == "bind":
119
+ clientId = frame.get("clientId")
120
+ targetId = frame.get("targetId")
121
+ if isinstance(clientId, str) and ("targetId" not in frame or targetId == ""):
122
+ self._handle_initial_bind(clientId)
123
+ return
124
+ if isinstance(clientId, str) and isinstance(targetId, str) and frame.get("message") == "200":
125
+ self._handle_pair_bind(targetId)
126
+ return
127
+ elif frame_type == "break":
128
+ self._paired_target_id = None
129
+ self._device = None
130
+ self._set_state(DglabSocketState.WAITING_FOR_PEER)
131
+ targetId = frame.get("targetId")
132
+ if isinstance(targetId, str):
133
+ self._emit_device(
134
+ {"type": DglabSocketDeviceType.COYOTE_030, "removed": True},
135
+ targetId,
136
+ )
137
+ self.emit("client-disconnected", targetId)
138
+ return
139
+ elif frame_type == "msg" or frame_type == 4:
140
+ self._handle_forward_message(frame)
141
+ return
142
+ elif frame_type == "error":
143
+ self.handle_error(
144
+ create_named_error(
145
+ "socket-v3-server",
146
+ frame.get("message") if isinstance(frame.get("message"), str) else "V3 服务端错误",
147
+ )
148
+ )
149
+ return
150
+
151
+ self.emit(
152
+ "data",
153
+ frame.get("message") if "message" in frame else frame,
154
+ frame.get("targetId") if isinstance(frame.get("targetId"), str) else None,
155
+ )
156
+
157
+ def _on_socket_closed(self, _event: DglabSocketCloseEvent) -> None:
158
+ self._targetId = None
159
+ self._paired_target_id = None
160
+ self._device = None
161
+
162
+ def _get_connected_result(self) -> dict[str, Any] | None:
163
+ if not self._targetId:
164
+ return None
165
+ return {"targetId": self._targetId}
166
+
167
+ def _handle_initial_bind(self, clientId: str) -> None:
168
+ self._targetId = clientId
169
+ self._set_state(DglabSocketState.WAITING_FOR_PEER)
170
+ self._resolve_active_connect({"targetId": clientId})
171
+
172
+ def _handle_pair_bind(self, targetId: str) -> None:
173
+ self._paired_target_id = targetId
174
+ self._set_state(DglabSocketState.PAIRED)
175
+ self._device = self._create_device()
176
+ self._emit_device(self._device, targetId)
177
+ self.emit("client-attached", targetId)
178
+
179
+ def _handle_forward_message(self, frame: dict[str, Any]) -> None:
180
+ message = frame.get("message")
181
+ if isinstance(message, str):
182
+ action = self._parse_action_message(message)
183
+ if action is not None:
184
+ self.emit("action", action)
185
+
186
+ device = self._parse_device_message(message)
187
+ if device is not None:
188
+ self._emit_device(device)
189
+
190
+ self.emit(
191
+ "data",
192
+ frame.get("message") if "message" in frame else frame,
193
+ frame.get("targetId") if isinstance(frame.get("targetId"), str) else None,
194
+ )
195
+
196
+ @staticmethod
197
+ def _parse_action_message(message: str) -> int | None:
198
+ import re
199
+
200
+ match = re.fullmatch(r"feedback-([0-9]+)", message)
201
+ if match is None:
202
+ return None
203
+ return int(match.group(1))
204
+
205
+ def _parse_device_message(self, message: str) -> dict[str, Any] | None:
206
+ import re
207
+
208
+ match = re.fullmatch(r"strength-([0-9]+)\+([0-9]+)\+([0-9]+)\+([0-9]+)", message)
209
+ if match is None or self._paired_target_id is None:
210
+ return None
211
+
212
+ a_strength, b_strength, a_soft_limit, b_soft_limit = [int(value) for value in match.groups()]
213
+ next_props = {
214
+ "strength": {"A": a_strength, "B": b_strength},
215
+ "softLimit": {"A": a_soft_limit, "B": b_soft_limit},
216
+ }
217
+ previous_props = (self._device or {}).get("props") or {}
218
+ props: dict[str, Any] = {}
219
+
220
+ if (previous_props.get("strength") or {}).get("A") != a_strength:
221
+ props.setdefault("strength", {})["A"] = a_strength
222
+ if (previous_props.get("strength") or {}).get("B") != b_strength:
223
+ props.setdefault("strength", {})["B"] = b_strength
224
+ if (previous_props.get("softLimit") or {}).get("A") != a_soft_limit:
225
+ props.setdefault("softLimit", {})["A"] = a_soft_limit
226
+ if (previous_props.get("softLimit") or {}).get("B") != b_soft_limit:
227
+ props.setdefault("softLimit", {})["B"] = b_soft_limit
228
+
229
+ self._device = {
230
+ **(self._device or self._create_device()),
231
+ "props": next_props,
232
+ }
233
+
234
+ if not props:
235
+ return None
236
+ return {"type": DglabSocketDeviceType.COYOTE_030, "props": props}
237
+
238
+ def _emit_device(self, device: dict[str, Any], client_id: str | None = None) -> None:
239
+ target_id = client_id or self._paired_target_id
240
+ if target_id is None:
241
+ return
242
+ self.emit("device", device, target_id)
243
+
244
+ @staticmethod
245
+ def _create_device() -> dict[str, Any]:
246
+ return {
247
+ "type": DglabSocketDeviceType.COYOTE_030,
248
+ }