设备接入 优化
This commit is contained in:
@@ -172,10 +172,11 @@ export default function AppLayout() {
|
||||
onChange={handleStationChange}
|
||||
options={stationList.map(s => ({ label: s.siteName, value: s.id }))}
|
||||
style={{
|
||||
width: 'clamp(140px, 15vw, 180px)',
|
||||
width: 'clamp(160px, 15vw, 220px)',
|
||||
backgroundColor: '#0837a8',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
@@ -238,7 +239,6 @@ export default function AppLayout() {
|
||||
<div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8 }}>
|
||||
{currentStation.siteName || '1MW 光伏电站'}
|
||||
</div>
|
||||
{/* 这里可以放电站图片,用你自己的电站图片地址替换 */}
|
||||
<img style={{ width: '100%', borderRadius: "8px", marginBottom: 8 }} src="https://images.unsplash.com/photo-1509391366360-2e959784a276?ixlib=rb-1.2.1&auto=format&fit=crop&w=1200&q=80" />
|
||||
|
||||
{/* <img src="电站图片地址" style={{ width: '100%', borderRadius: 4, marginBottom: 8 }} alt="电站" /> */}
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
PlusOutlined, EditOutlined, DeleteOutlined, ProductOutlined,
|
||||
AppstoreOutlined, SwapOutlined, VideoCameraOutlined
|
||||
} from '@ant-design/icons';
|
||||
import { addDeviceModel, addProduct, deleteModel, getConnectTypes, getDataTypesApi, getDeviceModelList, getProductPage, updateDeviceModel, updateProduct } from '../../api/deviceAccess.ts';
|
||||
import { addDeviceModel, addProduct, deleteModel, deleteProduct, getConnectTypes, getDataTypesApi, getDeviceModelList, getProductPage, updateDeviceModel, updateProduct } from '../../api/deviceAccess.ts';
|
||||
|
||||
const { Option } = Select;
|
||||
const { TabPane } = Tabs;
|
||||
@@ -186,7 +186,7 @@ export default function DeviceAccessPage() {
|
||||
}
|
||||
} else {
|
||||
if (type === 'device') { setDeviceProtocol('onvif'); setModelDetail({ props: [] }); }
|
||||
else if (type === 'product') { setProductProtocol(''); setPropertyList([]); }
|
||||
else if (type === 'product') { setProductProtocol(''); setPropertyList([]); form.setFieldsValue({ status: 1 }) }
|
||||
else setModelDetail({ props: [], events: [], actions: [] });
|
||||
}
|
||||
setVisible(true);
|
||||
@@ -427,7 +427,14 @@ export default function DeviceAccessPage() {
|
||||
messageApi.success('删除成功');
|
||||
};
|
||||
const handleDeleteProduct = (data) => {
|
||||
|
||||
deleteProduct(data).then(res => {
|
||||
if (res.code === 200) {
|
||||
messageApi.success('删除成功');
|
||||
getProductList();
|
||||
} else {
|
||||
messageApi.error('删除失败:' + res.msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const getAlarmProps = () => modelDetail?.props?.filter(item => item.isAlarm) || [];
|
||||
@@ -456,21 +463,7 @@ export default function DeviceAccessPage() {
|
||||
{ title: '操作', render: r => <Button type="text" icon={<EditOutlined />} onClick={() => openModal('device', r)}>编辑</Button> }
|
||||
];
|
||||
|
||||
const productColumns = [
|
||||
{ title: '产品名称', dataIndex: 'name' },
|
||||
{ title: '厂商', dataIndex: 'manufacturer' },
|
||||
{ title: '协议', dataIndex: 'protocolType' },
|
||||
{ title: '上报Topic', dataIndex: 'publishTopic' },
|
||||
{ title: '订阅Topic', dataIndex: 'subscribeTopic' },
|
||||
{
|
||||
title: '操作', render: r => (
|
||||
<Space>
|
||||
<Button type="text" style={{ color: '#1677ff' }} icon={<EditOutlined />} onClick={() => openModal('product', r)}>编辑</Button>
|
||||
<Button type="text" icon={<SwapOutlined />} onClick={() => openMappingModal()}>字段映射</Button>
|
||||
</Space>
|
||||
)
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
const modelColumns = [
|
||||
{ title: '模型名称', dataIndex: 'name' },
|
||||
@@ -514,12 +507,12 @@ export default function DeviceAccessPage() {
|
||||
{activeTab === 'device' && <Card><Space className="mb-3"><Button type="primary" icon={<PlusOutlined />} onClick={() => openModal('device')}>新增设备</Button></Space><Table rowKey="id" columns={deviceColumns} dataSource={deviceList} /></Card>}
|
||||
{activeTab === 'product' && (
|
||||
<Card>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'end' }}>
|
||||
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'end', }}>
|
||||
<Form
|
||||
form={filterForm}
|
||||
layout="inline"
|
||||
initialValues={{ pageNum: 1, pageSize: 10 }}
|
||||
style={{ display: 'flex', gap: '16px', flexWrap: 'wrap', alignItems: 'center' }}
|
||||
style={{ display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' }}
|
||||
>
|
||||
<Form.Item name="code" label="产品编码">
|
||||
<Input placeholder="请输入编码" allowClear />
|
||||
@@ -544,7 +537,7 @@ export default function DeviceAccessPage() {
|
||||
<Option value="udp">UDP</Option>
|
||||
</Select>
|
||||
</Form.Item>
|
||||
<Form.Item name="status" label="状态">
|
||||
<Form.Item name="status" label="状态" initialValue={1}>
|
||||
<Select placeholder="状态" allowClear style={{ width: 100 }}>
|
||||
<Option value={1}>启用</Option>
|
||||
<Option value={0}>禁用</Option>
|
||||
@@ -568,7 +561,6 @@ export default function DeviceAccessPage() {
|
||||
{ title: '产品编码', dataIndex: 'code', width: 120 },
|
||||
{ title: '产品名称', dataIndex: 'name', width: 160 },
|
||||
{ title: '生产厂家', dataIndex: 'manufacturer', width: 130 },
|
||||
{ title: '分类ID', dataIndex: 'categoryId', width: 90 },
|
||||
{ title: '协议', dataIndex: 'protocolCode', width: 100 },
|
||||
{ title: '传输方式', dataIndex: 'transport', width: 100 },
|
||||
{ title: '上报Topic', dataIndex: 'uploadTopic', ellipsis: true },
|
||||
@@ -641,54 +633,129 @@ export default function DeviceAccessPage() {
|
||||
title={modalType === 'device' ? '设备配置' : modalType === 'product' ? '产品配置' : '物模型配置'}>
|
||||
<Form form={form} layout="vertical">
|
||||
{modalType === 'device' && (
|
||||
<Tabs defaultActiveKey="base">
|
||||
<TabPane tab="基础信息" key="base">
|
||||
<Form.Item label="设备名称" name="name" rules={[{ required: true }]}><Input /></Form.Item>
|
||||
<Form.Item label="设备SN" name="sn" rules={[{ required: true }]}><Input /></Form.Item>
|
||||
<Form.Item label="关联产品" name="productId" rules={[{ required: true }]}><Select>{productList.map(p => <Option key={p.id} value={p.id}>{p.name}</Option>)}</Select></Form.Item>
|
||||
</TabPane>
|
||||
<TabPane tab="协议配置" key="protocol">
|
||||
<Form.Item label="设备协议类型" name="protocolType" rules={[{ required: true }]}>
|
||||
<Select value={deviceProtocol} onChange={setDeviceProtocol}>
|
||||
{protocolList.map(p => (
|
||||
<Option key={p.code} value={p.code}>{p.name}</Option>
|
||||
))}
|
||||
</Select>
|
||||
<>
|
||||
<Form.Item
|
||||
label="设备名称"
|
||||
name="name"
|
||||
rules={[{ required: true, message: '请输入设备名称' }]}
|
||||
>
|
||||
<Input placeholder="请输入设备名称" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="设备SN"
|
||||
name="sn"
|
||||
rules={[{ required: true, message: '请输入设备SN' }]}
|
||||
>
|
||||
<Input placeholder="请输入设备SN" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="关联产品"
|
||||
name="productId"
|
||||
rules={[{ required: true, message: '请选择关联产品' }]}
|
||||
>
|
||||
<Select placeholder="请选择关联产品">
|
||||
{productList.map(p => (
|
||||
<Option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="设备协议类型"
|
||||
name="protocolType"
|
||||
rules={[{ required: true, message: '请选择协议类型' }]}
|
||||
>
|
||||
<Select
|
||||
value={deviceProtocol}
|
||||
onChange={setDeviceProtocol}
|
||||
placeholder="请选择协议类型"
|
||||
>
|
||||
{protocolList.map(p => (
|
||||
<Option key={p.code} value={p.code}>
|
||||
{p.name}
|
||||
</Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
|
||||
<Divider />
|
||||
|
||||
{/* ONVIF 配置 */}
|
||||
{deviceProtocol === 'ONVIF' && (
|
||||
<>
|
||||
<Form.Item label="IP 地址" name="ip">
|
||||
<Input placeholder="例如:192.168.1.65" />
|
||||
</Form.Item>
|
||||
<Form.Item label="端口" name="port">
|
||||
<InputNumber className="w-full" placeholder="默认 80" />
|
||||
</Form.Item>
|
||||
<Form.Item label="登录账号" name="username">
|
||||
<Input placeholder="设备登录账号" />
|
||||
</Form.Item>
|
||||
<Form.Item label="登录密码" name="password">
|
||||
<Input.Password placeholder="设备登录密码" />
|
||||
</Form.Item>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* RTSP 配置 */}
|
||||
{deviceProtocol === 'RTSP' && (
|
||||
<Form.Item label="RTSP 地址" name="rtspUrl">
|
||||
<Input placeholder="rtsp://username:password@ip:port/stream" />
|
||||
</Form.Item>
|
||||
<Divider />
|
||||
{deviceProtocol === 'onvif' && (
|
||||
<>
|
||||
<Form.Item label="IP" name="ip"><Input /></Form.Item>
|
||||
<Form.Item label="端口" name="port"><InputNumber className="w-full" /></Form.Item>
|
||||
<Form.Item label="账号" name="username"><Input /></Form.Item>
|
||||
<Form.Item label="密码" name="password"><Input.Password /></Form.Item>
|
||||
</>
|
||||
)}
|
||||
{deviceProtocol === 'rtsp' && <Form.Item label="RTSP地址" name="rtspUrl"><Input /></Form.Item>}
|
||||
{deviceProtocol === 'mqtt' && (
|
||||
<>
|
||||
<Form.Item label="MQTT服务地址" name="mqttServer"><Input /></Form.Item>
|
||||
<Form.Item label="端口" name="mqttPort"><InputNumber defaultValue={1883} /></Form.Item>
|
||||
<Form.Item label="ClientID" name="clientId"><Input /></Form.Item>
|
||||
<Form.Item label="用户名" name="mqttUsername"><Input /></Form.Item>
|
||||
<Form.Item label="密码" name="mqttPassword"><Input.Password /></Form.Item>
|
||||
</>
|
||||
)}
|
||||
</TabPane>
|
||||
<TabPane tab="报警阈值" key="alarm">
|
||||
{getAlarmProps().map(item => (
|
||||
<div key={item.code} className="flex gap-2">
|
||||
<Form.Item label={`${item.name}上限`} name={['alarmConfig', `${item.code}Max`]} style={{ flex: 1 }}>
|
||||
<InputNumber className="w-full" />
|
||||
)}
|
||||
|
||||
{/* MQTT 配置 */}
|
||||
{deviceProtocol === 'MQTT' && (
|
||||
<>
|
||||
<Form.Item label="MQTT 服务地址" name="mqttServer">
|
||||
<Input placeholder="tcp://192.168.1.200" />
|
||||
</Form.Item>
|
||||
<Form.Item label="MQTT 端口" name="mqttPort">
|
||||
<InputNumber className="w-full" defaultValue={1883} />
|
||||
</Form.Item>
|
||||
<Form.Item label="ClientID" name="clientId">
|
||||
<Input placeholder="客户端唯一标识" />
|
||||
</Form.Item>
|
||||
<Form.Item label="MQTT 用户名" name="mqttUsername">
|
||||
<Input placeholder="MQTT 账号(选填)" />
|
||||
</Form.Item>
|
||||
<Form.Item label="MQTT 密码" name="mqttPassword">
|
||||
<Input.Password placeholder="MQTT 密码(选填)" />
|
||||
</Form.Item>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 告警阈值配置 */}
|
||||
<Divider>告警阈值配置</Divider>
|
||||
|
||||
{getAlarmProps().length > 0 ? (
|
||||
getAlarmProps().map(item => (
|
||||
<div key={item.code} className="flex gap-3 items-end">
|
||||
<Form.Item
|
||||
label={`${item.name} 上限`}
|
||||
name={['alarmConfig', `${item.code}Max`]}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<InputNumber className="w-full" placeholder="上限值" />
|
||||
</Form.Item>
|
||||
<Form.Item label={`${item.name}下限`} name={['alarmConfig', `${item.code}Min`]} style={{ flex: 1 }}>
|
||||
<InputNumber className="w-full" />
|
||||
<Form.Item
|
||||
label={`${item.name} 下限`}
|
||||
name={['alarmConfig', `${item.code}Min`]}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<InputNumber className="w-full" placeholder="下限值" />
|
||||
</Form.Item>
|
||||
</div>
|
||||
))}
|
||||
{getAlarmProps().length === 0 && <Empty description="无告警参数" />}
|
||||
</TabPane>
|
||||
</Tabs>
|
||||
))
|
||||
) : (
|
||||
<Empty description="当前物模型未设置告警属性,无法配置阈值" />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{modalType === 'product' && (
|
||||
@@ -703,9 +770,9 @@ export default function DeviceAccessPage() {
|
||||
<Form.Item label="厂商" name="manufacturer">
|
||||
<Input placeholder="迈步科技" />
|
||||
</Form.Item>
|
||||
<Form.Item label="分类ID" name="categoryId">
|
||||
{/*<Form.Item label="分类ID" name="categoryId">
|
||||
<InputNumber style={{ width: '100%' }} min={1} />
|
||||
</Form.Item>
|
||||
</Form.Item>*/}
|
||||
<Form.Item label="协议" name="protocolCode" rules={[{ required: true }]}>
|
||||
<Select placeholder="选择协议">
|
||||
{protocolList.map(p => (
|
||||
@@ -804,9 +871,9 @@ export default function DeviceAccessPage() {
|
||||
</Select>
|
||||
</Form.Item>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
{/*<div className="flex-1">
|
||||
<Form.Item label="设备类型" name="deviceType" initialValue={1}><InputNumber style={{ width: '100%' }} /></Form.Item>
|
||||
</div>
|
||||
</div>*/}
|
||||
</div>
|
||||
|
||||
<Divider>属性</Divider>
|
||||
|
||||
@@ -2,34 +2,70 @@ import React, { useEffect, useRef } from "react";
|
||||
import { joinRoom, leaveRoom } from "./droneplayer";
|
||||
import { postLiveHeartbeat } from "@/api/api";
|
||||
|
||||
export default function DroneLivePlayer({ streamData, videoMode = "NORMAL" }) {
|
||||
console.log(streamData)
|
||||
export default function DroneLivePlayer({
|
||||
streamData,
|
||||
videoMode = "NORMAL",
|
||||
}) {
|
||||
const containerRef = useRef(null);
|
||||
|
||||
// 心跳 timer
|
||||
const timerRef = useRef(null);
|
||||
|
||||
// ------------ 核心修复:防止异步竞态 ------------
|
||||
const isBusyRef = useRef(false); // 正在加入/离开,禁止重复操作
|
||||
const mountedRef = useRef(true); // 组件是否挂载
|
||||
// 当前 effect 是否有效(防止异步穿透)
|
||||
const aliveRef = useRef(false);
|
||||
|
||||
// 防止 join / leave 并发
|
||||
const busyRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
const container = containerRef.current;
|
||||
|
||||
// 清空容器,防止 DOM 不为空
|
||||
if (container) container.innerHTML = "";
|
||||
// 当前 effect 生效
|
||||
aliveRef.current = true;
|
||||
|
||||
if (!container || !streamData?.url) return;
|
||||
if (!container) return;
|
||||
|
||||
// 强制清空旧 DOM
|
||||
container.innerHTML = "";
|
||||
|
||||
// 没有流地址直接退出
|
||||
if (!streamData?.url) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------------- 解析 RTC 参数 ----------------
|
||||
|
||||
// 解析参数
|
||||
const params = new URLSearchParams(streamData.url);
|
||||
const appId = (params.get("app_id") || params.get("appid") || "").trim();
|
||||
const roomId = (params.get("room_id") || params.get("roomid") || "").trim();
|
||||
const token = decodeURIComponent((params.get("token") || "").trim());
|
||||
const userId = (params.get("user_id") || params.get("uid") || "").trim();
|
||||
|
||||
if (!appId || !roomId || !token || !userId) return;
|
||||
const appId = (
|
||||
params.get("app_id") ||
|
||||
params.get("appid") ||
|
||||
""
|
||||
).trim();
|
||||
|
||||
const roomId = (
|
||||
params.get("room_id") ||
|
||||
params.get("roomid") ||
|
||||
""
|
||||
).trim();
|
||||
|
||||
const token = decodeURIComponent(
|
||||
(params.get("token") || "").trim()
|
||||
);
|
||||
|
||||
const userId = (
|
||||
params.get("user_id") ||
|
||||
params.get("uid") ||
|
||||
""
|
||||
).trim();
|
||||
|
||||
if (!appId || !roomId || !token || !userId) {
|
||||
console.error("RTC 参数缺失");
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------------- 心跳 ----------------
|
||||
|
||||
// 心跳
|
||||
const liveheartbeat = async () => {
|
||||
try {
|
||||
await postLiveHeartbeat({
|
||||
@@ -41,46 +77,89 @@ export default function DroneLivePlayer({ streamData, videoMode = "NORMAL" }) {
|
||||
}
|
||||
};
|
||||
|
||||
// ---------------- 真正安全的初始化流程 ----------------
|
||||
const safeInit = async () => {
|
||||
// 1. 防止并发:正在忙就直接退出
|
||||
if (isBusyRef.current) return;
|
||||
isBusyRef.current = true;
|
||||
// ---------------- 初始化 RTC ----------------
|
||||
|
||||
const initRTC = async () => {
|
||||
// 防止重复进入
|
||||
if (busyRef.current) return;
|
||||
|
||||
busyRef.current = true;
|
||||
|
||||
try {
|
||||
// 2. 【强制顺序】先销毁旧房间 + 清心跳
|
||||
// =========================
|
||||
// 1. 先彻底关闭旧 RTC
|
||||
// =========================
|
||||
|
||||
if (timerRef.current) {
|
||||
clearInterval(timerRef.current);
|
||||
timerRef.current = null;
|
||||
}
|
||||
leaveRoom(); // 先离开旧房间
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
// 3. 组件已卸载,直接放弃
|
||||
if (!mountedRef.current) {
|
||||
isBusyRef.current = false;
|
||||
// 必须 await
|
||||
await leaveRoom();
|
||||
|
||||
// 给 SDK 一点释放时间
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, 300)
|
||||
);
|
||||
|
||||
// 组件已经卸载
|
||||
if (!aliveRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 4. 加入新房间(此时绝对安全)
|
||||
await joinRoom(container, appId, roomId, token, userId, videoMode);
|
||||
// =========================
|
||||
// 2. 加入新房间
|
||||
// =========================
|
||||
|
||||
// 5. 开启心跳
|
||||
//timerRef.current = setInterval(liveheartbeat, 3000);
|
||||
//liveheartbeat();
|
||||
await joinRoom(
|
||||
container,
|
||||
appId,
|
||||
roomId,
|
||||
token,
|
||||
userId,
|
||||
videoMode
|
||||
);
|
||||
|
||||
// 再次检查
|
||||
if (!aliveRef.current) {
|
||||
await leaveRoom();
|
||||
return;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 3. 开启心跳
|
||||
// =========================
|
||||
|
||||
/*
|
||||
timerRef.current = setInterval(() => {
|
||||
liveheartbeat();
|
||||
}, 3000);
|
||||
|
||||
liveheartbeat();
|
||||
*/
|
||||
} catch (err) {
|
||||
console.error("RTC 初始化失败", err);
|
||||
console.error("RTC 初始化失败:", err);
|
||||
|
||||
// 出错强制释放
|
||||
try {
|
||||
await leaveRoom();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
} finally {
|
||||
// 解锁
|
||||
isBusyRef.current = false;
|
||||
busyRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
safeInit();
|
||||
initRTC();
|
||||
|
||||
// =========================
|
||||
// cleanup
|
||||
// =========================
|
||||
|
||||
// ---------------- 清理函数 ----------------
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
aliveRef.current = false;
|
||||
|
||||
// 清理心跳
|
||||
if (timerRef.current) {
|
||||
@@ -88,8 +167,19 @@ export default function DroneLivePlayer({ streamData, videoMode = "NORMAL" }) {
|
||||
timerRef.current = null;
|
||||
}
|
||||
|
||||
// 离开房间
|
||||
leaveRoom();
|
||||
// 异步释放 RTC
|
||||
(async () => {
|
||||
try {
|
||||
await leaveRoom();
|
||||
|
||||
// 清空 DOM
|
||||
if (containerRef.current) {
|
||||
containerRef.current.innerHTML = "";
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("leaveRoom error:", err);
|
||||
}
|
||||
})();
|
||||
};
|
||||
}, [
|
||||
streamData?.url,
|
||||
@@ -102,7 +192,12 @@ export default function DroneLivePlayer({ streamData, videoMode = "NORMAL" }) {
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="rounded"
|
||||
style={{ width: "100%", height: "100%", background: "#000" }}
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
background: "#000",
|
||||
overflow: "hidden",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,34 +1,159 @@
|
||||
import VERTC, { RoomProfileType, StreamIndex } from "@volcengine/rtc";
|
||||
import VERTC, {
|
||||
RoomProfileType,
|
||||
StreamIndex,
|
||||
} from "@volcengine/rtc";
|
||||
|
||||
let engine;
|
||||
let engine = null;
|
||||
|
||||
export async function joinRoom(container, appId, roomId, token, userId) {
|
||||
console.info('joinRoom...');
|
||||
|
||||
const engine = VERTC.createEngine(appId);
|
||||
let currentRemoteUserId = null;
|
||||
|
||||
await engine.joinRoom(token, roomId, { userId }, {
|
||||
isAutoPublish: true,
|
||||
isAutoSubscribeAudio: true,
|
||||
isAutoSubscribeVideo: true,
|
||||
roomProfileType: RoomProfileType.meeting,
|
||||
});
|
||||
let isJoining = false;
|
||||
|
||||
engine.on(VERTC.events.onUserPublishStream, async (e) => {
|
||||
if (!container) return;
|
||||
|
||||
// 清空旧内容
|
||||
container.innerHTML = '';
|
||||
// =========================
|
||||
// 创建单例 engine
|
||||
// =========================
|
||||
|
||||
await engine.setUserVisibility(false);
|
||||
engine.setRemoteVideoPlayer(StreamIndex.STREAM_INDEX_MAIN, {
|
||||
userId: e.userId,
|
||||
renderDom: container,
|
||||
visible: true,
|
||||
});
|
||||
});
|
||||
function getEngine(appId) {
|
||||
if (!engine) {
|
||||
engine = VERTC.createEngine(appId);
|
||||
}
|
||||
|
||||
return engine;
|
||||
}
|
||||
|
||||
|
||||
// =========================
|
||||
// 加入房间
|
||||
// =========================
|
||||
|
||||
export async function joinRoom(
|
||||
container,
|
||||
appId,
|
||||
roomId,
|
||||
token,
|
||||
userId
|
||||
) {
|
||||
if (isJoining) {
|
||||
console.warn("正在 joinRoom,跳过");
|
||||
return;
|
||||
}
|
||||
|
||||
isJoining = true;
|
||||
|
||||
try {
|
||||
console.log("joinRoom start");
|
||||
|
||||
// 先离开旧房间
|
||||
await leaveRoom();
|
||||
|
||||
const rtcEngine = getEngine(appId);
|
||||
|
||||
// 防止重复监听
|
||||
rtcEngine.removeAllListeners();
|
||||
|
||||
// 监听远端流
|
||||
rtcEngine.on(
|
||||
VERTC.events.onUserPublishStream,
|
||||
async (e) => {
|
||||
console.log("收到远端流", e);
|
||||
|
||||
currentRemoteUserId = e.userId;
|
||||
|
||||
if (!container) return;
|
||||
|
||||
try {
|
||||
// 清空旧 video
|
||||
container.innerHTML = "";
|
||||
|
||||
// 隐藏本地
|
||||
await rtcEngine.setUserVisibility(false);
|
||||
|
||||
// 播放远端
|
||||
rtcEngine.setRemoteVideoPlayer(
|
||||
StreamIndex.STREAM_INDEX_MAIN,
|
||||
{
|
||||
userId: e.userId,
|
||||
renderDom: container,
|
||||
visible: true,
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// 加入房间
|
||||
await rtcEngine.joinRoom(
|
||||
token,
|
||||
roomId,
|
||||
{ userId },
|
||||
{
|
||||
isAutoPublish: false,
|
||||
isAutoSubscribeAudio: false,
|
||||
isAutoSubscribeVideo: true,
|
||||
roomProfileType:
|
||||
RoomProfileType.meeting,
|
||||
}
|
||||
);
|
||||
|
||||
console.log("joinRoom success");
|
||||
} catch (err) {
|
||||
console.error("joinRoom failed", err);
|
||||
} finally {
|
||||
isJoining = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================
|
||||
// 离开房间
|
||||
// =========================
|
||||
|
||||
export async function leaveRoom() {
|
||||
if (engine) await engine.leaveRoom();
|
||||
if (!engine) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("leaveRoom start");
|
||||
|
||||
try {
|
||||
// 移除事件
|
||||
engine.removeAllListeners();
|
||||
|
||||
// 停止远端渲染
|
||||
if (currentRemoteUserId) {
|
||||
try {
|
||||
engine.setRemoteVideoPlayer(
|
||||
StreamIndex.STREAM_INDEX_MAIN,
|
||||
{
|
||||
userId: currentRemoteUserId,
|
||||
renderDom: null,
|
||||
visible: false,
|
||||
}
|
||||
);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
// 离开房间
|
||||
try {
|
||||
await engine.leaveRoom();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
// 等待 SDK 内部释放
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, 500)
|
||||
);
|
||||
|
||||
currentRemoteUserId = null;
|
||||
|
||||
console.log("leaveRoom success");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user