feat: 无人机视频播放

This commit is contained in:
2025-12-16 11:44:00 +08:00
parent cb912a8c60
commit 8990daf861
5 changed files with 995 additions and 0 deletions
@@ -0,0 +1,75 @@
.whepPlayer {
position: relative;
width: 100%;
height: 100%;
background: #000;
border-radius: 4px;
overflow: hidden;
}
.video {
width: 100%;
height: 100%;
object-fit: contain;
background: #000;
}
.overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.85);
color: rgba(255, 255, 255, 0.85);
gap: 12px;
}
.icon {
font-size: 48px;
color: rgba(255, 255, 255, 0.3);
}
.errorIcon {
font-size: 48px;
color: #ff4d4f;
}
.text {
font-size: 14px;
color: rgba(255, 255, 255, 0.65);
}
.subText {
font-size: 12px;
color: rgba(255, 255, 255, 0.45);
font-family: monospace;
}
.retryBtn {
margin-top: 8px;
padding: 6px 16px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 4px;
color: rgba(255, 255, 255, 0.85);
cursor: pointer;
font-size: 13px;
display: flex;
align-items: center;
gap: 6px;
transition: all 0.2s;
&:hover {
background: rgba(255, 255, 255, 0.2);
border-color: rgba(255, 255, 255, 0.3);
}
&:active {
background: rgba(255, 255, 255, 0.15);
}
}
@@ -0,0 +1,179 @@
import React, { useRef, useEffect, useState, useCallback } from 'react';
import { Spin } from 'antd';
import {
LoadingOutlined,
ReloadOutlined,
VideoCameraOutlined,
ExclamationCircleOutlined,
} from '@ant-design/icons';
import { srsApi } from '@/services/srs';
import styles from './WhepPlayer.less';
interface WhepPlayerProps {
/** 视频流完整地址(WHEP URL) */
url: string;
/** 是否自动播放 */
autoPlay?: boolean;
/** 是否静音(用于自动播放) */
muted?: boolean;
/** 只播放视频 */
videoOnly?: boolean;
/** 只播放音频 */
audioOnly?: boolean;
/** 样式类名 */
className?: string;
/** 播放成功回调 */
onPlaySuccess?: () => void;
/** 播放失败回调 */
onPlayError?: (error: string) => void;
/** 连接状态变化回调 */
onConnectionChange?: (connected: boolean) => void;
}
type PlayerStatus = 'idle' | 'connecting' | 'playing' | 'error';
const WhepPlayer: React.FC<WhepPlayerProps> = ({
url,
autoPlay = true,
muted = true,
videoOnly = false,
audioOnly = false,
className,
onPlaySuccess,
onPlayError,
onConnectionChange,
}) => {
const videoRef = useRef<HTMLVideoElement>(null);
const pcRef = useRef<RTCPeerConnection | null>(null);
const streamRef = useRef<MediaStream | null>(null);
const [status, setStatus] = useState<PlayerStatus>('idle');
const [errorMsg, setErrorMsg] = useState<string>('');
const [retryCount, setRetryCount] = useState(0);
// 清理资源
const cleanup = useCallback(() => {
if (streamRef.current) {
streamRef.current.getTracks().forEach(track => track.stop());
streamRef.current = null;
}
if (pcRef.current) {
pcRef.current.close();
pcRef.current = null;
}
if (videoRef.current) {
videoRef.current.srcObject = null;
}
}, []);
// 开始播放
const startPlay = useCallback(async () => {
if (!url) {
setStatus('error');
setErrorMsg('未配置视频流地址');
return;
}
cleanup();
setStatus('connecting');
setErrorMsg('');
const result = await srsApi.playWhepByUrl(url, videoRef.current!, {
videoOnly,
audioOnly,
});
if (result.success && result.pc && result.stream) {
pcRef.current = result.pc;
streamRef.current = result.stream;
setStatus('playing');
setRetryCount(0);
onPlaySuccess?.();
onConnectionChange?.(true);
// 监听连接状态
result.pc.onconnectionstatechange = () => {
const state = result.pc?.connectionState;
if (state === 'disconnected' || state === 'failed' || state === 'closed') {
setStatus('error');
setErrorMsg('连接已断开');
onConnectionChange?.(false);
}
};
// 监听 ICE 连接状态(静默)
result.pc.oniceconnectionstatechange = () => {};
} else {
setStatus('error');
setErrorMsg(result.error || '连接失败');
onPlayError?.(result.error || '连接失败');
onConnectionChange?.(false);
}
}, [url, videoOnly, audioOnly, cleanup, onPlaySuccess, onPlayError, onConnectionChange]);
// 重试播放
const retry = useCallback(() => {
setRetryCount(prev => prev + 1);
startPlay();
}, [startPlay]);
// 自动播放
useEffect(() => {
if (autoPlay && url) {
startPlay();
}
return () => {
cleanup();
};
}, [url, autoPlay]); // 不要把 startPlay 和 cleanup 加入依赖
// 渲染状态覆盖层
const renderOverlay = () => {
switch (status) {
case 'connecting':
return (
<div className={styles.overlay}>
<Spin indicator={<LoadingOutlined style={{ fontSize: 32 }} spin />} />
<span className={styles.text}>正在连接视频流...</span>
</div>
);
case 'error':
return (
<div className={styles.overlay}>
<ExclamationCircleOutlined className={styles.errorIcon} />
<span className={styles.text}>{errorMsg}</span>
<button className={styles.retryBtn} onClick={retry}>
<ReloadOutlined /> 重试 {retryCount > 0 ? `(${retryCount})` : ''}
</button>
</div>
);
case 'idle':
return (
<div className={styles.overlay}>
<VideoCameraOutlined className={styles.icon} />
<span className={styles.text}>等待图传信号...</span>
</div>
);
default:
return null;
}
};
return (
<div className={`${styles.whepPlayer} ${className || ''}`}>
<video
ref={videoRef}
autoPlay
playsInline
muted={muted}
controls={false}
className={styles.video}
/>
{status !== 'playing' && renderOverlay()}
</div>
);
};
export default WhepPlayer;
@@ -0,0 +1,302 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { message } from 'antd';
// 无人机遥测数据接口定义(从useDeviceSSE.ts复制)
export interface DroneData {
// 飞行姿态
attitude_pitch?: number; // 俯仰角 (度)
attitude_roll?: number; // 横滚角 (度)
attitude_head?: number; // 偏航角/航向 (度)
// 速度
horizontal_speed?: number; // 水平速度 (m/s)
vertical_speed?: number; // 垂直速度 (m/s)
ground_speed?: number; // 地面速度 (m/s)
// 位置
latitude?: number; // 纬度
longitude?: number; // 经度
height?: number; // 高度 (m)
elevation?: number; // 海拔高度 (m)
home_distance?: number; // 距Home点距离 (m)
// 电池
battery?: {
capacity_percent?: number; // 电量百分比
voltage?: number; // 电压 (mV)
temperature?: number; // 温度 (°C)
remain_flight_time?: number; // 剩余飞行时间 (s)
remain_job_time?: number; // 剩余作业时间 (s)
landing_power?: number; // 降落电量
return_home_power?: number; // 返航电量
// 电池组详细信息(嵌套结构)
batteries?: Array<{
capacity_percent?: number; // 电量百分比
voltage?: number; // 电压 (mV)
temperature?: number; // 温度 (°C)
sn?: string; // 电池序列号
index?: number; // 电池索引
type?: number; // 电池类型
sub_type?: number; // 子类型
loop_times?: number; // 循环次数
firmware_version?: string; // 固件版本
high_voltage_storage_days?: number; // 高压存储天数
}>;
};
// 飞行模式
mode_code?: number; // 飞行模式代码
gear?: number; // 档位
// RTK/GPS
position_state?: {
rtk_number?: number; // RTK 卫星数
gps_number?: number; // GPS 卫星数
gps_level?: number; // GPS 等级
};
// 飞行状态
flight_status?: number; // 飞行状态
is_flying?: number; // 是否在飞行
flight_time?: number; // 飞行时间 (s)
// 其他
[key: string]: any;
}
// 无人机SSE Hook返回值接口
export interface UseDroneSSEReturn {
// 状态
droneData: DroneData | null;
sseConnected: boolean;
loading: boolean;
hasData: boolean; // 是否已经收到过数据
// 方法
connectDroneSSE: (deviceSn: string) => Promise<void>;
disconnectDroneSSE: (deviceSn?: string) => Promise<void>;
resetDroneData: () => void;
}
/**
* 无人机SSE Hook(独立连接)
* 专门用于接收无人机遥测数据(msg_alarm),与机库状态数据完全分离
*
* 特性:
* 1. 独立的SSE连接,不与机库数据混合
* 2. 专门接收无人机遥测数据(drone-data-update事件)
* 3. 支持等待机制,直到收到数据
*
* @returns UseDroneSSEReturn
*/
export const useDroneSSE = (): UseDroneSSEReturn => {
// 状态
const [droneData, setDroneData] = useState<DroneData | null>(null);
const [sseConnected, setSSEConnected] = useState(false);
const [loading, setLoading] = useState(false);
const [hasData, setHasData] = useState(false); // 是否已经收到过数据
// Refs
const abortControllerRef = useRef<AbortController | null>(null);
const currentDeviceSnRef = useRef<string>('');
const clientSessionIdRef = useRef<string>(
`drone_client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
);
const dataReceivedRef = useRef<boolean>(false); // 用于跟踪是否已收到数据
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
if (!deviceSn || !token) return;
// 尝试使用 fetch keepalive
fetch(`/api-device/sse/drone-telemetry/${deviceSn}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': sessionId,
},
keepalive: true,
}).catch(() => {});
};
// 断开无人机SSE连接
const disconnectDroneSSE = useCallback(async (deviceSn?: string) => {
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
// 1. 取消当前的 fetch 连接 (客户端主动断开)
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
// 2. 发送请求通知后端 (服务端清理资源)
if (snToDisconnect) {
const token = sessionStorage.getItem('access_token');
performDisconnect(snToDisconnect, clientSessionIdRef.current, token);
}
// 3. 重置状态
setSSEConnected(false);
setLoading(false);
setHasData(false);
dataReceivedRef.current = false;
currentDeviceSnRef.current = '';
}, []);
// 处理SSE事件(专门处理无人机数据)
const handleSSEEvent = useCallback((eventName: string, data: string) => {
try {
if (eventName === 'connected') {
setSSEConnected(true);
setLoading(false);
} else if (eventName === 'drone-data-update') {
const parsedData = JSON.parse(data) as DroneData;
setDroneData(parsedData);
// 标记已收到数据
if (!dataReceivedRef.current) {
dataReceivedRef.current = true;
setHasData(true);
}
}
// heartbeat 和其他事件静默处理
} catch (error) {
// 静默处理解析错误
}
}, []);
// 连接无人机SSE
const connectDroneSSE = useCallback(async (deviceSn: string) => {
// 如果已经连接了同一个设备,先断开旧的
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
await disconnectDroneSSE(currentDeviceSnRef.current);
}
if (!deviceSn) {
return;
}
// 重置状态
setDroneData(null);
setHasData(false);
dataReceivedRef.current = false;
currentDeviceSnRef.current = deviceSn;
setLoading(true);
try {
const token = sessionStorage.getItem('access_token');
const url = `/api-device/sse/drone-telemetry/${deviceSn}`; // 使用无人机SSE接口
// 创建 AbortController 用于取消请求
const abortController = new AbortController();
abortControllerRef.current = abortController;
// 使用 fetch 发起SSE请求
const response = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'text/event-stream',
'Cache-Control': 'no-cache',
'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': clientSessionIdRef.current,
},
cache: 'no-store',
signal: abortController.signal,
});
if (!response.ok) {
throw new Error(`无人机SSE连接失败: ${response.status}`);
}
// 读取SSE流
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) {
throw new Error('无法获取SSE流读取器');
}
let buffer = '';
// 持续读取SSE流
const readStream = async () => {
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
setSSEConnected(false);
break;
}
buffer += decoder.decode(value, { stream: true });
// 解析SSE消息
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // 保留未完成的行
let eventName = 'message';
let data = '';
for (const line of lines) {
if (line.startsWith('event:')) {
eventName = line.substring(6).trim();
} else if (line.startsWith('data:')) {
data = line.substring(5).trim();
} else if (line === '') {
// 空行表示消息结束
if (data) {
handleSSEEvent(eventName, data);
}
eventName = 'message';
data = '';
}
}
}
} catch (error) {
setSSEConnected(false);
setLoading(false);
}
};
readStream();
} catch (error) {
setSSEConnected(false);
setLoading(false);
if (error instanceof Error) {
message.error(`无人机SSE连接失败: ${error.message}`);
}
}
}, [disconnectDroneSSE, handleSSEEvent]);
// 重置无人机数据
const resetDroneData = useCallback(() => {
setDroneData(null);
setHasData(false);
dataReceivedRef.current = false;
}, []);
// 组件卸载时自动断开连接
useEffect(() => {
return () => {
if (currentDeviceSnRef.current) {
disconnectDroneSSE(currentDeviceSnRef.current);
}
};
}, [disconnectDroneSSE]);
return {
// 状态
droneData,
sseConnected,
loading,
hasData,
// 方法
connectDroneSSE,
disconnectDroneSSE,
resetDroneData,
};
};