diff --git a/src/composables/useDeviceDiscovery.js b/src/composables/useDeviceDiscovery.js new file mode 100644 index 0000000..c46c478 --- /dev/null +++ b/src/composables/useDeviceDiscovery.js @@ -0,0 +1,102 @@ +// src/composables/useDeviceDiscovery.js +import { nextTick } from 'vue' + +/** + * 负责连接 multiplex WebSocket,维护 deviceInformation 列表, + * 并在设备出现时按顺序调用 initCanvas / initVideoStream / getSize。 + * 获取设备的ws + */ +export function useDeviceDiscovery({ + deviceInformation, // ref([]) + initCanvas, // (udid) => void + initVideoStream, // (udid, index) => void + wsActionsRef, // () => wsActions (可能一开始是 null) + td // 你的 useTeardown 实例,可选 +}) { + const decoder = new TextDecoder('utf-8') + + function open(url, eitwoBuffer) { + const ws = new WebSocket(url) + td && td.setMultiplexWS && td.setMultiplexWS(ws) // 交给 teardown 托管 + ws.binaryType = 'arraybuffer' + + ws.onopen = () => { + ws.send(eitwoBuffer) // 请求设备列表 + } + + ws.onmessage = async (event) => { + let data + try { + // 兼容原逻辑:先解码再清理不可见字符再 JSON 解析 + data = JSON.parse(decoder.decode(event.data).replace(/[^\x20-\x7F]/g, '')) + } catch (e) { + console.error('[multiplex] parse error:', e) + return + } + + if (data.type === 'devicelist') { + // 全量刷新 + deviceInformation.value = [] + const list = (data.data.list || []).filter(it => it.state === 'device') + + for (let i = 0; i < list.length; i++) { + const item = list[i] + deviceInformation.value.push(item) + + await nextTick() // 等 v-for 渲染出