Files
web-Iot/src/components/devices/DroneVideoPlayer.tsx
2026-08-14 09:02:52 +08:00

469 lines
16 KiB
TypeScript

import React, { useState, useEffect, useRef } from 'react';
import { Button, Select, Space, Typography } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import DroneLivePlayer from '../VolcRtcPlayer.jsx';
import { changeCameragateway, changeCameraPlane } from '../../api/device.ts';
import utils from '../../lib/utils';
import AgoraRtcRoom from '../AgoraRtc.tsx';
import { useTranslation } from 'react-i18next';
const { Text } = Typography;
interface DroneVideoPlayerProps {
device: any;
height?: number | string;
showSourceSelect?: boolean;
dualVideo?: boolean;
defaultSource?: 'station' | 'drone';
videoSource?: 'station' | 'drone';
onSourceChange?: (source: 'station' | 'drone') => void;
// 新增:状态数据
statusData?: {
[key: string]: any;
};
// 新增:显示类型(用于区分显示机场状态还是无人机状态)
displayType?: 'station' | 'drone';
}
const DroneVideoPlayer: React.FC<DroneVideoPlayerProps> = ({
device,
height = 160,
showSourceSelect = true,
dualVideo = false,
defaultSource = 'drone',
videoSource: propsVideoSource,
onSourceChange,
statusData,
displayType
}) => {
const { t } = useTranslation();
const [internalVideoSource, setInternalVideoSource] = useState<'station' | 'drone'>(defaultSource);
const videoSource = propsVideoSource !== undefined ? propsVideoSource : internalVideoSource;
const setVideoSource = (source: 'station' | 'drone') => {
if (onSourceChange) onSourceChange(source);
else setInternalVideoSource(source);
};
const [selectedCamera, setSelectedCamera] = useState<'indoor' | 'outdoor'>('outdoor'); // 默认选择室外
const [selectedLens, setSelectedLens] = useState<'wide' | 'zoom' | 'ir'>(''); // 默认选择广角
// 当前选中的摄像头 index
const [selectedDroneCameraIdx, setSelectedDroneCameraIdx] = useState<number>(0);
const [droneStreamData, setDroneStreamData] = useState<any>(null);
const [stationStreamData, setStationStreamData] = useState<any>(null);
const [loadingDrone, setLoadingDrone] = useState(false);
const [loadingStation, setLoadingStation] = useState(false);
const switchingLock = useRef(false);
// 加载机场摄像头
const loadStationCamera = async (cameraPosition: 'indoor' | 'outdoor') => {
setSelectedCamera(cameraPosition);
if (!device?.gateway_sn || switchingLock.current) return;
switchingLock.current = true;
setLoadingStation(true);
try {
const cameraIndex = device?.gateway_camera_list[0]?.camera_index || ""; // 目前先默认用第一个摄像头
if (!cameraIndex) {
setStationStreamData(null);
utils.message.warning(t('devices.stationCameraNotFound', { type: cameraPosition === 'indoor' ? t('devices.indoor') : t('devices.outdoor') }));
return;
}
const res = await changeCameragateway({
sn: device.gateway_sn,
cameraIndex,
cameraPosition,
qualityType: "adaptive",
videoExpire: 720000000,
});
if (res.code == 200) setStationStreamData(res.data);
else utils.message.error(res.msg || t('devices.switchStationCameraFail'));
} catch (err) {
console.error('切换机场摄像头失败', err);
} finally {
setLoadingStation(false);
switchingLock.current = false;
}
};
// 加载无人机镜头(使用当前选中的摄像头索引)
const loadDroneLens = async (lensType: 'wide' | 'zoom' | 'ir') => {
setSelectedLens(lensType);
if (!device?.device_sn || switchingLock.current) return;
switchingLock.current = true;
setLoadingDrone(true);
try {
const cameraList = device.drone_camera_list || [];
const targetCamera = cameraList[selectedDroneCameraIdx];
const cameraIndex = targetCamera?.camera_index || "";
if (!cameraIndex) {
return;
}
const res = await changeCameraPlane({
sn: device.device_sn,
lensType,
cameraIndex,
qualityType: "adaptive",
videoExpire: 720000000,
});
if (res.code === 200) setDroneStreamData(res.data);
else utils.message.error(res.msg || t('devices.switchDroneLensFail'));
} catch (err) {
console.error('切换无人机镜头失败', err);
} finally {
setLoadingDrone(false);
switchingLock.current = false;
}
};
// 切换无人机摄像头
const switchDroneCamera = async (idx: number) => {
setSelectedDroneCameraIdx(idx);
// 切换摄像头后也需要调用接口加载当前选择的镜头
if (selectedLens) {
await loadDroneLens(selectedLens);
}
};
// 用来记住上一次的值,判断哪一路发生了变化
const prevRef = useRef({
selectedCamera: '',
selectedLens: '',
deviceSn: '',
gatewaySn: '',
videoSource: ''
});
// 记住是否已经加载过,避免重复加载
const hasLoadedRef = useRef({
station: false,
drone: false
});
useEffect(() => {
if (!device?.device_sn && !device?.gateway_sn) return;
const prev = prevRef.current;
const currentCamera = selectedCamera;
const currentLens = selectedLens;
const currentDeviceSn = device?.device_sn || '';
const currentGatewaySn = device?.gateway_sn || '';
const currentVideoSource = videoSource;
// 双画面:只刷新【真正变化】的那一路,另一路不动
if (dualVideo) {
// 只有【机场摄像头】或设备变化了,才刷新机场
const stationChanged = currentCamera !== prev.selectedCamera || currentGatewaySn !== prev.gatewaySn;
if (stationChanged || !hasLoadedRef.current.station) {
setStationStreamData(null);
loadStationCamera(currentCamera);
hasLoadedRef.current.station = true;
}
// 只有【无人机镜头】或设备变化了,才刷新无人机
const droneChanged = currentLens !== prev.selectedLens || currentDeviceSn !== prev.deviceSn;
if (droneChanged || !hasLoadedRef.current.drone) {
setDroneStreamData(null);
loadDroneLens(currentLens);
hasLoadedRef.current.drone = true;
}
// 保存最新值,供下一次对比
prevRef.current = {
selectedCamera: currentCamera,
selectedLens: currentLens,
deviceSn: currentDeviceSn,
gatewaySn: currentGatewaySn,
videoSource: currentVideoSource
};
return;
}
// 单画面:只在真正变化时才重新加载
const sourceChanged = currentVideoSource !== prev.videoSource;
const deviceChanged = currentDeviceSn !== prev.deviceSn || currentGatewaySn !== prev.gatewaySn;
const lensChanged = currentLens !== prev.selectedLens;
const cameraChanged = currentCamera !== prev.selectedCamera;
if (videoSource === 'station') {
if ((sourceChanged || cameraChanged || deviceChanged) || !hasLoadedRef.current.station) {
setStationStreamData(null);
loadStationCamera(currentCamera);
hasLoadedRef.current.station = true;
hasLoadedRef.current.drone = false; // 重置另一边的加载状态
}
} else {
if ((sourceChanged || lensChanged || deviceChanged) || !hasLoadedRef.current.drone) {
setDroneStreamData(null);
loadDroneLens(currentLens);
hasLoadedRef.current.drone = true;
hasLoadedRef.current.station = false; // 重置另一边的加载状态
}
}
// 保存最新值,供下一次对比
prevRef.current = {
selectedCamera: currentCamera,
selectedLens: currentLens,
deviceSn: currentDeviceSn,
gatewaySn: currentGatewaySn,
videoSource: currentVideoSource
};
}, [
device,
videoSource,
selectedDroneCameraIdx,
dualVideo,
selectedCamera,
selectedLens,
]);
// 生成摄像头下拉选项
const droneCameraOptions = device?.drone_camera_list?.map((item: any, idx: number) => ({
label: item.camera_name || `${t('devices.camera')} ${idx + 1}`,
value: idx,
})) || [];
// 格式化数字
const formatNumber = (num: any, decimals = 2) => {
if (num === null || num === undefined || isNaN(num)) return '-';
return Number(num).toFixed(decimals);
};
const renderVideo = (type: 'drone' | 'station', streamData: any, loading: boolean) => {
const isDrone = type === 'drone';
const currentDisplayType = displayType || type;
const data = statusData;
return (
<div style={{
flex: 1,
height: height,
borderRadius: 8,
position: 'relative',
overflow: 'hidden',
background: '#000',
border: dualVideo ? '1px solid #243157' : 'none',
minWidth: dualVideo ? '300px' : 'auto' // 确保在双视频模式下有最小宽度
}} key={type}>
{/* 视频控制按钮 */}
<div style={{
position: 'absolute',
top: '6px',
right: '6px',
display: 'flex',
gap: '4px',
zIndex: 10,
flexWrap: 'wrap',
}}>
{!isDrone ? (
<>
<Button disabled={loading} size="small" type="text" style={{
background: selectedCamera === 'indoor' ? '#1890ff' : 'rgba(0,0,0,0.4)',
color: '#fff', fontSize: 10, padding: '0 4px', height: 20, borderRadius: 4
}} onClick={() => loadStationCamera('indoor')}>{t('devices.indoor')}</Button>
<Button disabled={loading} size="small" type="text" style={{
background: selectedCamera === 'outdoor' ? '#1890ff' : 'rgba(0,0,0,0.4)',
color: '#fff', fontSize: 10, padding: '0 4px', height: 20, borderRadius: 4
}} onClick={() => loadStationCamera('outdoor')}>{t('devices.outdoor')}</Button>
</>
) : (
<>
{droneCameraOptions.length > 1 && (
<Select
disabled={loading}
size="small"
style={{ width: 80, fontSize: 10 }}
value={selectedDroneCameraIdx}
onChange={switchDroneCamera}
options={droneCameraOptions}
status={loading ? 'warning' : undefined}
/>
)}
<Button disabled={loading} size="small" type="text" style={{
background: selectedLens === 'wide' ? '#1890ff' : 'rgba(0,0,0,0.4)',
color: '#fff', fontSize: 10, padding: '0 4px', height: 20, borderRadius: 4
}} onClick={() => loadDroneLens('wide')}>{t('devices.wideLens')}</Button>
<Button disabled={loading} size="small" type="text" style={{
background: selectedLens === 'zoom' ? '#1890ff' : 'rgba(0,0,0,0.4)',
color: '#fff', fontSize: 10, padding: '0 4px', height: 20, borderRadius: 4
}} onClick={() => loadDroneLens('zoom')}>{t('devices.zoomLens')}</Button>
<Button disabled={loading} size="small" type="text" style={{
background: selectedLens === 'ir' ? '#1890ff' : 'rgba(0,0,0,0.4)',
color: '#fff', fontSize: 10, padding: '0 4px', height: 20, borderRadius: 4
}} onClick={() => loadDroneLens('ir')}>{t('devices.irLens')}</Button>
</>
)}
</div>
{streamData ? (
streamData?.url_type == "volc" ? (
<DroneLivePlayer
key={streamData.url}
streamData={streamData}
/>
) : (
<AgoraRtcRoom
key={streamData.url}
url={streamData.url}
/>
)
) : (
<div style={{
color: '#ccc',
display: 'flex',
height: '100%',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
gap: 8
}}>
{loading ? <ReloadOutlined spin style={{ color: '#fff' }} /> : null}
<span style={{ color: '#fff', fontSize: 12 }}>
{loading ? t('video.videoLoading') : t('devices.noVideoSignal')}
</span>
</div>
)}
{showSourceSelect && (
<div style={{
position: 'absolute',
top: 6,
left: 6,
background: 'rgba(0,0,0,0.5)',
color: '#fff',
padding: '2px 6px',
borderRadius: 4,
fontSize: 10,
zIndex: 5
}}>
{isDrone ? t('devices.droneVideo') : t('devices.stationVideo')}
</div>
)}
{/* 状态详情叠加层 - 左上角 */}
{data && (
<div style={{
position: 'absolute',
top: 6,
left: 6,
background: 'rgba(0,0,0,0.7)',
color: '#fff',
padding: '8px 10px',
borderRadius: 6,
fontSize: 11,
zIndex: 5,
maxWidth: '40%',
backdropFilter: 'blur(4px)'
}}>
{currentDisplayType === 'station' ? (
<>
<div style={{ marginBottom: 4, fontWeight: 600, color: '#1890ff' }}>{t('devices.stationStatus')}</div>
<div style={{ display: 'grid', gridTemplateColumns: 'auto auto', gap: '2px 8px' }}>
<span>{t('home.temperature')}:</span><span>{formatNumber(data.temperature || data.environment_temperature)}°C</span>
<span>{t('devices.humidity')}:</span><span>{data.humidity !== undefined ? `${data.humidity}%` : '-'}</span>
<span>{t('devices.windSpeed')}:</span><span>{formatNumber(data.wind_speed)}m/s</span>
<span>{t('devices.rainfall')}:</span><span style={{ color: data.rainfall === 'no_rain' || data.rainfall === 0 ? '#52c41a' : '#ff4d4f' }}>
{data.rainfall === 'no_rain' || data.rainfall === 0 ? t('devices.rainNo') : t('devices.rainYes')}
</span>
<span>{t('devices.hangar')}:</span><span style={{ color: data.cover_state === 1 || data.cover_state === 'open' ? '#52c41a' : '#faad14' }}>
{data.cover_state === 1 || data.cover_state === 'open' ? t('devices.coverOpen') : t('devices.coverClosed')}
</span>
<span>{t('devices.drone')}:</span><span style={{ color: data.drone_in_dock === 1 || data.drone_in_dock === true ? '#52c41a' : '#1890ff' }}>
{data.drone_in_dock === 1 || data.drone_in_dock === true ? t('devices.inDock') : t('devices.outDock')}
</span>
</div>
</>
) : (
<>
<div style={{ marginBottom: 4, fontWeight: 600, color: '#52c41a' }}>{t('devices.droneStatus')}</div>
<div style={{ display: 'grid', gridTemplateColumns: 'auto auto', gap: '2px 8px' }}>
<span>{t('devices.batteryLevel')}:</span><span style={{ color: (data.capacity_percent || 0) < 20 ? '#ff4d4f' : '#52c41a' }}>
{data.capacity_percent !== undefined ? `${data.capacity_percent}%` : '-'}
</span>
<span>{t('devices.altitude')}:</span><span>{formatNumber(data.height)}m</span>
<span>{t('devices.horizontalSpeed')}:</span><span>{formatNumber(data.horizontal_speed)}m/s</span>
<span>{t('devices.verticalSpeed')}:</span><span>{formatNumber(data.vertical_speed)}m/s</span>
<span>{t('devices.headingAngle')}:</span><span>{formatNumber(data.heading)}°</span>
<span>GPS:</span><span>{data.position_state?.gps_number || 0}{t('devices.gpsUnit')}</span>
<span>RTK:</span><span style={{ color: data.position_state?.is_fixed === 2 || data.position_state?.is_fixed === 'fixing_successful' ? '#52c41a' : '#faad14' }}>
{data.position_state?.is_fixed === 2 || data.position_state?.is_fixed === 'fixing_successful' ? t('devices.fixed') : t('devices.notFixed')}
</span>
</div>
</>
)}
</div>
)}
{/* 底部信息叠加 - 显示经纬度 */}
{data && data.latitude !== undefined && data.longitude !== undefined && (
<div style={{
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
background: 'rgba(0,0,0,0.6)',
color: '#fff',
display: 'flex',
justifyContent: 'center',
padding: '4px 8px',
fontSize: 10
}}>
<span>{t('devices.position')}: {formatNumber(data.latitude, 6)}, {formatNumber(data.longitude, 6)}</span>
</div>
)}
</div>
);
};
return (
<div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
{!dualVideo && showSourceSelect && (
<div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8 }}>
<Select
size="small"
style={{ width: 120 }}
value={videoSource}
onChange={(val) => setVideoSource(val)}
options={[
{ label: t('devices.stationVideo'), value: 'station' },
{ label: t('devices.droneVideo'), value: 'drone' },
]}
/>
</div>
)}
<div style={{
width: '100%',
flex: 1,
display: 'flex',
flexDirection: 'row',
gap: dualVideo ? 8 : 0
}}>
{dualVideo ? (
<>
{renderVideo('drone', droneStreamData, loadingDrone)}
{renderVideo('station', stationStreamData, loadingStation)}
</>
) : (
videoSource === 'station'
? renderVideo('station', stationStreamData, loadingStation)
: renderVideo('drone', droneStreamData, loadingDrone)
)}
</div>
</div>
);
};
export default DroneVideoPlayer;