feat: 无人机视频播放
This commit is contained in:
+183
@@ -0,0 +1,183 @@
|
|||||||
|
package com.central.device.websocket.model;
|
||||||
|
|
||||||
|
import com.alibaba.fastjson.JSONObject;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 无人机实时数据
|
||||||
|
* 专门存储无人机的实时遥测数据(msg_alarm)
|
||||||
|
* 与机库数据完全分离
|
||||||
|
*
|
||||||
|
* @author dzc
|
||||||
|
* @date 2025-12-11
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class DroneRealtimeData {
|
||||||
|
/**
|
||||||
|
* 设备SN
|
||||||
|
*/
|
||||||
|
private String deviceSn;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否在线
|
||||||
|
*/
|
||||||
|
private boolean online;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 最后消息时间戳
|
||||||
|
*/
|
||||||
|
private long lastMessageTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 纬度
|
||||||
|
*/
|
||||||
|
private Double latitude;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 经度
|
||||||
|
*/
|
||||||
|
private Double longitude;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 高度(m)
|
||||||
|
*/
|
||||||
|
private Double height;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 海拔(m)
|
||||||
|
*/
|
||||||
|
private Double elevation;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 水平速度(m/s)
|
||||||
|
*/
|
||||||
|
private Double horizontalSpeed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 垂直速度(m/s)
|
||||||
|
*/
|
||||||
|
private Double verticalSpeed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 风速(m/s)
|
||||||
|
*/
|
||||||
|
private Double windSpeed;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 姿态 - 俯仰角(度)
|
||||||
|
*/
|
||||||
|
private Double attitudePitch;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 姿态 - 横滚角(度)
|
||||||
|
*/
|
||||||
|
private Double attitudeRoll;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 姿态 - 偏航角(度)
|
||||||
|
*/
|
||||||
|
private Double attitudeYaw;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返航高度(m)
|
||||||
|
*/
|
||||||
|
private Integer rthAltitude;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 国家代码
|
||||||
|
*/
|
||||||
|
private String country;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 原始无人机数据
|
||||||
|
*/
|
||||||
|
private JSONObject rawData;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从原始无人机数据创建
|
||||||
|
*/
|
||||||
|
public static DroneRealtimeData fromRawData(String deviceSn, JSONObject rawDroneData) {
|
||||||
|
if (rawDroneData == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
DroneRealtimeData droneData = new DroneRealtimeData();
|
||||||
|
droneData.setDeviceSn(deviceSn);
|
||||||
|
droneData.setOnline(true);
|
||||||
|
droneData.setLastMessageTime(System.currentTimeMillis());
|
||||||
|
droneData.setRawData(rawDroneData);
|
||||||
|
|
||||||
|
// 提取字段
|
||||||
|
droneData.setLatitude(rawDroneData.getDouble("latitude"));
|
||||||
|
droneData.setLongitude(rawDroneData.getDouble("longitude"));
|
||||||
|
droneData.setHeight(rawDroneData.getDouble("height"));
|
||||||
|
droneData.setElevation(rawDroneData.getDouble("elevation"));
|
||||||
|
droneData.setHorizontalSpeed(rawDroneData.getDouble("horizontal_speed"));
|
||||||
|
droneData.setVerticalSpeed(rawDroneData.getDouble("vertical_speed"));
|
||||||
|
droneData.setWindSpeed(rawDroneData.getDouble("wind_speed"));
|
||||||
|
droneData.setAttitudePitch(rawDroneData.getDouble("attitude_pitch"));
|
||||||
|
droneData.setAttitudeRoll(rawDroneData.getDouble("attitude_roll"));
|
||||||
|
droneData.setAttitudeYaw(rawDroneData.getDouble("attitude_yaw"));
|
||||||
|
droneData.setRthAltitude(rawDroneData.getInteger("rth_altitude"));
|
||||||
|
droneData.setCountry(rawDroneData.getString("country"));
|
||||||
|
|
||||||
|
return droneData;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 转换为前端兼容的JSON对象(使用下划线命名)
|
||||||
|
*/
|
||||||
|
public JSONObject toFrontendJson() {
|
||||||
|
JSONObject json = new JSONObject();
|
||||||
|
|
||||||
|
// 基本字段
|
||||||
|
json.put("deviceSn", deviceSn);
|
||||||
|
|
||||||
|
// 位置字段
|
||||||
|
json.put("latitude", latitude);
|
||||||
|
json.put("longitude", longitude);
|
||||||
|
json.put("height", height);
|
||||||
|
json.put("elevation", elevation);
|
||||||
|
json.put("home_distance", 0); // 需要从原始数据获取
|
||||||
|
|
||||||
|
// 速度字段
|
||||||
|
json.put("horizontal_speed", horizontalSpeed);
|
||||||
|
json.put("vertical_speed", verticalSpeed);
|
||||||
|
json.put("ground_speed", horizontalSpeed); // 使用水平速度作为地面速度
|
||||||
|
|
||||||
|
// 姿态字段
|
||||||
|
json.put("attitude_pitch", attitudePitch);
|
||||||
|
json.put("attitude_roll", attitudeRoll);
|
||||||
|
json.put("attitude_head", attitudeYaw); // 注意:前端使用 attitude_head
|
||||||
|
|
||||||
|
// 电池字段
|
||||||
|
if (rawData != null && rawData.containsKey("battery")) {
|
||||||
|
json.put("battery", rawData.getJSONObject("battery"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 飞行模式
|
||||||
|
if (rawData != null) {
|
||||||
|
json.put("mode_code", rawData.getInteger("mode_code"));
|
||||||
|
json.put("gear", rawData.getInteger("gear"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 位置状态
|
||||||
|
if (rawData != null && rawData.containsKey("position_state")) {
|
||||||
|
json.put("position_state", rawData.getJSONObject("position_state"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 飞行状态
|
||||||
|
if (rawData != null) {
|
||||||
|
json.put("flight_status", rawData.getInteger("flight_status"));
|
||||||
|
json.put("is_flying", rawData.getInteger("is_flying"));
|
||||||
|
json.put("flight_time", rawData.getInteger("flight_time"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 其他字段
|
||||||
|
json.put("wind_speed", windSpeed);
|
||||||
|
json.put("rth_altitude", rthAltitude);
|
||||||
|
json.put("country", country);
|
||||||
|
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
}
|
||||||
+75
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+179
@@ -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;
|
||||||
+302
@@ -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,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
/**
|
||||||
|
* SRS 流媒体服务
|
||||||
|
* 处理 SRS 服务器认证和 WebRTC WHEP 视频流播放
|
||||||
|
*/
|
||||||
|
|
||||||
|
// SRS 服务器配置
|
||||||
|
const SRS_CONFIG = {
|
||||||
|
// 开发环境通过代理访问,生产环境直接访问
|
||||||
|
baseUrl: process.env.NODE_ENV === 'development' ? '' : 'http://220.205.16.27:8024',
|
||||||
|
// 登录密码
|
||||||
|
password: 'a6949674ed817fa3',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 存储 token
|
||||||
|
let srsToken: string | null = null;
|
||||||
|
let tokenExpireTime: number = 0;
|
||||||
|
|
||||||
|
export interface SrsLoginResponse {
|
||||||
|
code: number;
|
||||||
|
data?: {
|
||||||
|
token: string;
|
||||||
|
[key: string]: any;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const srsApi = {
|
||||||
|
/**
|
||||||
|
* 登录 SRS 服务器获取 token
|
||||||
|
* @param password 登录密码
|
||||||
|
*/
|
||||||
|
login: async (password?: string): Promise<{ success: boolean; token?: string; error?: string }> => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${SRS_CONFIG.baseUrl}/terraform/v1/mgmt/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ password: password || SRS_CONFIG.password }),
|
||||||
|
credentials: 'include', // 重要:携带 cookie
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
return { success: false, error: `HTTP ${response.status}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.code === 0 && data.data?.token) {
|
||||||
|
srsToken = data.data.token;
|
||||||
|
// token 有效期设为 1 小时
|
||||||
|
tokenExpireTime = Date.now() + 3600 * 1000;
|
||||||
|
return { success: true, token: data.data.token };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false, error: data.msg || '登录失败' };
|
||||||
|
} catch (error: any) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前 token(如果过期则重新登录)
|
||||||
|
*/
|
||||||
|
getToken: async (): Promise<string | null> => {
|
||||||
|
// 检查 token 是否有效
|
||||||
|
if (srsToken && Date.now() < tokenExpireTime) {
|
||||||
|
return srsToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重新登录获取 token
|
||||||
|
const result = await srsApi.login();
|
||||||
|
return result.success ? result.token || null : null;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否已登录
|
||||||
|
*/
|
||||||
|
isLoggedIn: (): boolean => {
|
||||||
|
return !!srsToken && Date.now() < tokenExpireTime;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建 WHEP 播放 URL
|
||||||
|
* @param streamId 流ID(如 49214ac552fa)
|
||||||
|
* @param app 应用名称(默认 live)
|
||||||
|
*/
|
||||||
|
buildWhepUrl: (streamId: string, app: string = 'live'): string => {
|
||||||
|
return `${SRS_CONFIG.baseUrl}/rtc/v1/whep/?app=${app}&stream=${streamId}`;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用 WHEP 协议播放 WebRTC 视频流
|
||||||
|
* @param streamId 流ID
|
||||||
|
* @param videoElement video 元素
|
||||||
|
* @param options 选项
|
||||||
|
*/
|
||||||
|
playWhep: async (
|
||||||
|
streamId: string,
|
||||||
|
videoElement: HTMLVideoElement,
|
||||||
|
options?: { app?: string; videoOnly?: boolean; audioOnly?: boolean }
|
||||||
|
): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
pc?: RTCPeerConnection;
|
||||||
|
stream?: MediaStream;
|
||||||
|
error?: string;
|
||||||
|
}> => {
|
||||||
|
try {
|
||||||
|
// 确保已登录
|
||||||
|
const token = await srsApi.getToken();
|
||||||
|
if (!token) {
|
||||||
|
return { success: false, error: 'SRS 认证失败,请检查密码' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = srsApi.buildWhepUrl(streamId, options?.app);
|
||||||
|
|
||||||
|
// 创建 RTCPeerConnection
|
||||||
|
const pc = new RTCPeerConnection();
|
||||||
|
const stream = new MediaStream();
|
||||||
|
|
||||||
|
// 设置接收音视频轨道
|
||||||
|
if (!options?.videoOnly) {
|
||||||
|
pc.addTransceiver('audio', { direction: 'recvonly' });
|
||||||
|
}
|
||||||
|
if (!options?.audioOnly) {
|
||||||
|
pc.addTransceiver('video', { direction: 'recvonly' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 监听远端轨道
|
||||||
|
pc.ontrack = (event) => {
|
||||||
|
stream.addTrack(event.track);
|
||||||
|
videoElement.srcObject = stream;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 创建 offer
|
||||||
|
const offer = await pc.createOffer();
|
||||||
|
await pc.setLocalDescription(offer);
|
||||||
|
|
||||||
|
// 发送 offer 到 WHEP 端点
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/sdp',
|
||||||
|
},
|
||||||
|
body: offer.sdp,
|
||||||
|
credentials: 'include', // 携带 cookie
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
pc.close();
|
||||||
|
return { success: false, error: `WHEP 请求失败: HTTP ${response.status}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const answerSdp = await response.text();
|
||||||
|
|
||||||
|
// 设置远端描述
|
||||||
|
await pc.setRemoteDescription(new RTCSessionDescription({
|
||||||
|
type: 'answer',
|
||||||
|
sdp: answerSdp,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { success: true, pc, stream };
|
||||||
|
} catch (error: any) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用完整 URL 播放 WHEP 视频流
|
||||||
|
* @param whepUrl 完整的 WHEP URL(如:http://220.205.16.27:8024/rtc/v1/whep/?app=live&stream=xxx)
|
||||||
|
* @param videoElement video 元素
|
||||||
|
* @param options 选项
|
||||||
|
*/
|
||||||
|
playWhepByUrl: async (
|
||||||
|
whepUrl: string,
|
||||||
|
videoElement: HTMLVideoElement,
|
||||||
|
options?: { videoOnly?: boolean; audioOnly?: boolean }
|
||||||
|
): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
pc?: RTCPeerConnection;
|
||||||
|
stream?: MediaStream;
|
||||||
|
error?: string;
|
||||||
|
}> => {
|
||||||
|
try {
|
||||||
|
// 解析 URL,提取路径部分通过代理访问(避免跨域)
|
||||||
|
const urlObj = new URL(whepUrl);
|
||||||
|
// 开发环境使用代理路径,生产环境使用完整 URL
|
||||||
|
const actualUrl = process.env.NODE_ENV === 'development'
|
||||||
|
? `${urlObj.pathname}${urlObj.search}` // 只使用路径和查询参数,通过代理访问
|
||||||
|
: whepUrl;
|
||||||
|
|
||||||
|
// 确保已登录
|
||||||
|
const token = await srsApi.getToken();
|
||||||
|
|
||||||
|
// 创建 RTCPeerConnection
|
||||||
|
const pc = new RTCPeerConnection();
|
||||||
|
const stream = new MediaStream();
|
||||||
|
|
||||||
|
// 设置接收音视频轨道
|
||||||
|
if (!options?.videoOnly) {
|
||||||
|
pc.addTransceiver('audio', { direction: 'recvonly' });
|
||||||
|
}
|
||||||
|
if (!options?.audioOnly) {
|
||||||
|
pc.addTransceiver('video', { direction: 'recvonly' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 监听远端轨道
|
||||||
|
pc.ontrack = (event) => {
|
||||||
|
stream.addTrack(event.track);
|
||||||
|
videoElement.srcObject = stream;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 创建 offer
|
||||||
|
const offer = await pc.createOffer();
|
||||||
|
await pc.setLocalDescription(offer);
|
||||||
|
|
||||||
|
// 发送 offer 到 WHEP 端点
|
||||||
|
const response = await fetch(actualUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/sdp',
|
||||||
|
},
|
||||||
|
body: offer.sdp,
|
||||||
|
credentials: 'include', // 携带 cookie
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
pc.close();
|
||||||
|
return { success: false, error: `WHEP 请求失败: HTTP ${response.status}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const answerSdp = await response.text();
|
||||||
|
|
||||||
|
// 设置远端描述
|
||||||
|
await pc.setRemoteDescription(new RTCSessionDescription({
|
||||||
|
type: 'answer',
|
||||||
|
sdp: answerSdp,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return { success: true, pc, stream };
|
||||||
|
} catch (error: any) {
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 停止播放并清理资源
|
||||||
|
*/
|
||||||
|
stopPlay: (pc: RTCPeerConnection | null, stream: MediaStream | null) => {
|
||||||
|
if (stream) {
|
||||||
|
stream.getTracks().forEach(track => track.stop());
|
||||||
|
}
|
||||||
|
if (pc) {
|
||||||
|
pc.close();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user