@raydiculousx/ts-sdk 0.0.0-stage → 1.0.0

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.
Files changed (126) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +55 -0
  3. package/NOTICE +14 -0
  4. package/README.md +91 -3
  5. package/dist/THIRD_PARTY_NOTICES.txt +466 -0
  6. package/dist/host/src/bootstrap/client.d.ts +37 -0
  7. package/dist/host/src/bootstrap/client.js +215 -0
  8. package/dist/host/src/bootstrap/host.d.ts +79 -0
  9. package/dist/host/src/bootstrap/host.js +214 -0
  10. package/dist/host/src/bootstrap/protocol.d.ts +20 -0
  11. package/dist/host/src/bootstrap/protocol.js +72 -0
  12. package/dist/host/src/dev.d.ts +30 -0
  13. package/dist/host/src/dev.js +20 -0
  14. package/dist/host/src/entry/app.d.ts +10 -0
  15. package/dist/host/src/entry/app.js +9 -0
  16. package/dist/host/src/entry/auto.d.ts +16 -0
  17. package/dist/host/src/entry/auto.js +18747 -0
  18. package/dist/host/src/standalone/account-api.d.ts +32 -0
  19. package/dist/host/src/standalone/account-api.js +176 -0
  20. package/dist/host/src/standalone/connection-slot.d.ts +12 -0
  21. package/dist/host/src/standalone/connection-slot.js +28 -0
  22. package/dist/host/src/standalone/device-picker.d.ts +6 -0
  23. package/dist/host/src/standalone/device-picker.js +19 -0
  24. package/dist/host/src/standalone/locale.d.ts +4 -0
  25. package/dist/host/src/standalone/locale.js +35 -0
  26. package/dist/host/src/standalone/mount-host.d.ts +155 -0
  27. package/dist/host/src/standalone/mount-host.js +396 -0
  28. package/dist/host/src/standalone/mount-surface.d.ts +12 -0
  29. package/dist/host/src/standalone/mount-surface.js +69 -0
  30. package/dist/host/src/standalone/robot-setup.d.ts +61 -0
  31. package/dist/host/src/standalone/robot-setup.js +160 -0
  32. package/dist/lib/client/action-ownership.d.ts +31 -0
  33. package/dist/lib/client/action-ownership.js +182 -0
  34. package/dist/lib/client/direct.d.ts +149 -0
  35. package/dist/lib/client/direct.js +560 -0
  36. package/dist/lib/client/raydiculousx.d.ts +541 -0
  37. package/dist/lib/client/raydiculousx.js +694 -0
  38. package/dist/lib/client/runtime.d.ts +165 -0
  39. package/dist/lib/client/runtime.js +1 -0
  40. package/dist/lib/core/index.d.ts +16 -0
  41. package/dist/lib/core/index.js +9 -0
  42. package/dist/lib/core/rpc/command-channel.d.ts +345 -0
  43. package/dist/lib/core/rpc/command-channel.js +697 -0
  44. package/dist/lib/core/rpc/commands.d.ts +354 -0
  45. package/dist/lib/core/rpc/commands.js +134 -0
  46. package/dist/lib/core/rpc/request-policy.d.ts +29 -0
  47. package/dist/lib/core/rpc/request-policy.js +35 -0
  48. package/dist/lib/core/rpc/robot-api.d.ts +184 -0
  49. package/dist/lib/core/rpc/robot-api.js +34 -0
  50. package/dist/lib/core/signaling/ice-servers.d.ts +10 -0
  51. package/dist/lib/core/signaling/ice-servers.js +58 -0
  52. package/dist/lib/core/signaling/peer-negotiator.d.ts +164 -0
  53. package/dist/lib/core/signaling/peer-negotiator.js +366 -0
  54. package/dist/lib/core/signaling/signaling-client.d.ts +204 -0
  55. package/dist/lib/core/signaling/signaling-client.js +473 -0
  56. package/dist/lib/core/signaling/signaling-contract.d.ts +164 -0
  57. package/dist/lib/core/signaling/signaling-contract.js +35 -0
  58. package/dist/lib/core/signaling/signaling.d.ts +172 -0
  59. package/dist/lib/core/signaling/signaling.js +381 -0
  60. package/dist/lib/media/attach-video.d.ts +3 -0
  61. package/dist/lib/media/attach-video.js +243 -0
  62. package/dist/lib/media/direct-audio.d.ts +36 -0
  63. package/dist/lib/media/direct-audio.js +94 -0
  64. package/dist/lib/media/index.d.ts +5 -0
  65. package/dist/lib/media/index.js +3 -0
  66. package/dist/lib/media/pcm-types.d.ts +33 -0
  67. package/dist/lib/media/pcm-types.js +1 -0
  68. package/dist/lib/media/robot-audio.d.ts +64 -0
  69. package/dist/lib/media/robot-audio.js +82 -0
  70. package/dist/lib/media/robot-pcm-output.d.ts +16 -0
  71. package/dist/lib/media/robot-pcm-output.js +101 -0
  72. package/dist/lib/robot/action-upload.d.ts +32 -0
  73. package/dist/lib/robot/action-upload.js +143 -0
  74. package/dist/lib/robot/robot-commands.d.ts +148 -0
  75. package/dist/lib/robot/robot-commands.js +164 -0
  76. package/dist/lib/robot/robot-responses.d.ts +42 -0
  77. package/dist/lib/robot/robot-responses.js +226 -0
  78. package/dist/lib/robot/robot-tof.d.ts +61 -0
  79. package/dist/lib/robot/robot-tof.js +25 -0
  80. package/dist/lib/robot/robot-types.d.ts +293 -0
  81. package/dist/lib/robot/robot-types.js +17 -0
  82. package/dist/lib/shared/errors.d.ts +57 -0
  83. package/dist/lib/shared/errors.js +45 -0
  84. package/dist/lib/shared/events.d.ts +11 -0
  85. package/dist/lib/shared/events.js +40 -0
  86. package/dist/lib/shared/types.d.ts +26 -0
  87. package/dist/lib/shared/types.js +1 -0
  88. package/dist/lib/shared/validation.d.ts +29 -0
  89. package/dist/lib/shared/validation.js +87 -0
  90. package/dist/lib/version.d.ts +2 -0
  91. package/dist/lib/version.js +3 -0
  92. package/dist/raydiculousx-sdk.d.ts +26 -0
  93. package/dist/raydiculousx-sdk.js +17 -0
  94. package/docs/API.md +1106 -0
  95. package/docs/DIRECT_APPS.md +83 -0
  96. package/docs/HOST_HANDOFF.md +59 -0
  97. package/docs/HOST_PROTOCOL.md +43 -0
  98. package/docs/RELEASING.md +33 -0
  99. package/docs/assets/raydiculousx-mark.png +0 -0
  100. package/examples/README.md +10 -0
  101. package/examples/application-template/README.md +60 -0
  102. package/examples/application-template/index.html +12 -0
  103. package/examples/application-template/package.json +21 -0
  104. package/examples/application-template/src/app.config.ts +8 -0
  105. package/examples/application-template/src/app.ts +81 -0
  106. package/examples/application-template/src/dispatch.ts +29 -0
  107. package/examples/application-template/src/embed.ts +39 -0
  108. package/examples/application-template/src/env.d.ts +10 -0
  109. package/examples/application-template/src/host-origin.ts +9 -0
  110. package/examples/application-template/src/locale.ts +90 -0
  111. package/examples/application-template/src/styles.css +31 -0
  112. package/examples/application-template/tsconfig.json +24 -0
  113. package/examples/application-template/vite.config.mjs +16 -0
  114. package/examples/sdk-diagnostics/README.md +199 -0
  115. package/examples/sdk-diagnostics/assets/THIRD_PARTY_NOTICES.txt +567 -0
  116. package/examples/sdk-diagnostics/assets/auto-CnsixhmH.js +9 -0
  117. package/examples/sdk-diagnostics/assets/console-BjvPHSNK.css +1 -0
  118. package/examples/sdk-diagnostics/assets/console-BrwFsb65.js +9 -0
  119. package/examples/sdk-diagnostics/assets/favicon-BZQEit-G.ico +0 -0
  120. package/examples/sdk-diagnostics/assets/index-DXSJUMrS.js +2 -0
  121. package/examples/sdk-diagnostics/assets/messages-C1UCo5nT.js +1 -0
  122. package/examples/sdk-diagnostics/assets/robot-x3-D4wBvBN8.webp +0 -0
  123. package/examples/sdk-diagnostics/assets/styles-D3TrErcf.css +1 -0
  124. package/examples/sdk-diagnostics/index.html +15 -0
  125. package/host/README.md +34 -0
  126. package/package.json +80 -4
@@ -0,0 +1,697 @@
1
+ /** 共享 JSON-RPC 客户端:回执、连接隔离、事件订阅及应用退出停车。 */
2
+ import { changesMotion, defaultRequestTimeoutMs, isRateLimitedMethod, stopsMotion } from "./request-policy.js";
3
+ import { controlParamsError, usesMotionPriority, WEB_PRIORITY } from "../../robot/robot-commands.js";
4
+ import { hasValidTofCapabilities, isRobotTofFrame } from "../../robot/robot-tof.js";
5
+ import { MAX_MESSAGE_BYTES } from "../../shared/validation.js";
6
+ import { DEFAULT_MAX_COMMAND_HZ, MAX_BUFFERED_AMOUNT, MAX_FRAME_BYTES, RPC_ERROR_HINTS, isAppAllowed, isRpcFailure, } from "./commands.js";
7
+ let nextRpcId = 1; // 所有连接和调试请求共用编号,避免回包误配。
8
+ const MAX_PENDING = 32;
9
+ const record = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
10
+ /** 上位机返回的原始错误码。 */
11
+ export class RobotRpcError extends Error {
12
+ /** 设备返回的数值错误码,不转换为业务 SDK 的字符串码。 */
13
+ code;
14
+ /** 设备附带的诊断数据;未提供时为 undefined。 */
15
+ data;
16
+ /**
17
+ * 保存设备返回的错误。
18
+ * @param code - 设备返回的数值错误码。
19
+ * @param message - 设备提供的说明,省略或为空时使用已知错误提示或通用说明。
20
+ * @param data - 设备附带的诊断数据,可选。
21
+ */
22
+ constructor(code, message, data) {
23
+ super(message || RPC_ERROR_HINTS[code] || '机器人请求失败');
24
+ this.name = 'RobotRpcError';
25
+ this.code = code;
26
+ this.data = data;
27
+ }
28
+ }
29
+ /** 本地传输错误;取消和超时不代表远端动作取消。 */
30
+ export class RobotTransportError extends Error {
31
+ /** 本地传输错误码,例如 NOT_READY、REQUEST_TIMEOUT 或 ABORTED。 */
32
+ code;
33
+ /**
34
+ * 创建本地传输错误。
35
+ * @param code - 本地传输错误码。
36
+ * @param message - 描述失败原因的文本。
37
+ */
38
+ constructor(code, message) {
39
+ super(message);
40
+ this.name = 'RobotTransportError';
41
+ this.code = code;
42
+ }
43
+ }
44
+ const error = (code, message) => new RobotTransportError(code, message);
45
+ function publish(listeners, value) {
46
+ for (const listener of [...listeners]) {
47
+ try {
48
+ listener(value);
49
+ }
50
+ catch (failure) {
51
+ console.error('[robot] listener failed', failure);
52
+ }
53
+ }
54
+ }
55
+ function subscribe(listeners, listener) {
56
+ listeners.add(listener);
57
+ return () => { listeners.delete(listener); };
58
+ }
59
+ /**
60
+ * 已建立 WebRTC 上的 JSON-RPC 客户端,管理回执、订阅、限频和本地应用会话清理。
61
+ * @remarks 不创建网络连接,也不在 dispose 时关闭连接;连接生命周期由调用方管理。
62
+ * 事件不回放,监听器收到共享对象引用;同步监听错误被记录并隔离,异步错误由监听器自行处理。
63
+ */
64
+ export class CommandChannel {
65
+ connection;
66
+ control;
67
+ /** 此客户端绑定的本地连接代次,构造后不变。 */
68
+ connectionEpoch;
69
+ requestTimeoutMs;
70
+ maxCommandHz;
71
+ lastCommandAt = new Map();
72
+ pending = new Map();
73
+ disposed = false;
74
+ lifetime = new AbortController();
75
+ tofRequestPending = false;
76
+ activeSessions = new Set();
77
+ closedSessions = new Set();
78
+ cleanup = new Map();
79
+ revision = 0;
80
+ caps = null;
81
+ capabilityTimers = new Set();
82
+ telemetryListeners = new Set();
83
+ tofListeners = new Set();
84
+ responseListeners = new Set();
85
+ faultListeners = new Set();
86
+ skillListeners = new Set();
87
+ audioErrorListeners = new Set();
88
+ closeListeners = new Set();
89
+ capabilityListeners = new Set();
90
+ /**
91
+ * 绑定现有 WebRTC 与数据通道的事件。
92
+ * @param opts - 连接、连接代次、初始频率及等待配置,见 {@link CommandChannelOptions}。
93
+ * @throws 缺少 control 通道或初始频率非法时同步抛出 {@link RobotTransportError}。
94
+ */
95
+ constructor(opts) {
96
+ if (!opts.connection.control)
97
+ throw error('NOT_READY', '连接没有 control 通道');
98
+ this.connection = opts.connection;
99
+ this.control = opts.connection.control;
100
+ this.connectionEpoch = opts.connectionEpoch ?? 0;
101
+ this.requestTimeoutMs = opts.requestTimeoutMs;
102
+ this.maxCommandHz = opts.maxCommandHz ?? DEFAULT_MAX_COMMAND_HZ;
103
+ if (!Number.isFinite(this.maxCommandHz) || this.maxCommandHz <= 0) {
104
+ throw error('INVALID_ARGUMENT', 'maxCommandHz 必须为正数');
105
+ }
106
+ this.control.addEventListener('message', this.onControlMessage);
107
+ this.control.addEventListener('close', this.onClosed);
108
+ this.control.addEventListener('error', this.onClosed);
109
+ this.connection.pc.addEventListener('connectionstatechange', this.onConnectionState);
110
+ this.connection.telemetry?.addEventListener('message', this.onTelemetryMessage);
111
+ this.connection.tof?.addEventListener('message', this.onTofMessage);
112
+ }
113
+ /**
114
+ * 订阅通过外层校验的 robot.state 遥测帧。
115
+ * @param fn - 接收 {@link TelemetryNotification} 的回调;核心不完整校验业务载荷。
116
+ * @returns 可重复调用的退订函数。
117
+ */
118
+ onTelemetry(fn) { return subscribe(this.telemetryListeners, fn); }
119
+ /**
120
+ * 监听已校验的头部 ToF 深度帧。
121
+ * @param fn - 接收 {@link RobotTofFrame} 的回调。
122
+ * @returns 可重复调用的退订函数,只移除此监听。
123
+ * @remarks 帧通过独立的 tof 通道到达。设备推流由 robot.tof.subscribe 和 robot.tof.unsubscribe 控制。
124
+ */
125
+ onTof(fn) { return subscribe(this.tofListeners, fn); }
126
+ /**
127
+ * 订阅通过外层解析的 control 帧及本地错误记录。
128
+ * @param fn - 接收原始 control 帧或 {@link CommandChannel.sendRawFrame} 的 localError 的回调。
129
+ * @returns 可重复调用的退订函数。
130
+ * @remarks 监听范围不限于已配对的请求回执。
131
+ */
132
+ onResponse(fn) { return subscribe(this.responseListeners, fn); }
133
+ /**
134
+ * 订阅通过校验的设备故障通知。
135
+ * @param fn - 接收 {@link FaultNotification} 的回调,通知包含字符串 reason 和 FAULT 状态。
136
+ * @returns 可重复调用的退订函数。
137
+ */
138
+ onFault(fn) { return subscribe(this.faultListeners, fn); }
139
+ /**
140
+ * 订阅设备报告的技能执行结果。
141
+ * @param fn - 接收 {@link RobotSkillEvent} 的回调。
142
+ * @returns 可重复调用的退订函数。
143
+ */
144
+ onSkill(fn) { return subscribe(this.skillListeners, fn); }
145
+ /**
146
+ * 订阅经过结构和帧大小校验的设备音频失败通知。
147
+ * @param fn - 接收 {@link AudioErrorNotification} 的回调。
148
+ * @returns 可重复调用的退订函数。
149
+ */
150
+ onAudioError(fn) { return subscribe(this.audioErrorListeners, fn); }
151
+ /**
152
+ * 订阅控制通道关闭或连接中断。
153
+ * @param fn - 控制通道关闭、出错或 WebRTC 进入 disconnected、failed、closed 时调用的函数。
154
+ * @returns 可重复调用的退订函数。
155
+ * @remarks 同一次断线可能触发多次通知。
156
+ */
157
+ onClose(fn) { return subscribe(this.closeListeners, fn); }
158
+ /**
159
+ * 订阅成功查询后异步发布的设备能力。
160
+ * @param fn - 接收 {@link RobotCapabilities} 的回调,不会立即收到已有能力快照。
161
+ * @returns 可重复调用的退订函数。
162
+ */
163
+ onCapabilities(fn) { return subscribe(this.capabilityListeners, fn); }
164
+ /** 最近一次校验通过的能力对象,查询前为 null;返回内部引用,调用方不应修改。 */
165
+ get capabilitiesSnapshot() { return this.caps; }
166
+ /** 当前尚未完成的请求数量,包含停车请求。 */
167
+ get pendingCount() { return this.pending.size; }
168
+ /**
169
+ * 读取设备请求传输的就绪状态。
170
+ * @returns 通道未释放、control 为 open 且 WebRTC 为 connected 时为 true。
171
+ * @remarks 设备执行器状态需另行查询。
172
+ */
173
+ isReady() {
174
+ return !this.disposed && this.control.readyState === 'open' && this.connection.pc.connectionState === 'connected';
175
+ }
176
+ onConnectionState = () => {
177
+ if (['disconnected', 'failed', 'closed'].includes(this.connection.pc.connectionState))
178
+ this.onClosed();
179
+ };
180
+ onClosed = () => {
181
+ this.rejectAll(error('CONTEXT_CHANGED', '设备连接已断开,执行结果可能未知'));
182
+ publish(this.closeListeners, undefined);
183
+ };
184
+ parse(raw, allowConfigReply = false) {
185
+ if (typeof raw !== 'string')
186
+ return null;
187
+ const limit = allowConfigReply ? MAX_MESSAGE_BYTES : MAX_FRAME_BYTES;
188
+ if (raw.length > limit)
189
+ return null;
190
+ const size = new TextEncoder().encode(raw).length;
191
+ if (size > limit)
192
+ return null;
193
+ try {
194
+ const frame = JSON.parse(raw);
195
+ if (!record(frame) || frame.jsonrpc !== '2.0')
196
+ return null;
197
+ // 配置文件可大于普通指令帧。只有本连接当前等待的配置回执可使用较大的接收额度。
198
+ if (size > MAX_FRAME_BYTES && (typeof frame.id !== 'number'
199
+ || this.pending.get(frame.id)?.method !== 'robot.config'))
200
+ return null;
201
+ return frame;
202
+ }
203
+ catch {
204
+ return null;
205
+ }
206
+ }
207
+ onControlMessage = (event) => {
208
+ if (this.disposed)
209
+ return;
210
+ const msg = this.parse(event.data, true);
211
+ if (!msg)
212
+ return;
213
+ publish(this.responseListeners, msg);
214
+ if (!('id' in msg) && msg.method === 'robot.fault' && record(msg.params)
215
+ && msg.params.state === 'FAULT' && typeof msg.params.reason === 'string') {
216
+ publish(this.faultListeners, msg);
217
+ return;
218
+ }
219
+ if (!('id' in msg) && msg.method === 'robot.skill' && record(msg.params)) {
220
+ const { skill, status, reason, durationMs } = msg.params;
221
+ if (typeof skill === 'string' && (status === 'completed' || status === 'timed_out'
222
+ || status === 'failed' || status === 'cancelled') && (reason === null || typeof reason === 'string')
223
+ && (durationMs === null || (typeof durationMs === 'number' && Number.isFinite(durationMs) && durationMs >= 0))) {
224
+ publish(this.skillListeners, { skill, status, reason, durationMs });
225
+ }
226
+ return;
227
+ }
228
+ if (!('id' in msg) && msg.method === 'robot.audio.error' && record(msg.params)
229
+ && typeof msg.params.reason === 'string' && typeof msg.params.message === 'string') {
230
+ publish(this.audioErrorListeners, {
231
+ jsonrpc: '2.0', method: 'robot.audio.error',
232
+ params: { reason: msg.params.reason, message: msg.params.message },
233
+ });
234
+ return;
235
+ }
236
+ if (typeof msg.id !== 'number')
237
+ return;
238
+ const pending = this.pending.get(msg.id);
239
+ if (!pending)
240
+ return;
241
+ this.pending.delete(msg.id);
242
+ pending.release();
243
+ if (isRpcFailure(msg) && !('result' in msg && msg.result !== null)) {
244
+ pending.reject(new RobotRpcError(msg.error.code, msg.error.message, msg.error.data));
245
+ return;
246
+ }
247
+ if (!('result' in msg) || (msg.error !== undefined && msg.error !== null)) {
248
+ pending.reject(error('PROTOCOL_ERROR', '设备回包缺少 result 或包含无效 error'));
249
+ return;
250
+ }
251
+ if (pending.method === 'robot.capabilities') {
252
+ try {
253
+ this.acceptCapabilities(msg.result);
254
+ }
255
+ catch (failure) {
256
+ pending.reject(failure);
257
+ return;
258
+ }
259
+ }
260
+ if (pending.revision === this.revision && record(msg.result)) {
261
+ if (stopsMotion(pending.method) && msg.result.accepted === true) {
262
+ this.activeSessions.clear();
263
+ }
264
+ if (pending.newActivity && pending.session && msg.result.accepted === false)
265
+ this.activeSessions.delete(pending.session);
266
+ }
267
+ pending.resolve(msg.result);
268
+ };
269
+ onTelemetryMessage = (event) => {
270
+ if (this.disposed)
271
+ return;
272
+ const msg = this.parse(event.data);
273
+ if (msg && !('id' in msg) && msg.method === 'robot.state' && record(msg.params)) {
274
+ publish(this.telemetryListeners, msg);
275
+ }
276
+ };
277
+ onTofMessage = (event) => {
278
+ if (!this.isReady() || this.connection.tof?.readyState !== 'open')
279
+ return;
280
+ const msg = this.parse(event.data);
281
+ if (msg && !('id' in msg) && msg.method === 'robot.tof' && record(msg.params) && isRobotTofFrame(msg.params)) {
282
+ publish(this.tofListeners, msg.params);
283
+ }
284
+ };
285
+ acceptCapabilities(value) {
286
+ if (!record(value) || value.protocol !== 'v1' || value.dof !== 15
287
+ || !Array.isArray(value.jointNames) || value.jointNames.length !== 15
288
+ || !value.jointNames.every((name) => typeof name === 'string')
289
+ || typeof value.maxCommandHz !== 'number' || !Number.isFinite(value.maxCommandHz) || value.maxCommandHz <= 0
290
+ || typeof value.telemetryHz !== 'number' || !Number.isFinite(value.telemetryHz) || value.telemetryHz <= 0
291
+ || !['hasVideo', 'hasAudioOut', 'hasAudioIn'].every((key) => typeof value[key] === 'boolean')
292
+ || !hasValidTofCapabilities(value)
293
+ || (value.hasLightFollow !== undefined && typeof value.hasLightFollow !== 'boolean')) {
294
+ throw error('PROTOCOL_ERROR', '设备能力回包不符合 WebRTC v1');
295
+ }
296
+ this.caps = value;
297
+ this.maxCommandHz = this.caps.maxCommandHz;
298
+ const caps = this.caps;
299
+ // 查询先回包给 SDK,再更新能力上下文,避免能力变化取消自身查询。
300
+ const timer = setTimeout(() => {
301
+ this.capabilityTimers.delete(timer);
302
+ if (!this.disposed)
303
+ publish(this.capabilityListeners, caps);
304
+ }, 0);
305
+ this.capabilityTimers.add(timer);
306
+ }
307
+ waitForTof(channel, timeout, signal) {
308
+ return new Promise((resolve, reject) => {
309
+ const listeners = new AbortController();
310
+ const local = { signal: listeners.signal };
311
+ const finish = (failure) => {
312
+ clearTimeout(timer);
313
+ listeners.abort();
314
+ offClose();
315
+ if (failure)
316
+ reject(failure);
317
+ else
318
+ resolve();
319
+ };
320
+ const unavailable = () => finish(error('UNSUPPORTED', '连接没有可用的 tof 通道'));
321
+ const disconnected = () => finish(error('CONTEXT_CHANGED', '等待 tof 通道时设备连接已关闭'));
322
+ const timer = setTimeout(() => finish(error('REQUEST_TIMEOUT', '等待 tof 通道打开超时')), timeout);
323
+ const offClose = this.onClose(disconnected);
324
+ channel.addEventListener('open', () => finish(), local);
325
+ channel.addEventListener('close', unavailable, local);
326
+ channel.addEventListener('error', unavailable, local);
327
+ signal?.addEventListener('abort', () => finish(error('ABORTED', '等待 tof 通道已取消')), local);
328
+ this.lifetime.signal.addEventListener('abort', disconnected, local);
329
+ });
330
+ }
331
+ /**
332
+ * 发送一次允许的设备请求并等待匹配的回执,不自动重试。
333
+ * @param method - {@link RobotRpcMethod} 中允许发送的请求方法。
334
+ * @param params - 可 JSON 序列化的方法参数;undefined 时省略 params。序列化后的整帧最多 16384 个 UTF-8 字节。
335
+ * @param options - 本地归属、取消与等待配置,见 {@link RobotRequestOptions}。
336
+ * @returns 设备 result;除能力回执外,本层不完整校验业务结果结构,R 由调用方指定。
337
+ * @throws 设备错误以 {@link RobotRpcError} 拒绝 Promise。请求参数校验、背压、限频、积压、断线、取消或超时
338
+ * 以 {@link RobotTransportError} 拒绝。JSON 序列化失败时透传序列化异常。
339
+ * @remarks 在途请求达到 32 个后,stop 和 relax 可各额外进入一个请求,前提是同类请求当前没有在途。
340
+ * 取消或超时只结束本地等待;按需调用 {@link CommandChannel.stop} 或 {@link CommandChannel.closeSession} 停止已发出的动作。
341
+ * move、head、look、pose 的发包优先级固定为 Web 的 3。
342
+ * ToF 订阅与退订每次只允许一项在途。订阅与 tof 通道打开共用本次等待上限。
343
+ */
344
+ request(method, params, options = {}) {
345
+ if (method !== 'robot.tof.subscribe' && method !== 'robot.tof.unsubscribe') {
346
+ return this.sendRequest(method, params, options);
347
+ }
348
+ if ((options.context?.signal ?? options.signal)?.aborted) {
349
+ return Promise.reject(error('ABORTED', '请求已取消'));
350
+ }
351
+ if (this.tofRequestPending)
352
+ return Promise.reject(error('BUSY', '当前连接已有 ToF 请求在进行'));
353
+ this.tofRequestPending = true;
354
+ return this.sendRequest(method, params, options).finally(() => { this.tofRequestPending = false; });
355
+ }
356
+ sendRequest(method, params, options) {
357
+ return new Promise((resolve, reject) => {
358
+ const context = options.context;
359
+ const signal = context?.signal ?? options.signal;
360
+ const timeout = options.timeoutMs ?? this.requestTimeoutMs ?? defaultRequestTimeoutMs(method, params);
361
+ if (signal?.aborted)
362
+ throw error('ABORTED', '请求已取消');
363
+ if (context && (context.robotId !== this.connection.sn || context.connectionEpoch !== this.connectionEpoch)) {
364
+ throw error('CONTEXT_CHANGED', '请求设备或连接代次已失效');
365
+ }
366
+ if (context && this.closedSessions.has(context.appSessionId))
367
+ throw error('APP_DISPOSED', '应用会话已关闭');
368
+ if (!this.isReady())
369
+ throw error('NOT_READY', 'control 通道未就绪');
370
+ if (!isAppAllowed(method))
371
+ throw error('UNSUPPORTED', '未注册的机器人请求');
372
+ const paramsError = controlParamsError(method, params);
373
+ if (paramsError)
374
+ throw error('INVALID_ARGUMENT', paramsError);
375
+ if (method === 'robot.actions.delete' && (!record(params) || typeof params.name !== 'string' || !params.name)) {
376
+ throw error('INVALID_ARGUMENT', 'deleteAction 需要非空动作名');
377
+ }
378
+ if ((method === 'robot.audio.stop' || method === 'robot.actions.list' || method === 'robot.config')
379
+ && params != null && (!record(params) || Object.keys(params).length > 0)) {
380
+ throw error('INVALID_ARGUMENT', '此方法不接受参数');
381
+ }
382
+ if (method === 'robot.setMode' && (!record(params) || typeof params.mode !== 'string')) {
383
+ throw error('INVALID_ARGUMENT', 'setMode 需要字符串 mode');
384
+ }
385
+ if (method === 'robot.move' && (!record(params)
386
+ || ![params.vx, params.vyaw, params.vy ?? 0].every((v) => typeof v === 'number' && Number.isFinite(v))
387
+ || params.vy === null || 'duration_s' in params)) {
388
+ throw error('INVALID_ARGUMENT', 'move 需要有限 vx/vyaw、可选 vy,不接受 duration_s');
389
+ }
390
+ if (method === 'robot.do' && (!record(params) || typeof params.skill !== 'string'
391
+ || !params.skill.trim() || params.skill.length > 256)) {
392
+ throw error('INVALID_ARGUMENT', 'skill 必须是非空字符串,最多 256 字符');
393
+ }
394
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 120000)
395
+ throw error('INVALID_ARGUMENT', '请求超时应为 1–120000 ms');
396
+ if (method === 'robot.tof.subscribe') {
397
+ const tof = this.connection.tof;
398
+ if (!tof || tof.readyState === 'closing' || tof.readyState === 'closed') {
399
+ throw error('UNSUPPORTED', '连接没有可用的 tof 通道');
400
+ }
401
+ if (tof.readyState === 'connecting') {
402
+ const deadline = performance.now() + timeout;
403
+ void this.waitForTof(tof, timeout, signal).then(() => {
404
+ const remaining = Math.ceil(deadline - performance.now());
405
+ if (remaining < 1)
406
+ throw error('REQUEST_TIMEOUT', '等待 tof 通道打开超时');
407
+ return this.sendRequest(method, params, { ...options, timeoutMs: remaining });
408
+ }).then(resolve, reject);
409
+ return;
410
+ }
411
+ }
412
+ if (this.control.bufferedAmount > MAX_BUFFERED_AMOUNT)
413
+ throw error('BACKPRESSURE', '发送缓冲积压,请稍后重试');
414
+ // 安全方向指令各预留一个槽位,仍遵守可靠通道的在途帧顺序。
415
+ const stopping = stopsMotion(method);
416
+ if (this.pending.size >= MAX_PENDING && (!stopping || [...this.pending.values()].some(p => p.method === method))) {
417
+ throw error('TOO_MANY_REQUESTS', '等待设备响应的请求过多');
418
+ }
419
+ const motion = changesMotion(method);
420
+ if (motion && [...this.activeSessions].some((id) => this.closedSessions.has(id))) {
421
+ throw error('BUSY', '正在等待旧应用的停车回执');
422
+ }
423
+ if (motion && [...this.activeSessions].some((id) => id !== context?.appSessionId)) {
424
+ throw error('BUSY', '其他应用仍有未清理的设备活动');
425
+ }
426
+ const rateLimited = isRateLimitedMethod(method);
427
+ if (rateLimited && performance.now() - (this.lastCommandAt.get(method) ?? -Infinity) < 1000 / this.maxCommandHz) {
428
+ throw error('RATE_LIMITED', `${method} 超过设备 maxCommandHz`);
429
+ }
430
+ const id = nextRpcId++;
431
+ const wireParams = usesMotionPriority(method)
432
+ ? { ...(record(params) ? params : {}), priority: WEB_PRIORITY }
433
+ : params;
434
+ const text = JSON.stringify({ jsonrpc: '2.0', id, method, ...(wireParams === undefined ? {} : { params: wireParams }) });
435
+ if (new TextEncoder().encode(text).length > MAX_FRAME_BYTES)
436
+ throw error('MESSAGE_TOO_LARGE', '请求超过 16 KB');
437
+ const session = context?.appSessionId;
438
+ const newActivity = Boolean(motion && session && !this.activeSessions.has(session));
439
+ if (motion || stopping)
440
+ this.revision++;
441
+ const fail = (failure) => {
442
+ const pending = this.pending.get(id);
443
+ if (!pending)
444
+ return;
445
+ this.pending.delete(id);
446
+ pending.release();
447
+ reject(failure);
448
+ };
449
+ const timer = setTimeout(() => fail(error('REQUEST_TIMEOUT', '等待 ' + method + ' 回执超时,执行结果未知')), timeout);
450
+ const abort = () => fail(error('ABORTED', '本地等待已取消,远端执行结果未知'));
451
+ this.pending.set(id, {
452
+ resolve: resolve, reject, method, session,
453
+ revision: this.revision, newActivity,
454
+ release: () => { clearTimeout(timer); signal?.removeEventListener('abort', abort); },
455
+ });
456
+ signal?.addEventListener('abort', abort, { once: true });
457
+ if (motion && session)
458
+ this.activeSessions.add(session);
459
+ try {
460
+ this.control.send(text);
461
+ if (rateLimited)
462
+ this.lastCommandAt.set(method, performance.now());
463
+ }
464
+ catch {
465
+ if (newActivity && session)
466
+ this.activeSessions.delete(session);
467
+ fail(error('SEND_FAILED', '设备请求未能发送'));
468
+ }
469
+ });
470
+ }
471
+ /**
472
+ * 提交调试 JSON 帧,复用常规请求的编号和发送器。
473
+ * @param text - 包含受支持 method 和可选 params 的 JSON 字符串;输入的 id 不参与配对。
474
+ * @returns 通过初步解析且交给 {@link CommandChannel.request} 时返回 true,其他情况返回 false。
475
+ * @remarks 返回 true 只表示已交给请求流程。异步失败通过 onResponse 的 localError 报告,白名单、限频和背压规则仍然生效。
476
+ */
477
+ sendRawFrame(text) {
478
+ const msg = this.parse(text);
479
+ if (!msg || typeof msg.method !== 'string' || !isAppAllowed(msg.method) || !this.isReady())
480
+ return false;
481
+ void this.request(msg.method, msg.params).catch((failure) => {
482
+ publish(this.responseListeners, { localError: { code: failure.code, message: failure.message } });
483
+ });
484
+ return true;
485
+ }
486
+ /**
487
+ * 发送一次速度设定。
488
+ * @param params - 目标速度,单位和约束见 {@link MoveParams};省略 vy 时发送 0。
489
+ * @returns 设备受理回执,移动是否完成由设备状态判断。
490
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
491
+ * @remarks 本方法不自动续发。保活超时和速度裁剪由设备决定。
492
+ */
493
+ move(params) { return this.request('robot.move', { ...params, vy: params.vy ?? 0 }); }
494
+ /**
495
+ * 请求设备切换行走、轮滑或舵机直控模式。
496
+ * @param params - 目标运动模式,见 {@link SetModeParams}。
497
+ * @returns 设备报告的受理状态;可通过 status 查询实际模式。
498
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
499
+ */
500
+ setMode(params) { return this.request('robot.setMode', params); }
501
+ /**
502
+ * 请求关节上电并返回 home。
503
+ * @returns 设备报告的受理状态,可附拒绝原因。
504
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
505
+ * @remarks 设备可能移动。
506
+ */
507
+ init() { return this.request('robot.init'); }
508
+ /**
509
+ * 交给或收回策略驱动。
510
+ * @param params - 是否启用策略驱动,见 {@link EnableParams}。
511
+ * @returns 设备报告的受理状态及可选原因。
512
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
513
+ */
514
+ enable(params) { return this.request('robot.enable', params); }
515
+ /**
516
+ * 设置头部关节目标。
517
+ * @param params - 可选目标角度,单位、范围和默认值见 {@link HeadParams}。
518
+ * @returns 设备报告的受理状态及采用的目标角度。
519
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
520
+ */
521
+ head(params = {}) { return this.request('robot.head', params); }
522
+ /**
523
+ * 请求设备朝指定位置注视。
524
+ * @param params - 躯干坐标系中的注视点及可选颈部俯仰,见 {@link LookParams}。
525
+ * @returns 设备报告的受理状态、目标角度及是否需要裁剪。
526
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
527
+ */
528
+ look(params) { return this.request('robot.look', params); }
529
+ /**
530
+ * 设置嘴部开合。
531
+ * @param params - 目标开合值,见 {@link MouthParams}。
532
+ * @returns 设备报告的受理状态及采用的开合值。
533
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
534
+ */
535
+ mouth(params) { return this.request('robot.mouth', params); }
536
+ /**
537
+ * 设置或解除身体姿态保持。
538
+ * @param params - 可选姿态目标及保持开关,见 {@link PoseParams}。
539
+ * @returns 设备报告的受理状态和姿态保持状态。
540
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
541
+ */
542
+ pose(params = {}) { return this.request('robot.pose', params); }
543
+ /**
544
+ * 请求切断关节力矩。
545
+ * @returns 设备返回的受理状态。
546
+ * @throws 设备错误以 RobotRpcError 拒绝 Promise;传输错误以 RobotTransportError 拒绝。
547
+ * @remarks 机器人可能倒下,操作前确认它已获得支撑。恢复需重新初始化关节。
548
+ */
549
+ relax() { return this.request('robot.relax'); }
550
+ /**
551
+ * 请求设备停车。
552
+ * @returns 设备受理回执;硬件是否停稳需另行确认。
553
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
554
+ * @remarks 停车不会清除执行器故障。
555
+ */
556
+ stop() { return this.request('robot.stop'); }
557
+ /**
558
+ * 请求设备执行技能。
559
+ * @param params - 技能名及等待标志,见 {@link DoParams}。
560
+ * @returns 设备受理状态与报告的执行结果;完成情况以 completed/status 为准。
561
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
562
+ */
563
+ do(params) { return this.request('robot.do', params); }
564
+ /**
565
+ * 请求设备中断播放。
566
+ * @returns 设备受理回执。
567
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
568
+ */
569
+ stopAudio() { return this.request('robot.audio.stop'); }
570
+ /**
571
+ * 查询设备登记的用户动作。
572
+ * @returns 设备提供的动作目录和文件信息。
573
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
574
+ */
575
+ listActions() { return this.request('robot.actions.list'); }
576
+ /**
577
+ * 请求设备删除一个用户动作。
578
+ * @param name - 要删除的已登记动作名。
579
+ * @returns 设备确认删除后返回动作名与文件大小。
580
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
581
+ * @remarks 本地超时后,已发送的删除请求仍可能由设备执行。
582
+ */
583
+ deleteAction(name) { return this.request('robot.actions.delete', { name }); }
584
+ /**
585
+ * 读取设备选定的配置文件快照。
586
+ * @returns 设备报告的文件信息及内容;缺失或解析错误也可由快照报告。
587
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
588
+ */
589
+ getConfig() { return this.request('robot.config'); }
590
+ /**
591
+ * 查询执行器状态快照。
592
+ * @returns 设备报告的查询时刻状态。
593
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
594
+ * @remarks 持续观察状态可订阅遥测。
595
+ */
596
+ status() { return this.request('robot.status'); }
597
+ /**
598
+ * 查询当前设备能力。
599
+ * @returns 设备报告的协议及能力信息。
600
+ * @throws 设备或传输失败时拒绝 Promise,见 {@link CommandChannel.request}。
601
+ * @remarks 校验 v1 能力并更新本地能力缓存和限频。
602
+ */
603
+ capabilities() { return this.request('robot.capabilities'); }
604
+ /**
605
+ * 撤销指定应用会话的本地请求;若有未清理动作则等待停车受理,不关闭 WebRTC。
606
+ * @param info - 要关闭的应用会话。
607
+ * @returns 无活动或已得到 accepted=true 的停车回执后完成;不证明硬件停稳。
608
+ * @throws 停车请求失败或回执未确认时拒绝,不能视为已经释放设备活动。
609
+ * @remarks 关闭标记立即生效,后续该会话请求被拒绝。重复调用复用首次 Promise,
610
+ * 包括首次失败的结果;无独立取消信号,停车使用默认请求等待策略。
611
+ */
612
+ closeSession(info) {
613
+ const id = info.appSessionId;
614
+ const existing = this.cleanup.get(id);
615
+ if (existing)
616
+ return existing;
617
+ this.closedSessions.add(id);
618
+ for (const [requestId, p] of this.pending) {
619
+ if (p.session !== id)
620
+ continue;
621
+ this.pending.delete(requestId);
622
+ p.release();
623
+ p.reject(error('APP_DISPOSED', '应用会话已撤销'));
624
+ }
625
+ const work = (async () => {
626
+ if (!this.activeSessions.has(id))
627
+ return;
628
+ const result = await this.stop();
629
+ if (result?.accepted !== true)
630
+ throw error('CLEANUP_UNCONFIRMED', '未收到停车受理回执');
631
+ this.activeSessions.delete(id);
632
+ })();
633
+ this.cleanup.set(id, work);
634
+ return work;
635
+ }
636
+ /**
637
+ * 请求设备复位可恢复故障。
638
+ * @returns 设备报告的复位后状态。
639
+ * @throws 设备拒绝复位时以 {@link RobotRpcError} 的数值码 409 拒绝 Promise;共同错误见 {@link CommandChannel.request}。
640
+ * @remarks 执行器须处于 FAULT 且 faultRecoverable 为 true,复位条件由设备判定。
641
+ */
642
+ reset() {
643
+ return this.request('robot.reset', {});
644
+ }
645
+ /**
646
+ * 请求停车并等待设备确认受理。
647
+ * @returns 收到 accepted 为 true 的回执后完成。
648
+ * @throws 请求失败或回执未确认时拒绝 Promise;未确认时错误码为 CLEANUP_UNCONFIRMED。
649
+ * @remarks 保留 WebRTC 和客户端资源,硬件是否停稳需另行确认。
650
+ */
651
+ async shutdownGracefully() {
652
+ const result = await this.stop();
653
+ if (result?.accepted !== true)
654
+ throw error('CLEANUP_UNCONFIRMED', '未收到停车受理回执');
655
+ }
656
+ /** 页面关闭时尽力发送一次停车帧,不等待回包、不检查背压,也不保证送达。 */
657
+ shutdownFast() {
658
+ if (!this.isReady())
659
+ return;
660
+ try {
661
+ this.control.send(JSON.stringify({ jsonrpc: '2.0', id: nextRpcId++, method: 'robot.stop' }));
662
+ }
663
+ catch { /* 设备断连兜底。 */ }
664
+ }
665
+ /** 幂等释放监听器、能力计时器和在途等待;以 CONTEXT_CHANGED 拒绝未完成请求,不停车或关闭 WebRTC。 */
666
+ dispose() {
667
+ if (this.disposed)
668
+ return;
669
+ this.disposed = true;
670
+ this.lifetime.abort();
671
+ this.rejectAll(error('CONTEXT_CHANGED', '设备通道已释放'));
672
+ this.control.removeEventListener('message', this.onControlMessage);
673
+ this.control.removeEventListener('close', this.onClosed);
674
+ this.control.removeEventListener('error', this.onClosed);
675
+ this.connection.pc.removeEventListener('connectionstatechange', this.onConnectionState);
676
+ this.connection.telemetry?.removeEventListener('message', this.onTelemetryMessage);
677
+ this.connection.tof?.removeEventListener('message', this.onTofMessage);
678
+ for (const timer of this.capabilityTimers)
679
+ clearTimeout(timer);
680
+ this.capabilityTimers.clear();
681
+ this.telemetryListeners.clear();
682
+ this.tofListeners.clear();
683
+ this.responseListeners.clear();
684
+ this.faultListeners.clear();
685
+ this.skillListeners.clear();
686
+ this.audioErrorListeners.clear();
687
+ this.closeListeners.clear();
688
+ this.capabilityListeners.clear();
689
+ }
690
+ rejectAll(failure) {
691
+ for (const p of this.pending.values()) {
692
+ p.release();
693
+ p.reject(failure);
694
+ }
695
+ this.pending.clear();
696
+ }
697
+ }