Files
NODEDC_MISSION_CORE/plugins/insta360-x4/frontend/src/X4Detail.tsx
T
DCCONSTRUCTIONS fa8bde584f feat(video): recover camera previews and reduce encoding and playout cost
Improve camera recovery, shared preview lifecycle and receiver playout diagnostics. Preserve qualified X4 runtime changes and restore async admission in loopback media tests.
2026-10-29 09:10:01 +03:00

79 lines
8.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {useCallback,useEffect,useRef,useState} from 'react';
import {LoadingRegion,Button,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions';
import {SensorDetailBack} from '../../../../packages/sensor-ui/src/SensorDetailBack';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import {LiveViewportSurface} from '../../../../packages/sensor-ui/src/LiveViewport';
import {useX4Preview} from './useX4Preview';
import {CameraSettings} from './CameraSettings';
import {RecoverySettings} from './RecoverySettings';
import {cameraStatus,cameraLabel,cameraDetailAvailability,fileName,type CameraFiles,type CameraSettings as Settings} from './model';
export function X4Detail({device,transport,enabled,previewEnabled=enabled,back,navigationTarget,refresh,failure}:SensorDetailProps){
const status=cameraStatus(device),sections=cameraDetailAvailability(device,enabled),available=sections.available;
const viewing=useX4Preview(device,transport,previewEnabled,enabled);
const [settings,setSettings]=useState<Settings|null>(null),[files,setFiles]=useState<CameraFiles|null>(null);
const [pending,setPending]=useState<string|null>(null);const busy=pending!==null||viewing.busy;
const [settingsLoading,setSettingsLoading]=useState(false);const running=useRef(false),mounted=useRef(true),epoch=useRef(0);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;epoch.current++;};},[]);
const load=useCallback(async()=>{
const request=++epoch.current;
if(!available){setSettings(null);setFiles(null);setSettingsLoading(false);return;}
setSettingsLoading(true);
const current=()=>mounted.current&&request===epoch.current;
try{
if(status.function_mode!==null){const value=await perform<Settings>(transport,device,'settings.read',{mode:status.function_mode});if(!current())return;setSettings(value);}
const value=await perform<CameraFiles>(transport,device,'files.list',{offset:0});if(current())setFiles(value);
}finally{if(current())setSettingsLoading(false);}
},[transport,device.id,device.snapshot.context.session_id,status.function_mode,available]);
useEffect(()=>{void load().catch(error=>{if(mounted.current)failure(error);});return()=>{epoch.current++;};},[load]);
async function action(name:string,parameters:Record<string,unknown>={},key=name){
if(running.current||!enabled||(!available&&!['recovery.configure','power.wake'].includes(name)))return;
if(name==='power.wake'&&!sections.wake)return;
running.current=true;setPending(key);failure(null);const request=epoch.current;
try{
const result=name==='refresh'?await load():await perform<unknown>(transport,device,name,parameters);
if(!mounted.current)return;
if(request===epoch.current){
if(name==='settings.apply')setSettings(result as Settings);
if(name==='files.list')setFiles(result as CameraFiles);
if(name==='photo.capture'||name==='record.stop')await load();
}
await refresh();
}catch(error){if(mounted.current)failure(error);}
finally{running.current=false;if(mounted.current)setPending(null);}
}
const mode=settings?.mode??status.function_mode;
const label=available?cameraLabel(device,true):{label:'Недоступна',tone:'neutral' as const};
const recordLabel=status.recording===1?'Идёт запись на карту':'Запись остановлена';
const viewDevice=viewing.available?device:{...device,snapshot:{...device.snapshot,acquisition:'idle'}};
const showImage=available&&(viewing.pending||viewing.preview.live||(status.preview===1&&!viewing.error));
const recovery=sections.recovery&&status.recovery?<RecoverySettings value={status.recovery} online={available} enabled={enabled&&!busy} pending={pending==='recovery.configure'} change={value=>void action('recovery.configure',{enabled:value,wakeup_confirmed:value})} wake={sections.wake?()=>void action('power.wake'):undefined} waking={pending==='power.wake'}/>:null;
return <div className="sensor-content">
<SensorDetailBack back={back} target={navigationTarget}/>
<ResourceRow title={device.name} description={label.label} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={label.tone} aria-label={label.label} title={label.label}/>} actions={available?<>
{status.preview===0||viewing.error?<Button disabled={busy} loading={viewing.pending} onClick={()=>void viewing.retry()}>{viewing.error?'Повторить просмотр':'Начать просмотр'}</Button>:status.preview===1?<Button disabled={busy} loading={pending==='preview.stop'} onClick={()=>void action('preview.stop')}>Остановить просмотр</Button>:null}
<IconButton label="Обновить состояние камеры" loading={pending==='refresh'} disabled={busy||settingsLoading} onClick={()=>void action('refresh')}><Icon name="refresh"/></IconButton>
</>:recovery}/>
{available&&(status.alerts?.temperature_high||status.alerts?.storage_full||status.alerts?.battery_low)&&<SettingsCard title="Состояние камеры">
{status.alerts.temperature_high&&<p>Камера сообщает о перегреве.</p>}
{status.alerts.storage_full&&<p>На карте камеры закончилось место.</p>}
{status.alerts.battery_low&&<p>Камера сообщает о низком заряде.</p>}
</SettingsCard>}
{available&&recovery}
{/* Keep the decoder attached while unavailable/empty content stays outside the visible layout. */}
<div hidden={!showImage}><LiveViewportSurface video={viewing.video} preview={viewing.preview} pending={viewing.pending} error={viewing.error} device={viewDevice} layer="preview" title="Изображение X4" note="Запись сохраняется на карте памяти камеры." inactiveMessage="Нет свежих данных"/></div>
{sections.capture&&<SettingsCard title="Съёмка" description="Фото и видеозапись сохраняются на карте памяти X4." actions={<StatusBadge tone={status.recording===1?'success':'neutral'}>{recordLabel}</StatusBadge>}>
<div className="sensor-actions">{status.recording===1?<Button disabled={busy} loading={pending==='record.stop'} onClick={()=>void action('record.stop')}>Остановить запись</Button>:mode===7?<Button disabled={busy} loading={pending==='record.start'} onClick={()=>void action('record.start')}>Начать запись</Button>:mode===6?<Button disabled={busy} loading={pending==='photo.capture'} onClick={()=>void action('photo.capture')}>Сделать фото</Button>:null}</div>
{status.recording===1&&<p>Запись продолжится после закрытия просмотра.</p>}
</SettingsCard>}
{available&&(settings||settingsLoading)&&<LoadingRegion loading={(settingsLoading&&!settings)||pending==='settings.apply'} label={pending==='settings.apply'?'Применение настройки':'Получение настроек камеры'}>
{settings&&<CameraSettings value={settings} disabled={busy||status.recording!==0||status.preview!==0} apply={(key,value)=>void action('settings.apply',{mode:settings.mode,key,value})}/>}
</LoadingRegion>}
{available&&!!files?.items.length&&<SettingsCard title="Файлы на камере" actions={<Button disabled={busy} loading={pending==='files.refresh'} onClick={()=>void action('files.list',{offset:0},'files.refresh')}>Обновить список</Button>}>
<ResourceList aria-label="Файлы на карте X4">{files.items.map((item,index)=><li key={`${files.offset+index}:${item}`}><ResourceRow title={fileName(item)} icon={<Icon name="file"/>}/></li>)}</ResourceList>
{files.total>files.items.length&&<div className="sensor-actions"><Button disabled={busy||files.offset===0} loading={pending==='files.previous'} onClick={()=>void action('files.list',{offset:Math.max(0,files.offset-32)},'files.previous')}>Назад</Button><span>{files.offset+1}–{files.offset+files.items.length} из {files.total}</span><Button disabled={busy||files.offset+files.items.length>=files.total} loading={pending==='files.next'} onClick={()=>void action('files.list',{offset:files.offset+files.items.length},'files.next')}>Далее</Button></div>}
</SettingsCard>}
</div>;
}