46e1b5be65
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
145 lines
4.8 KiB
JavaScript
145 lines
4.8 KiB
JavaScript
// 实体机器人连接层。仿真 / USB 串口 (Web Serial) / WebSocket 三种传输方式,
|
||
// 对上层只暴露 connect / send / disconnect。
|
||
//
|
||
// 下发协议(占位,按你的固件改 encode 即可),每行一条 JSON:
|
||
// {"type":"joints","t":1712345678901,"q":{"joint_name":0.123, ...}} // 弧度 / 米
|
||
// 如果配置了 hardware.servoIds,会额外带上 "servo":{"1":0.123, ...}
|
||
|
||
export class RobotLink extends EventTarget {
|
||
constructor() {
|
||
super();
|
||
this.kind = 'sim';
|
||
this.status = 'idle'; // idle | connecting | connected | error
|
||
this.transport = null;
|
||
this.lastSend = 0;
|
||
this.rateHz = 30;
|
||
}
|
||
|
||
get supportsSerial() { return 'serial' in navigator; }
|
||
|
||
setStatus(status, message) {
|
||
this.status = status;
|
||
this.dispatchEvent(new CustomEvent('status', { detail: { status, kind: this.kind, message } }));
|
||
}
|
||
|
||
log(message) { this.dispatchEvent(new CustomEvent('log', { detail: { message, time: new Date() } })); }
|
||
|
||
async connect(kind, opts = {}) {
|
||
await this.disconnect();
|
||
this.kind = kind;
|
||
this.setStatus('connecting');
|
||
try {
|
||
if (kind === 'serial') this.transport = await SerialTransport.open(opts, (m) => this.log(m));
|
||
else if (kind === 'websocket') this.transport = await WebSocketTransport.open(opts, (m) => this.log(m));
|
||
else this.transport = null;
|
||
this.setStatus('connected');
|
||
this.log(kind === 'sim' ? '仿真模式:只驱动 3D 模型' : `已连接(${kind})`);
|
||
} catch (err) {
|
||
this.transport = null;
|
||
this.setStatus('error', err.message);
|
||
this.log(`连接失败:${err.message}`);
|
||
}
|
||
}
|
||
|
||
async disconnect() {
|
||
if (this.transport) {
|
||
await this.transport.close().catch(() => {});
|
||
this.log('已断开');
|
||
}
|
||
this.transport = null;
|
||
if (this.status !== 'idle') this.setStatus('idle');
|
||
}
|
||
|
||
// 按 rateHz 节流;calibration 为 {joint: 零位偏移}
|
||
send(joints, { calibration = {}, hardware = null } = {}) {
|
||
if (!this.transport || this.status !== 'connected') return;
|
||
const now = performance.now();
|
||
if (now - this.lastSend < 1000 / this.rateHz) return;
|
||
this.lastSend = now;
|
||
this.transport.write(encode(joints, calibration, hardware)).catch((err) => {
|
||
this.setStatus('error', err.message);
|
||
this.log(`发送失败:${err.message}`);
|
||
});
|
||
}
|
||
}
|
||
|
||
export function encode(joints, calibration, hardware) {
|
||
const q = {};
|
||
for (const [name, v] of Object.entries(joints)) {
|
||
const sign = hardware?.direction?.[name] ?? 1;
|
||
q[name] = +(sign * (v - (calibration[name] ?? 0))).toFixed(4);
|
||
}
|
||
const msg = { type: 'joints', t: Date.now(), q };
|
||
if (hardware?.servoIds) {
|
||
msg.servo = {};
|
||
for (const [name, id] of Object.entries(hardware.servoIds)) if (name in q) msg.servo[id] = q[name];
|
||
}
|
||
return JSON.stringify(msg) + '\n';
|
||
}
|
||
|
||
class SerialTransport {
|
||
static async open({ baudRate = 1000000 } = {}, log) {
|
||
if (!('serial' in navigator)) throw new Error('当前浏览器不支持 Web Serial,请使用 Chrome / Edge');
|
||
const port = await navigator.serial.requestPort();
|
||
await port.open({ baudRate });
|
||
const t = new SerialTransport();
|
||
t.port = port;
|
||
t.writer = port.writable.getWriter();
|
||
t.encoder = new TextEncoder();
|
||
t.readLoop(log);
|
||
return t;
|
||
}
|
||
|
||
async readLoop(log) {
|
||
const decoder = new TextDecoderStream();
|
||
this.readClosed = this.port.readable.pipeTo(decoder.writable).catch(() => {});
|
||
this.reader = decoder.readable.getReader();
|
||
let buf = '';
|
||
try {
|
||
for (;;) {
|
||
const { value, done } = await this.reader.read();
|
||
if (done) break;
|
||
buf += value;
|
||
const lines = buf.split('\n');
|
||
buf = lines.pop();
|
||
lines.filter(Boolean).forEach((l) => log(`← ${l.trim()}`));
|
||
}
|
||
} catch { /* 关闭时会抛出 */ }
|
||
}
|
||
|
||
write(text) { return this.writer.write(this.encoder.encode(text)); }
|
||
|
||
async close() {
|
||
await this.reader?.cancel().catch(() => {});
|
||
await this.readClosed;
|
||
this.writer.releaseLock();
|
||
await this.port.close();
|
||
}
|
||
}
|
||
|
||
class WebSocketTransport {
|
||
static open({ url } = {}, log) {
|
||
return new Promise((resolve, reject) => {
|
||
if (!url) return reject(new Error('请填写 WebSocket 地址'));
|
||
const ws = new WebSocket(url);
|
||
const timer = setTimeout(() => { ws.close(); reject(new Error('连接超时')); }, 6000);
|
||
ws.onopen = () => {
|
||
clearTimeout(timer);
|
||
const t = new WebSocketTransport();
|
||
t.ws = ws;
|
||
ws.onmessage = (e) => log(`← ${String(e.data).slice(0, 200)}`);
|
||
ws.onclose = () => log('WebSocket 已关闭');
|
||
resolve(t);
|
||
};
|
||
ws.onerror = () => { clearTimeout(timer); reject(new Error(`无法连接 ${url}`)); };
|
||
});
|
||
}
|
||
|
||
async write(text) {
|
||
if (this.ws.readyState !== WebSocket.OPEN) throw new Error('WebSocket 未连接');
|
||
this.ws.send(text);
|
||
}
|
||
|
||
async close() { this.ws.close(); }
|
||
}
|