feat(routers): integrate Banana Pi Client API and onboard LibreSpeed measurements

Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
This commit is contained in:
DCCONSTRUCTIONS
2026-11-11 23:53:46 +03:00
parent 58ac9fe3d2
commit a49fb00b8e
208 changed files with 7007 additions and 881 deletions
@@ -0,0 +1,80 @@
import {RouterDiagnostics} from './RouterDiagnostics';
import {useEffect,useRef,useState} from 'react';
import {Button,ConfirmationModal,Description,FieldFrame,Select,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
import {simChannels,simLabel,modeLabel,type RouterControl,type RouterDevice,type RouterPolicy,type RouterReceipt,type RouterSnapshot,type RouterTransport} from './contracts';
import {routerMode} from './mode';
import {controlBusy,controlEnabled,controlMessage} from './control';
export function ClientRouterControls({device,value,transport,ready,visible=true}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport;ready:boolean;visible?:boolean}){
const api=device.client_api!,mode=routerMode(device,ready);
const [policy,setPolicy]=useState<RouterPolicy>(api.policy),[dirty,setDirty]=useState(false);
const [draftVersion,setDraftVersion]=useState({boot:api.boot_id,revision:api.revision});
const staleDraft=dirty&&(draftVersion.boot!==api.boot_id||draftVersion.revision!==api.revision);
const [recovery,setRecovery]=useState('wan_reconnect'),[sim,setSIM]=useState(`M${simChannels(device)[0].slot}`);
const [confirm,setConfirm]=useState<RouterControl['action']|null>(null),[pending,setPending]=useState(''),[sending,setSending]=useState(false),[result,setResult]=useState<RouterReceipt|null>(null),[error,setError]=useState('');
const active=useRef(true);useEffect(()=>{active.current=true;return()=>{active.current=false;};},[]);
const remote=value.results.find(r=>r.device_id===device.id&&controlBusy(r));
const busy=sending||!!pending||!!remote,enabled=controlEnabled(value,device,ready)&&!busy;
useEffect(()=>{if(!dirty&&!busy){setPolicy(api.policy);setDraftVersion({boot:api.boot_id,revision:api.revision});}},[api.boot_id,api.revision,dirty,busy]);
useEffect(()=>{
if(!pending)return;
let stopped=false;let timer:ReturnType<typeof setTimeout>;const end=Date.now()+300000;
async function poll(){
try{const next=await transport.operation(pending);if(stopped)return;setResult(next);
if(!controlBusy(next)){setPending('');if(next.state==='complete')setDirty(false);return;}
}catch{/* Poll a receipt, never repeat the write. */}
if(stopped)return;
if(Date.now()>=end){setResult({operation_id:pending,state:'unknown'});setPending('');return;}
timer=setTimeout(()=>void poll(),2000);
}
void poll();return()=>{stopped=true;clearTimeout(timer);};
},[pending,transport]);
function change(next:Partial<RouterPolicy>){setPolicy(p=>({...p,...next}));setDirty(true);}
const valid=(policy.mode!=='direct'||!!policy.preferred_sim)&&Number.isInteger(policy.fail_seconds)&&policy.fail_seconds>=15&&policy.fail_seconds<=300&&Number.isInteger(policy.recover_seconds)&&policy.recover_seconds>=30&&policy.recover_seconds<=600&&Number.isInteger(policy.min_vpn_seconds)&&policy.min_vpn_seconds>=60&&policy.min_vpn_seconds<=900;
const labels:Record<string,string>={policy:'Применить настройки',recovery:'Выполнить восстановление',diagnostics:'Запустить диагностику',reboot:'Перезагрузить роутер'};
async function send(){
if(!confirm||!enabled||!value.runtime_id||!api.rights.includes(confirm)||(confirm==='policy'&&(!valid||staleDraft))){setConfirm(null);return;}
const action=confirm;setConfirm(null);setSending(true);setError('');setResult(null);
const id='op_'+crypto.randomUUID().replaceAll('-','');
const nextPolicy:RouterPolicy={mode:policy.mode,allow_fallback:true,return_to_preferred:true,persist:true,fail_seconds:policy.fail_seconds,recover_seconds:policy.recover_seconds,min_vpn_seconds:policy.min_vpn_seconds,...(policy.mode==='direct'?{preferred_sim:policy.preferred_sim}:{})};
const command:RouterControl={operation_id:id,runtime_id:value.runtime_id,device_id:device.id,deadline:Math.floor(Date.now()/1000)+85,action,mode:'',slots:[],expected_boot_id:action==='policy'?draftVersion.boot:api.boot_id,expected_revision:action==='policy'?draftVersion.revision:api.revision,policy:action==='policy'?nextPolicy:null,recovery:action==='recovery'?recovery:'',sim:action==='recovery'&&recovery==='wan_reconnect'?sim:''};
try{const receipt=await transport.control(command);if(active.current)setResult(receipt);}
catch(e){if(active.current)setError(e instanceof Error?e.message:'Не удалось получить ответ на команду.');}
finally{if(active.current){setSending(false);setPending(id);}}
}
const receipt=remote?.action==='inspect'?result:remote??result;
const recoveryName={wan_reconnect:'Переподключить сотовый канал',vpn_reconnect:'Переподключить VPN',dns_restart:'Перезапустить DNS'}[recovery]??'';
const confirmation=confirm==='policy'?`${modeLabel(policy.mode)}${policy.mode==='direct'?` · ${simLabel(device,Number(policy.preferred_sim?.slice(1)))}`:''}. Настройки сохранятся после перезагрузки; соединения через роутер могут прерваться.`:confirm==='recovery'?`${recoveryName}${recovery==='wan_reconnect'?` · ${simLabel(device,Number(sim.slice(1)))}`:''}. Текущие соединения могут прерваться.`:confirm==='reboot'?'Связь через этот роутер временно прервётся.':'Будет выполнена проверка служб роутера без переключения режима.';
return <div className="router-form">
<SettingsCard title="Режим подключения" description={`Сейчас: ${mode.current}`}>
<div className="router-form">
{mode.message&&<Description role="status">{mode.message}</Description>}
<FieldFrame label={dirty?'Новый режим':'Сохранённый режим'} hint={dirty?'Не применён':undefined}>
<Select label={dirty?'Новый режим':'Сохранённый режим'} value={policy.mode} disabled={!enabled||!api.rights.includes('policy')} options={(['direct','vpn','aggregation','whitelist'] as const).map(mode=>({value:mode,label:modeLabel(mode)}))} onChange={mode=>change({mode:mode as RouterPolicy['mode'],preferred_sim:undefined})}/>
</FieldFrame>
{dirty&&<Description>Изменения ещё не применены. На роутере задано: {mode.configured}.</Description>}
{policy.mode==='direct'&&<Select label="Предпочтительная SIM" value={policy.preferred_sim??''} disabled={!enabled||!api.rights.includes('policy')} options={[{value:'',label:'Выберите SIM',disabled:true},...simChannels(device).map(s=>({value:`M${s.slot}`,label:`${s.label} (${s.detail}) · ${device.modems.find(m=>m.slot===s.slot)?.operator||'Оператор не определён'}`}))]} onChange={s=>change({preferred_sim:s as RouterPolicy['preferred_sim']})}/>}
<Description>Автоматическим резервированием и возвратом на предпочтительную SIM управляет прошивка. Ограничение агрегации выбранным набором SIM этим API не поддерживается.</Description>
{([['fail_seconds','Ожидание отказа, с',15,300],['recover_seconds','Ожидание восстановления, с',30,600],['min_vpn_seconds','Минимальное время VPN, с',60,900]] as const).map(([key,label,min,max])=><TextField key={key} label={label} type="number" min={min} max={max} step={1} value={policy[key]} disabled={!enabled||!api.rights.includes('policy')} onChange={e=>change({[key]:Number(e.target.value)})}/>)}
{staleDraft&&<Description>Настройки роутера изменились во время редактирования. Обновите форму перед применением.</Description>}
{staleDraft&&<Button disabled={busy} onClick={()=>setDirty(false)}>Обновить форму</Button>}
<Button disabled={!enabled||!valid||staleDraft||!api.rights.includes('policy')} onClick={()=>setConfirm('policy')}>Применить</Button>
</div>
</SettingsCard>
<SettingsCard title="Восстановление соединения" description="Ручное действие штатного контроллера роутера. Успешное выполнение команды само по себе не подтверждает доступ в интернет.">
<div className="router-form">
<Select label="Действие" value={recovery} disabled={!enabled||!api.rights.includes('recovery')} options={[{value:'wan_reconnect',label:'Переподключить сотовый канал'},{value:'vpn_reconnect',label:'Переподключить VPN'},{value:'dns_restart',label:'Перезапустить DNS'}]} onChange={setRecovery}/>
{recovery==='wan_reconnect'&&<Select label="SIM-карта" value={sim} disabled={!enabled||!api.rights.includes('recovery')} options={simChannels(device).map(s=>({value:`M${s.slot}`,label:`${s.label} (${s.detail})`}))} onChange={setSIM}/>}
<Button disabled={!enabled||!api.rights.includes('recovery')} onClick={()=>setConfirm('recovery')}>Выполнить</Button>
</div>
</SettingsCard>
<SettingsCard title="Диагностика" description="Проверка служб. Результаты относятся к моменту запуска проверки.">
<Button disabled={!enabled||!api.rights.includes('diagnostics')} onClick={()=>setConfirm('diagnostics')}>Проверить роутер</Button>
<RouterDiagnostics device={device} value={value} transport={transport} visible={visible}/>
</SettingsCard>
<SettingsCard title="Перезагрузка роутера" description="После загрузки будут показаны фактический режим и состояние каналов."><Button disabled={!enabled||!api.rights.includes('reboot')} onClick={()=>setConfirm('reboot')}>Перезагрузить роутер</Button></SettingsCard>
{error&&<StatusBadge tone="warning">{error}</StatusBadge>}
{receipt&&<StatusBadge tone={receipt.state==='complete'?'success':receipt.state==='error'||receipt.state==='unknown'?'warning':'neutral'}>{controlMessage(receipt)}</StatusBadge>}
<ConfirmationModal open={confirm!==null} title={labels[confirm??'']??''} description={confirmation} confirmLabel="Выполнить" cancelLabel="Отмена" onClose={()=>setConfirm(null)} onConfirm={send}/>
</div>;
}
+15 -38
View File
@@ -1,41 +1,18 @@
import {useEffect,useRef,useState} from 'react';
import {Button,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
import {useState} from 'react';
import {Button,Description,SettingsCard,StatusBadge,TextAreaField,TextField} from '@nodedc/ui-react';
import type {RouterDevice,RouterSnapshot,RouterTransport} from './contracts';
const errors:Record<string,string>={access_rejected:'Роутер отклонил доступ. Проверьте имя и пароль.',router_unavailable:'Роутер недоступен. Дождитесь подключения.',expired:'Срок запроса истёк. Повторите после обновления состояния.',unsupported_response:'Не удалось прочитать совместимый ответ роутера.',storage_error:'Не удалось сохранить доступ на борту.'};
import {useRouterRequest} from './useRouterRequest';
export function RouterAccess({device,value,transport,fresh}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport;fresh:boolean}){
const [username,setUsername]=useState(''),[password,setPassword]=useState(''),[pending,setPending]=useState(''),[message,setMessage]=useState(''),[sending,setSending]=useState(false);
const busy=sending||!!pending;
const active=useRef(true);
useEffect(()=>{active.current=true;return()=>{active.current=false;};},[]);
useEffect(()=>{
if(!pending)return;
let stopped=false;let timer:ReturnType<typeof setTimeout>;const end=Date.now()+95000;
async function poll(){
try{const result=await transport.operation(pending);if(stopped)return;
if(result.state!=='queued'){setPending('');setMessage(result.state==='complete'?'Доступ сохранён на борту.':errors[result.error??'']??'Подтверждение не получено. Обновите состояние перед повтором.');return;}
}catch{/* A lost response is not proof that authorization failed. */}
if(stopped)return;
if(Date.now()>=end){setPending('');setMessage('Подтверждение не получено. Обновите состояние перед повтором.');return;}
timer=setTimeout(()=>void poll(),2000);
}
void poll();return()=>{stopped=true;clearTimeout(timer);};
},[pending,transport]);
async function authorize(){
if(!value.runtime_id)return;
const id='op_'+crypto.randomUUID().replaceAll('-','');const secret=password;setPassword('');setSending(true);setMessage('');
try{await transport.authorize({operation_id:id,runtime_id:value.runtime_id,device_id:device.id,deadline:Math.floor(Date.now()/1000)+85,username,password:secret});}
catch{if(active.current)setMessage('Подтверждаем результат отправки.');}
finally{if(active.current){setSending(false);setPending(id);}}
}
return <SettingsCard title="Доступ к роутеру" description="Имя и пароль сохраняются только на бортовом компьютере. Доступ к админке передаётся по локальному соединению с роутером.">
<div className="router-form">
<p>Устройство привязано к локальному сетевому адресу оборудования. Криптографическая идентификация этой прошивкой не подтверждена.</p>
<TextField label="Имя пользователя" value={username} maxLength={64} disabled={busy} autoComplete="off" onChange={e=>setUsername(e.target.value)}/>
<TextField label="Пароль" type="password" value={password} maxLength={256} disabled={busy} autoComplete="new-password" onChange={e=>setPassword(e.target.value)}/>
<Button loading={busy} disabled={!fresh||busy||!username||!password} onClick={()=>void authorize()}>Предоставить доступ</Button>
{message&&<StatusBadge tone="neutral">{message}</StatusBadge>}
</div>
</SettingsCard>;
const [token,setToken]=useState(''),[ca,setCA]=useState('');const request=useRouterRequest(value,transport);
const busy=request.busy||value.results.some(r=>r.state==='queued'||r.state==='applying');
function authorize(){const key=token,certificate=ca;setToken('');setCA('');void request.send({device_id:device.id,model_id:'',client_api:{token:key,ca:certificate}});}
return <SettingsCard title="Client API" description={device.client_api?`Подключён · модуль ${device.client_api.module_version}`:'Подключите Client API, если он установлен в прошивке этого роутера.'}>
<div className="router-form">
<Description>Ключ из config.json и сертификат ca.pem выдаются для конкретного роутера. Они сохраняются на борту отдельно от пароля админки.</Description>
<TextField label="Ключ Client API" type="password" value={token} maxLength={4096} disabled={busy} autoComplete="new-password" onChange={e=>setToken(e.target.value)}/>
<TextAreaField label="Сертификат CA (PEM)" value={ca} rows={6} maxLength={8192} disabled={busy} autoComplete="off" spellCheck={false} onChange={e=>setCA(e.target.value)}/>
<Button loading={request.busy} disabled={!fresh||busy||!token||!ca} onClick={authorize}>Подключить Client API</Button>
{request.message&&<StatusBadge tone="neutral">{request.message}</StatusBadge>}
</div>
</SettingsCard>;
}
+11 -8
View File
@@ -1,6 +1,7 @@
import {useEffect,useRef,useState} from 'react';
import {Button,ConfirmationModal,SegmentedControl,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {modeLabel,type RouterControl,type RouterDevice,type RouterReceipt,type RouterSnapshot,type RouterTransport} from './contracts';
import {Button,ConfirmationModal,Description,SegmentedControl,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {simChannels,simLabel,modeLabel,type RouterControl,type RouterDevice,type RouterReceipt,type RouterSnapshot,type RouterTransport} from './contracts';
import {routerMode} from './mode';
import {availableSlots,controlBusy,controlEnabled,controlMessage} from './control';
export function RouterControls({device,value,transport,ready}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport;ready:boolean}){
@@ -10,7 +11,7 @@ export function RouterControls({device,value,transport,ready}:{device:RouterDevi
const remote=value.results.find(r=>r.device_id===device.id&&controlBusy(r));
const busy=sending||!!pending||!!remote;
const enabled=controlEnabled(value,device,ready)&&!busy;
const live=availableSlots(device);
const live=availableSlots(device),observed=routerMode(device,ready);
useEffect(()=>{
if(dirty||busy)return;
setMode(device.manual_mode==='direct'?'direct':'aggregation');
@@ -43,11 +44,13 @@ export function RouterControls({device,value,transport,ready}:{device:RouterDevi
const receipt=remote??result;
return <div className="router-form">
{value.control_version!==1&&<StatusBadge tone="neutral">Для управления требуется обновление Mission Core на борту.</StatusBadge>}
<SettingsCard title="Режим подключения" description={`Сейчас: ${ready?modeLabel(device.active_mode):'нет свежего подтверждения'}${ready&&device.active_mode==='direct'&&device.active_wan?` · SIM ${device.active_wan.replace('wan','M')}`:''}`}>
<SettingsCard title="Режим подключения" description={`Сейчас: ${observed.current}`}>
<div className="router-form">
<SegmentedControl label="Режим интернета" value={mode} items={[{value:'direct',label:'Одна SIM',disabled:!enabled},{value:'aggregation',label:'Агрегация',disabled:!enabled}]} onChange={next=>{setMode(next);setDirty(true);if(next==='direct')setSlots(slots.slice(0,1));}}/>
{mode==='direct'?<Select label="SIM-карта" value={String(slots[0]??'')} disabled={!enabled} options={[{value:'',label:'Выберите SIM',disabled:true},...[1,2,3].map(slot=>({value:String(slot),label:`M${slot} · ${device.modems.find(m=>m.slot===slot)?.operator||'Нет подключения'}`,disabled:!live.includes(slot)}))]} onChange={s=>{setSlots([Number(s)]);setDirty(true);}}/>:
<SegmentedControl selectionMode="multiple" label="SIM для агрегации" value={slots.map(String)} items={[1,2,3].map(slot=>({value:String(slot),label:`M${slot} · ${device.modems.find(m=>m.slot===slot)?.operator||'Нет подключения'}`,disabled:!enabled||!live.includes(slot)}))} onChange={s=>{setSlots(s.map(Number));setDirty(true);}}/>}
{observed.message&&<Description role="status">{observed.message}</Description>}
<Description>{dirty?'Изменения ещё не применены. ':''}Задано на роутере: {observed.configured}.</Description>
<SegmentedControl label="Режим интернета" value={mode} items={[{value:'direct',label:'Прямой выход через SIM',disabled:!enabled},{value:'aggregation',label:'Агрегация',disabled:!enabled}]} onChange={next=>{setMode(next);setDirty(true);if(next==='direct')setSlots(slots.slice(0,1));}}/>
{mode==='direct'?<Select label="SIM-карта" value={String(slots[0]??'')} disabled={!enabled} options={[{value:'',label:'Выберите SIM',disabled:true},...simChannels(device).map(s=>({value:String(s.slot),label:`${s.label} (${s.detail}) · ${device.modems.find(m=>m.slot===s.slot)?.operator||'Нет подключения'}`,disabled:!live.includes(s.slot)}))]} onChange={s=>{setSlots([Number(s)]);setDirty(true);}}/>:
<SegmentedControl selectionMode="multiple" label="SIM для агрегации" value={slots.map(String)} items={simChannels(device).map(s=>({value:String(s.slot),label:`${s.label} (${s.detail}) · ${device.modems.find(m=>m.slot===s.slot)?.operator||'Нет подключения'}`,disabled:!enabled||!live.includes(s.slot)}))} onChange={s=>{setSlots(s.map(Number));setDirty(true);}}/>}
<p className="router-note">{mode==='direct'?'Интернет через выбранную SIM без сервера агрегации.':'Выбранные SIM передают трафик через сервер агрегации.'}</p>
<Button disabled={!enabled||!selected} loading={busy&&receipt?.action==='mode'} onClick={()=>setConfirm('mode')}>Применить</Button>
</div>
@@ -57,6 +60,6 @@ export function RouterControls({device,value,transport,ready}:{device:RouterDevi
</SettingsCard>
{error&&<StatusBadge tone="warning">{error}</StatusBadge>}
{receipt&&<StatusBadge tone={receipt.state==='complete'?'success':receipt.state==='error'||receipt.state==='unknown'?'warning':'neutral'}>{controlMessage(receipt)}</StatusBadge>}
<ConfirmationModal open={confirm!==null} title={confirm==='reboot'?'Перезагрузить DexaFlow?':'Изменить подключение DexaFlow?'} description={confirm==='reboot'?'Интернет через этот роутер временно пропадёт. Настройки Wi-Fi борта не изменяются.':`${modeLabel(mode)} · ${slots.map(s=>'M'+s).join(', ')}. Текущие соединения через роутер могут прерваться. Настройки Wi-Fi борта не изменяются.`} confirmLabel={confirm==='reboot'?'Перезагрузить':'Применить'} cancelLabel="Отмена" onClose={()=>setConfirm(null)} onConfirm={send}/>
<ConfirmationModal open={confirm!==null} title={confirm==='reboot'?'Перезагрузить DexaFlow?':'Изменить подключение DexaFlow?'} description={confirm==='reboot'?'Интернет через этот роутер временно пропадёт. Настройки Wi-Fi борта не изменяются.':`${modeLabel(mode)} · ${slots.map(s=>simLabel(device,s)).join(', ')}. Текущие соединения через роутер могут прерваться. Настройки Wi-Fi борта не изменяются.`} confirmLabel={confirm==='reboot'?'Перезагрузить':'Применить'} cancelLabel="Отмена" onClose={()=>setConfirm(null)} onConfirm={send}/>
</div>;
}
+29 -18
View File
@@ -1,46 +1,57 @@
import {useState} from 'react';
import {Button,SegmentedControl,SettingsCard,StatusBadge,Window} from '@nodedc/ui-react';
import {incidentLabels,incidentValue,metric,routerFresh,routerLabel,type RouterDevice,type RouterSnapshot,type RouterTransport} from './contracts';
import {RouterVendorHistory} from './RouterVendorHistory';
import {RouterRadioHistory,useRadioHistory} from './RouterRadioHistory';
import {useState,type ReactNode} from 'react';
import {Button,Description,SegmentedControl,SettingsCard,StatusBadge,Window} from '@nodedc/ui-react';
import {simChannels,simLabel,incidentLabels,incidentValue,metric,routerFresh,routerLabel,routerName,type RouterDevice,type RouterSnapshot,type RouterTransport} from './contracts';
import {RouterControls} from './RouterControls';
import {ClientRouterControls} from './ClientRouterControls';
import {RouterAccess} from './RouterAccess';
import {RouterGeneral} from './RouterGeneral';
import {RouterOverview,useRouterTraffic} from './RouterOverview';
function Facts({items}:{items:[string,string][]}){return <dl className="router-facts">{items.map(([label,value])=><div key={label}><dt>{label}</dt><dd>{value||'Нет сведений'}</dd></div>)}</dl>;}
const sections=[{value:'overview',label:'Обзор'},{value:'control',label:'Управление'},{value:'signal',label:'Радиоканал'},{value:'events',label:'Происшествия'},{value:'access',label:'Доступ'}];
const sections=[{value:'overview',label:'Обзор'},{value:'control',label:'Управление'},{value:'signal',label:'Радиоканал'},{value:'events',label:'Происшествия'},{value:'general',label:'Общие'}];
export function RouterDetails({device,value,transport,onClose,error}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport;onClose:()=>void;error:string}){
const [section,setSection]=useState(device.state==='access_required'||device.state==='access_rejected'?'access':'overview');
export function RouterDetails({device,value,transport,onClose,error,speedtest}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport;onClose:()=>void;error:string;speedtest?:ReactNode}){
const [section,setSection]=useState(device.state==='access_required'||device.state==='access_rejected'?'general':'overview');
const fresh=routerFresh(value,device),ready=fresh&&device.state==='ready';
const traffic=useRouterTraffic(device,value,ready);
const radio=useRadioHistory(device,value,ready);
const [eventSource,setEventSource]=useState('board');
const incidents=value.events.filter(e=>e.device_id===device.id).slice().reverse();
function download(){
const data={schema:'missioncore.router-journal/v1',fresh:value.fresh??true,journal:value.journal,events:incidents};
const url=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));
const a=document.createElement('a');a.href=url;a.download='router-journal.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
}
return <Window open size="lg" title="DexaFlow" subtitle="Сеть аппарата" onClose={onClose} closeOnBackdrop={false}>
return <Window open size="lg" title={routerName(device)} subtitle="Сеть аппарата" onClose={onClose} closeOnBackdrop={false}>
<div className="router-details">
<StatusBadge tone={ready?'success':'neutral'}>{routerLabel(value,device)}</StatusBadge>
<p className="router-note">{device.observed_at?`Последнее наблюдение: ${new Date(device.observed_at*1000).toLocaleString('ru-RU')}`:'Наблюдений пока нет'}{!ready&&device.modems.length>0?' · Показаны последние полученные значения':''}</p>
<Description>{device.observed_at?`Последнее наблюдение: ${new Date(device.observed_at*1000).toLocaleString('ru-RU')}`:'Наблюдений пока нет'}{!ready&&device.modems.length>0?' · Показаны последние полученные значения':''}</Description>
{error&&<StatusBadge tone="warning">{error}</StatusBadge>}
<SegmentedControl label="Сведения о роутере" value={section} items={sections} onChange={setSection}/>
<SegmentedControl label="Сведения о роутере" value={section} items={speedtest?[...sections.slice(0,2),{value:'speedtest',label:'Замер скорости'},...sections.slice(2)]:sections} onChange={setSection}/>
{section==='overview'&&<RouterOverview device={device} ready={ready} points={traffic}/>}
<div hidden={section!=='control'}><RouterControls device={device} value={value} transport={transport} ready={ready}/></div>
<div hidden={section!=='control'}>{device.client_api?<ClientRouterControls device={device} value={value} transport={transport} ready={ready} visible={section==='control'}/>:<RouterControls device={device} value={value} transport={transport} ready={ready}/>}</div>
<div hidden={section!=='speedtest'}>{speedtest}</div>
{section==='signal'&&<>
<p className="router-note">Показатели относятся к модемам. Данных по отдельным разъёмам антенн роутер не предоставил.</p>
{device.modems.length===0?<p>Для получения радиопоказателей нужен доступ к роутеру.</p>:device.modems.map(m=><SettingsCard key={m.slot} title={`SIM M${m.slot}`} description={m.operator||'Оператор не определён'}><Facts items={[
<RouterRadioHistory device={device} samples={radio}/>
<Description>Показатели относятся к модемам. Данных по отдельным разъёмам антенн роутер не предоставил.</Description>
{device.modems.length===0?<Description>Для получения радиопоказателей нужен доступ к роутеру.</Description>:simChannels(device).flatMap(channel=>{const m=device.modems.find(m=>m.slot===channel.slot);return m?[<SettingsCard key={m.slot} title={`${channel.label} (${channel.detail})`} description={m.operator||'Оператор не определён'}><Facts items={[
['Регистрация',device.client_api?.wan.find(w=>w.slot===m.slot)?.registration??''],['Причина недоступности',device.client_api?.wan.find(w=>w.slot===m.slot)?.failure_reason??''],
['Радиомодуль',m.radio==='NOSIM'?'SIM не обнаружена':m.radio==='OK'?'Готов':m.radio],['Подключение',m.connectivity==='online'?'В сети':m.connectivity==='offline'?'Нет связи':m.connectivity],
['Сеть',m.technology],['Диапазон',m.band],['Ширина канала',metric(m.bandwidth,'МГц')],['RSRP',metric(m.rsrp,'dBm')],['RSRQ',metric(m.rsrq,'dB')],['SINR',metric(m.sinr,'dB')],['RSSI',metric(m.rssi,'dBm')],['Адрес модема',m.ip],['Базовая станция',m.cell_id],['PCI',m.pci==null?'Нет сведений':String(m.pci)],
]}/></SettingsCard>)}
['Сеть',m.technology],['Диапазон',m.band],['Ширина канала',metric(m.bandwidth,'МГц')],['RSRP',metric(m.rsrp,'dBm')],['RSRQ',metric(m.rsrq,'dB')],['SINR',metric(m.sinr,'dB')],['RSSI',metric(m.rssi,'dBm')],['Адрес модема',m.ip],['Базовая станция',m.cell_id],['EARFCN',m.earfcn==null?'Нет сведений':String(m.earfcn)],['TAC',m.tac??''],['PCI',m.pci==null?'Нет сведений':String(m.pci)],
]}/></SettingsCard>]:[];})}
</>}
{section==='events'&&<>
{device.client_api&&<SegmentedControl label="Источник истории" value={eventSource} items={[{value:'board',label:'Борт'},{value:'router',label:'Роутер'}]} onChange={setEventSource}/>}
{eventSource==='router'&&device.client_api?<RouterVendorHistory device={device} value={value} transport={transport}/>:<>
<div className="router-actions"><Button disabled={!incidents.length} onClick={download}>Скачать журнал</Button></div>
<p className="router-note">На борту хранятся до {value.journal?.limit??256} событий за {value.journal?.retention_days??7} дней. Время событий — по часам борта.</p>
<Description>На борту хранятся до {value.journal?.limit??256} событий за {value.journal?.retention_days??7} дней. Время событий — по часам борта.</Description>
{!!value.journal?.dropped&&<StatusBadge tone="neutral">Старые события удалены по сроку или лимиту: {value.journal.dropped}</StatusBadge>}
{value.journal?.error&&<StatusBadge tone="warning">Борт не подтвердил сохранение журнала.</StatusBadge>}
{incidents.length===0?<p>Происшествий пока нет.</p>:<ol className="router-events">{incidents.map(e=><li key={`${e.boot_id}:${e.sequence}`}><time dateTime={new Date(e.at*1000).toISOString()}>{new Date(e.at*1000).toLocaleString('ru-RU')}</time><strong>{incidentLabels[e.code]??'Состояние изменилось'}{e.slot?` · M${e.slot}`:''}</strong>{(e.before||e.after)&&<span>{[incidentValue(e.before),incidentValue(e.after)].filter(Boolean).join(' → ')}</span>}</li>)}</ol>}
</>}
{section==='access'&&<RouterAccess key={device.id} device={device} value={value} transport={transport} fresh={fresh&&device.state!=='unreachable'&&device.state!=='incompatible'}/>}
{incidents.length===0?<Description>Происшествий пока нет.</Description>:<ol className="router-events">{incidents.map(e=><li key={`${e.boot_id}:${e.sequence}`}><time dateTime={new Date(e.at*1000).toISOString()}>{new Date(e.at*1000).toLocaleString('ru-RU')}</time><strong>{incidentLabels[e.code]??'Состояние изменилось'}{e.slot?` · ${simLabel(device,e.slot)}`:''}</strong>{(e.before||e.after)&&<span>{[incidentValue(e.before),incidentValue(e.after)].filter(Boolean).join(' → ')}</span>}</li>)}</ol>}
</>}</>}
{section==='general'&&<><RouterGeneral device={device} value={value} transport={transport}/><RouterAccess key={device.id} device={device} value={value} transport={transport} fresh={fresh&&device.state!=='unreachable'&&device.state!=='incompatible'}/></>}
</div>
</Window>;
}
@@ -0,0 +1,39 @@
import {useEffect} from 'react';
import {Button,Description,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {simLabel,type RouterDevice,type RouterSnapshot,type RouterTransport} from './contracts';
import {useRouterEvidence} from './useRouterEvidence';
import {checkState,downloadEvidence,vendorTime,type Report,type EvidenceData} from './evidence';
import {RouterFacts} from './RouterVPN';
function resolveReport(data:EvidenceData):Report|null {return data.result??data.report??data.operation?.result??null;}
export function RouterDiagnostics({device,value,transport,visible=true}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport;visible?:boolean}){
const read=useRouterEvidence(device,value,transport);
const result=value.results.filter(r=>r.device_id===device.id&&r.action==='diagnostics'&&r.vendor_id&&r.state==='complete').sort((a,b)=>(a.at??0)-(b.at??0)||a.operation_id.localeCompare(b.operation_id)).at(-1);
const id=result?.vendor_id??'';
const allowed=value.read_version===1&&!!device.client_api?.rights.includes('read');
useEffect(()=>{if(visible&&allowed)void read.load(id?'diagnostic':'diagnostics_latest',id);},[visible,allowed,id,read.load]);
const doc=read.document,report=doc?resolveReport(doc.data):null;
const service=report?.service_report??report,checks=service?.checks??report?.checks??report?.machine_checks??[];
const physicalNames=report?.boot_id===device.client_api?.boot_id&&!!device.slot_map?.length;
const display=(text:string|undefined)=>physicalNames?text?.replace(/\bM([123])\b/g,(_,slot:string)=>simLabel(device,Number(slot))):text;
const busy=read.busy||value.results.some(r=>r.state==='queued'||r.state==='applying');
async function bundle(){const data=await read.load('bundle',id);if(data)downloadEvidence(data,`router-diagnostic-${id}.json`);}
return <div className="router-form">
<div className="router-evidence-actions"><Button disabled={!allowed||busy} onClick={()=>void read.load(id?'diagnostic':'diagnostics_latest',id)}>Обновить отчёт</Button><Button disabled={!doc||busy} onClick={()=>doc&&downloadEvidence(doc,'router-diagnostic-report.json')}>Скачать отчёт</Button><Button disabled={!id||busy||!device.client_api?.rights.includes('bundle')} onClick={()=>void bundle()}>Скачать пакет диагностики</Button></div>
{read.busy&&<Description>Загрузка отчёта{read.progress>0?` · ${Math.round(read.progress*100)}%`:''}…</Description>}
{read.error&&<StatusBadge tone="warning">{read.error}</StatusBadge>}
{!allowed&&<Description>Чтение подробных отчётов недоступно для этой версии борта или ключа.</Description>}
{!read.busy&&!read.error&&!report&&allowed&&<Description>Готового отчёта пока нет. Кнопка «Проверить роутер» запускает новую проверку.</Description>}
{report&&<>
<RouterFacts items={[["Начало",vendorTime(report.started_utc??service?.started)],["Завершение",vendorTime(report.finished_utc??service?.finished)],["Длительность",service?.duration_ms==null?'Нет сведений':`${(service.duration_ms/1000).toLocaleString('ru-RU')} с`],["Путь менялся во время проверки",report.path_changed_during_run==null?'Нет сведений':report.path_changed_during_run?'Да':'Нет']]}/>
<Description>Результаты относятся к моменту проверки. Время записано часами роутера; его точность отдельно не подтверждена.</Description>
{report.result_available===false&&<StatusBadge tone="warning">Подробный результат больше не хранится на роутере.</StatusBadge>}
{report.snapshot_omitted&&<Description>Роутер исключил снимок из отчёта из-за ограничения размера.</Description>}
{checks.map((check,i)=><SettingsCard key={`${check.id??check.check_id}:${i}`} title={check.title??check.id??check.check_id??'Проверка'} description={display(check.summary)} actions={<StatusBadge tone="neutral">{checkState(check.state)}</StatusBadge>}>
{!!check.facts?.length&&<ul className="router-report-facts">{check.facts.map((fact,j)=><li key={j}>{display(fact)}</li>)}</ul>}
{check.scope&&<Description>{display(check.scope)}</Description>}{check.impact&&<Description>{display(check.impact)}</Description>}
</SettingsCard>)}
{!!report.target_probes?.length&&<SettingsCard title="Проверки заданных целей">{report.target_probes.map((probe,i)=><div className="router-form" key={i}><strong>{probe.target_id||'Цель'} · {probe.path==='vpn'?'VPN':'Сотовый канал'}</strong><Description>{probe.success===true?'Доступ подтверждён':probe.success===false?'Доступ не подтверждён':'Проверка не завершена'}</Description>{Object.entries(probe.stages??{}).map(([name,s])=><Description key={name}>{name.toUpperCase()} · {s.state||'Нет результата'}{s.duration_ms!=null?` · ${s.duration_ms} мс`:''}</Description>)}</div>)}</SettingsCard>}
</>}
{doc?.resource==='bundle'&&<Description>В пакете отдельно сохранены состояние при проверке ({vendorTime(doc.data.captured_snapshot?.generated_utc)}) и состояние при выгрузке ({vendorTime(doc.data.current_snapshot?.generated_utc)}).</Description>}
</div>;
}
+9 -8
View File
@@ -1,19 +1,20 @@
import {useState} from 'react';
import {useState,type ReactNode} from 'react';
import {Icon,IconButton,ResourceList,ResourceRow,StatusBadge} from '@nodedc/ui-react';
import {modeLabel,routerFresh,routerLabel,type RouterTransport} from './contracts';
import {visibleRouters,modeLabel,routerName,routerFresh,routerLabel,type RouterTransport,type RouterDevice,type RouterSnapshot} from './contracts';
import {useRouters} from './useRouters';
import {RouterDetails} from './RouterDetails';
import './router.css';
export function RouterEquipment({transport}:{transport:RouterTransport}){
export function RouterEquipment({transport,renderSpeedtest}:{transport:RouterTransport;renderSpeedtest?:(device:RouterDevice,value:RouterSnapshot)=>ReactNode}){
const {value,error}=useRouters(transport),[selected,setSelected]=useState<string|null>(null);
const device=value?.items.find(d=>d.id===selected);
if(!value?.items.length)return null;
const connected=visibleRouters(value?.items??[]);
const device=connected.find(d=>d.id===selected);
if(!value||!connected.length)return null;
return <>
<ResourceList aria-label="Роутеры аппарата">{value.items.map(d=>{
<ResourceList aria-label="Роутеры бортового компьютера">{connected.map(d=>{
const fresh=routerFresh(value,d),ready=fresh&&d.state==='ready';
return <li key={d.id}><ResourceRow icon={<Icon name="network"/>} title={d.family} description={`${modeLabel(d.active_mode)} · ${d.address}`} metadata={routerLabel(value,d)} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={ready?'success':'neutral'} aria-label={routerLabel(value,d)}/>} actions={<IconButton label={`Состояние роутера ${d.family}`} onClick={()=>setSelected(d.id)}><Icon name="activity"/></IconButton>}/></li>;
return <li key={d.id}><ResourceRow icon={<Icon name="network"/>} title={routerName(d)} description={`${modeLabel(d.active_mode)} · ${d.address}`} metadata={`${d.connection==='ethernet'?`Ethernet · ${d.interface} · `:''}${d.attached===false?'Отключён':routerLabel(value,d)}`} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={ready?'success':'neutral'} aria-label={routerLabel(value,d)}/>} actions={<IconButton label={`Состояние роутера ${routerName(d)}`} onClick={()=>setSelected(d.id)}><Icon name="activity"/></IconButton>}/></li>;
})}</ResourceList>
{device&&<RouterDetails key={device.id} device={device} value={value} transport={transport} onClose={()=>setSelected(null)} error={error}/>}
{device&&<RouterDetails key={device.id} device={device} value={value} transport={transport} onClose={()=>setSelected(null)} error={error} speedtest={renderSpeedtest?.(device,value)}/>}
</>;
}
+37
View File
@@ -0,0 +1,37 @@
import {useState} from 'react';
import {Button,Description,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
import {routerModel,type RouterDevice,type RouterSnapshot,type RouterTransport} from './contracts';
import {useRouterRequest} from './useRouterRequest';
export function RouterGeneral({device,value,transport}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport}){
const [name,setName]=useState(device.name??''),[address,setAddress]=useState(device.address);
const [username,setUsername]=useState(device.web_username||'admin'),[password,setPassword]=useState(device.web_access?'':'admin');
const [savingWeb,setSavingWeb]=useState(false);
const request=useRouterRequest(value,transport);
const busy=request.busy||value.results.some(r=>r.state==='queued'||r.state==='applying');
const enabled=value.available&&value.fresh!==false&&!!value.runtime_id&&!busy;
function save(web:boolean){
setSavingWeb(web);const secret=web?password:'';if(web)setPassword('');
void request.send({device_id:device.id,settings:{name,address:web?address:device.address,username:web?username:'',password:secret}});
}
return <div className="router-form">
<SettingsCard title="Устройство" description="Название сохраняется для этого экземпляра. Модель определяется по данным платы.">
<div className="router-form">
<TextField label="Название" placeholder={routerModel(device)} value={name} maxLength={128} disabled={busy} onChange={e=>setName(e.target.value)}/>
<TextField label="Модель" value={device.model_name||'Модель платы пока не определена'} readOnly/>
<Description>{device.connection==='ethernet'?`Ethernet · ${device.interface} · ${device.attached===false?'отключён':'подключён к бортовому компьютеру'}`:'Подключение пока не подтверждено'}</Description>
<Button loading={request.busy&&!savingWeb} disabled={!enabled||name===(device.name??'')} onClick={()=>save(false)}>Сохранить название</Button>
</div>
</SettingsCard>
<SettingsCard title="Админка Dexaflow" description={device.web_access?'Доступ сохранён. Пароль обратно не передаётся.':'Подключите админку для определения модели и физических SIM-разъёмов.'}>
<div className="router-form">
<TextField label="Адрес роутера" value={address} maxLength={45} disabled={busy} onChange={e=>setAddress(e.target.value)}/>
<Description>{`http://${address}/cgi-bin/luci/dexaflow`}</Description>
<TextField label="Логин" value={username} maxLength={64} disabled={busy} autoComplete="off" onChange={e=>setUsername(e.target.value)}/>
<TextField label="Пароль админки" type="password" value={password} maxLength={256} disabled={busy} autoComplete="new-password" onChange={e=>setPassword(e.target.value)}/>
<Button loading={request.busy&&savingWeb} disabled={!enabled||!address||!username||!password} onClick={()=>save(true)}>Подключить админку</Button>
<Description>Данные доступа хранятся на борту для этого роутера. Подключение выполняется через его Ethernet-интерфейс.</Description>
</div>
</SettingsCard>
{request.message&&<StatusBadge tone="neutral">{request.message}</StatusBadge>}
</div>;
}
+25 -44
View File
@@ -1,7 +1,11 @@
import {useEffect,useState} from 'react';
import {Button,Icon,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {metric,modeLabel,type RouterDevice,type RouterSnapshot} from './contracts';
import {collectTraffic,modemLabel,signalFraction,trafficPath,trafficRate,trafficWindow,type TrafficHistory} from './overview';
import {Description,Icon,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {simChannels,simLabel,metric,modeLabel,routerName,type RouterDevice,type RouterSnapshot} from './contracts';
import {routerMode} from './mode';
import {RouterVPN} from './RouterVPN';
import {RouterSignal} from './RouterSignal';
import {RouterTraffic} from './RouterTraffic';
import {collectTraffic,modemLabel,trafficRate,type TrafficHistory} from './overview';
export function useRouterTraffic(device:RouterDevice,value:RouterSnapshot,ready:boolean){
const [history,setHistory]=useState<TrafficHistory>({key:'',day:0,points:[]});
@@ -10,44 +14,33 @@ export function useRouterTraffic(device:RouterDevice,value:RouterSnapshot,ready:
return history.key===key?history.points:[];
}
function SignalScale({rsrp}:{rsrp:number|null|undefined}){
const fraction=signalFraction(rsrp);
return <div className="router-signal">
<div className="router-metric-line"><span>Сигнал · RSRP</span><strong>{rsrp==null?'—':metric(rsrp,'dBm')}</strong></div>
<svg className="router-signal-scale" viewBox="0 0 200 24" role="img" aria-label={fraction==null?'Уровень сигнала неизвестен':`RSRP ${metric(rsrp,'dBm')}; шкала от минус 120 до минус 60 dBm`}>
{Array.from({length:20},(_,i)=><rect key={i} x={i*10} y={22-(6+i*0.8)} width="6" height={6+i*0.8} className={fraction!=null&&i<Math.round(fraction*20)?'router-signal-lit':'router-signal-empty'}/>)}
</svg>
<div className="router-scale-labels"><span>−120 dBm</span><span>−60 dBm</span></div>
</div>;
}
export function RouterOverview({device,ready,points}:{device:RouterDevice;ready:boolean;points:TrafficHistory['points']}){
const [details,setDetails]=useState(false);
const selected=/^wan[1-3]$/.test(device.active_wan)?Number(device.active_wan.slice(-1)):null;
const mode=routerMode(device,ready),selected=mode.activeSlot;
const active=device.modems.find(m=>m.slot===selected);
const verified=ready&&device.internet==='verified';
const latest=points.at(-1)?.at??Date.now()/1000,start=latest-trafficWindow;
const max=Math.max(1,...points.flatMap(p=>[p.down??0,p.up??0]));
const hasTrend=points.filter(p=>p.down!=null||p.up!=null).length>=2;
const facts:[string,string][]=[['Роутер',device.address],['Адрес борта',device.local_ip],['Интерфейс борта',device.interface],['Внешний IP',device.public_ip],['Выбранный режим',modeLabel(device.selected_mode)],['Сохранённый режим',modeLabel(device.persisted_mode)],['После перезагрузки',device.reboot_resets===true?'Роутер сообщает о сбросе режима':device.reboot_resets===false?'Сброс режима не заявлен':'Нет сведений'],['Сервер агрегации',device.vps_up==null?'Нет сведений':device.vps_up?'Доступен по данным роутера':'Недоступен по данным роутера'],['Прошивка',device.firmware],['Время работы',device.uptime==null?'Нет сведений':metric(device.uptime/3600,'ч')]];
const facts:[string,string][]=[['Роутер',device.address],['Адрес борта',device.local_ip],['Интерфейс борта',device.interface],['Внешний IP',device.public_ip],['Выбранный режим',modeLabel(device.selected_mode)],['Сохранённый режим',modeLabel(device.persisted_mode)],['После перезагрузки',device.reboot_resets===true?'Роутер сообщает о сбросе режима':device.reboot_resets===false?'Сброс режима не заявлен':'Нет сведений'],['Подтверждение VPN',device.vps_up==null?'Нет сведений':device.vps_up?'Доступен по данным роутера':'Недоступен по данным роутера'],['Прошивка',device.firmware],['Время работы',device.uptime==null?'Нет сведений':metric(device.uptime/3600,'ч')]];
return <div className="router-overview">
<SettingsCard title={modeLabel(device.active_mode)} description="Текущий режим роутера" actions={<StatusBadge tone={verified?'success':ready?'warning':'neutral'}>{verified?'Интернет подтверждён':ready?'Интернет не подтверждён':'Нет свежих данных'}</StatusBadge>}>
<SettingsCard title={`Сейчас: ${mode.current}`} description={`${ready?'Задано':'Последний заданный режим'}: ${mode.configured}`} actions={<StatusBadge tone={verified?'success':ready?'warning':'neutral'}>{verified?'Интернет подтверждён':ready?'Интернет не подтверждён':'Нет свежих данных'}</StatusBadge>}>
<div className="router-form">
{mode.message&&<Description role="status">{mode.message}</Description>}
<div className="router-path" aria-label="Выход роутера в интернет">
<div><Icon name="network"/><strong>DexaFlow</strong><span>{device.address}</span></div>
<div><Icon name="network"/><strong>{routerName(device)}</strong><span>{device.address}</span></div>
<Icon name="chevron-right"/>
<div><strong>{device.active_mode==='direct'&&selected?`SIM M${selected}`:modeLabel(device.active_mode)}</strong><span>{device.active_mode==='direct'?active?.operator||'Оператор неизвестен':device.vps_up==null?'Нет сведений о сервере':device.vps_up?'Сервер доступен':'Сервер недоступен'}</span></div>
<div><strong>{mode.activeMode==='direct'&&selected?simLabel(device,selected):mode.current}</strong><span>{!mode.activeMode?'Нет текущего подтверждения':mode.activeMode==='direct'?active?.operator||'Оператор неизвестен':device.vps_up==null?'Нет сведений о сервере':device.vps_up?'Сервер доступен':'Сервер недоступен'}</span></div>
<Icon name="chevron-right"/>
<div><Icon name="globe"/><strong>Интернет</strong><span>{verified?'По проверке роутера':'Доступ не подтверждён'}</span></div>
</div>
</div>
</SettingsCard>
<div className="router-channel-grid" aria-label="Три SIM-канала">
{[1,2,3].map(slot=>{
{simChannels(device).map(channel=>{
const slot=channel.slot;
const m=device.modems.find(item=>item.slot===slot),empty=m?.radio==='NOSIM',online=ready&&!empty&&m?.connectivity==='online';
return <SettingsCard key={slot} title={`SIM M${slot}`} description={empty?'Слот свободен':m?.operator||'Оператор неизвестен'} actions={<StatusBadge variant="indicator" tone={online?'success':'neutral'} aria-label={modemLabel(m,ready)}/>}>
return <SettingsCard key={slot} title={`${channel.label} (${channel.detail})`} description={empty?'Слот свободен':m?.operator||'Оператор неизвестен'} actions={<StatusBadge variant="indicator" tone={online?'success':'neutral'} aria-label={modemLabel(m,ready)}/>}>
<div className="router-channel-content">
<span className="router-note">{modemLabel(m,ready)}{ready&&device.active_mode==='direct'&&selected===slot?' · выбран':''}</span>
<span className="router-note">{modemLabel(m,ready)}{selected===slot?' · текущий выход':''}</span>
<div className="router-radio-summary">{empty?'—':[m?.technology?.toUpperCase(),m?.band].filter(Boolean).join(' · ')||'Нет сведений о сети'}</div>
<SignalScale rsrp={empty?null:m?.rsrp}/>
<RouterSignal rsrp={empty||!ready?null:m?.rsrp}/>
<div className="router-channel-rates">
<div><Icon name="download"/><span>Приём</span><strong>{ready&&!empty?trafficRate(m?.down_kbps):'—'}</strong></div>
<div><Icon name="upload"/><span>Передача</span><strong>{ready&&!empty?trafficRate(m?.up_kbps):'—'}</strong></div>
@@ -56,23 +49,11 @@ export function RouterOverview({device,ready,points}:{device:RouterDevice;ready:
</SettingsCard>;
})}
</div>
<SettingsCard title="Поток данных" description="Текущий трафик роутера" actions={<span className="router-note">Задержка {ready?metric(device.rtt_ms,'мс'):'—'}</span>}>
<div className="router-traffic-values">
<div><span className="router-download"><Icon name="download"/> Приём</span><strong>{ready?trafficRate(device.down_kbps):'—'}</strong></div>
<div><span className="router-upload"><Icon name="upload"/> Передача</span><strong>{ready?trafficRate(device.up_kbps):'—'}</strong></div>
</div>
{hasTrend?<figure className="router-traffic-chart">
<div className="router-scale-labels"><span>{trafficRate(max)}</span><span>{ready?'Последние 5 минут':'Последние полученные измерения'}</span></div>
<svg viewBox="0 0 320 82" preserveAspectRatio="none" role="img" aria-label="Трафик роутера за последние пять минут: приём — сплошная линия, передача — пунктир. Разрывы означают отсутствие измерений.">
{[4,41,78].map(y=><line key={y} x1="2" x2="318" y1={y} y2={y} className="router-chart-grid"/>)}
<path d={trafficPath(points,'down',start,latest,max)} className="router-chart-down"/>
<path d={trafficPath(points,'up',start,latest,max)} className="router-chart-up"/>
</svg>
<figcaption className="router-scale-labels"><span>−5 мин</span><span>{new Date(latest*1000).toLocaleTimeString('ru-RU')}</span></figcaption>
</figure>:<p className="router-note router-chart-empty">{ready?'Ожидание следующего измерения для графика':'Нет свежих измерений для графика'}</p>}
<p className="router-note">Трафик — текущая передача данных. Он не показывает предельную скорость интернета.</p>
<Description>«В сети» — подключение к оператору. Трафик на нескольких SIM сам по себе не подтверждает агрегацию.</Description>
<SettingsCard title="Поток данных" description={device.client_api?"Суммарный трафик сотовых каналов":"Текущий трафик роутера"} actions={<span className="router-note">Задержка {ready?metric(device.rtt_ms,'мс'):'—'}</span>}>
<RouterTraffic points={points} ready={ready} down={device.down_kbps} up={device.up_kbps}/>
</SettingsCard>
<div className="router-actions"><Button aria-expanded={details} onClick={()=>setDetails(open=>!open)}>{details?'Скрыть сведения о подключении':'Сведения о подключении'}</Button></div>
{details&&<SettingsCard title="Подключение"><dl className="router-facts">{facts.map(([label,v])=><div key={label}><dt>{label}</dt><dd>{v||'Нет сведений'}</dd></div>)}</dl><p className="router-note">Отдельная проверка DNS не получена. Радиопоказатели относятся к модему; исправность отдельной антенны по ним не определяется.</p></SettingsCard>}
<RouterVPN device={device} ready={ready}/>
<SettingsCard title="Подключение"><dl className="router-facts router-connection-facts">{facts.map(([label,v])=><div key={label}><dt>{label}</dt><dd>{v||'Нет сведений'}</dd></div>)}</dl><Description>Доступность интернета подтверждается отдельными проверками. Радиопоказатели относятся к модему; исправность отдельной антенны по ним не определяется.</Description></SettingsCard>
</div>;
}
@@ -0,0 +1,21 @@
import {useEffect,useState} from 'react';
import {Description,Select,SettingsCard} from '@nodedc/ui-react';
import {metric,simChannels,type RouterDevice,type RouterSnapshot} from './contracts';
import {collectRadio,radioChanges,radioMetrics,radioPath,radioSegments,type RadioHistory} from './radioHistory';
export function useRadioHistory(device:RouterDevice,value:RouterSnapshot,ready:boolean){
const [history,setHistory]=useState<RadioHistory>({key:'',day:0,samples:[]});
const key=`${value.runtime_id}:${device.id}:${device.client_api?.boot_id}:${JSON.stringify(device.slot_map)}`;
useEffect(()=>{setHistory(previous=>collectRadio(previous,key,device,ready,Date.now()/1000));},[key,device,ready]);
return history.key===key?history.samples:[];
}
export function RouterRadioHistory({device,samples}:{device:RouterDevice;samples:RadioHistory['samples']}){
const [field,setField]=useState<keyof typeof radioMetrics>('rsrp'),m=radioMetrics[field];
return <div className="router-form">
<Select label="История радиоканала" value={field} options={Object.entries(radioMetrics).map(([value,m])=>({value,label:m.label}))} onChange={s=>setField(s as keyof typeof radioMetrics)}/>
<Description>Последние пять минут, пока открыто окно роутера. Разрывы — пропуски измерений или смена диапазона/соты.</Description>
{simChannels(device).map(channel=>{const points=samples.filter(s=>s.slot===channel.slot),end=points.at(-1)?.at??0,last=points.at(-1),changes=radioChanges(points),valid=points.filter(p=>p[field]!=null).length;return <SettingsCard key={channel.slot} title={`${channel.label} · ${m.label}`} description={last?`${metric(last[field],m.unit)}${last.band?` · ${last.band}`:''}`:'Свежих измерений пока нет'}>
{valid>=2?<figure className="router-traffic-chart"><div className="router-scale-labels"><span>{m.max} {m.unit}</span><span>{m.min} {m.unit}</span></div><svg viewBox="0 0 320 82" preserveAspectRatio="none" role="img" aria-label={`${channel.label}: ${m.label} за пять минут`}><line x1="2" x2="318" y1="78" y2="78" className="router-chart-baseline"/><path d={radioPath(points,field,end)} className="router-chart-line router-chart-down"/>{radioSegments(points,field,end).filter(p=>p.length===1).map((p,i)=><circle key={i} cx={p[0].x} cy={p[0].y} r="1.5" className="router-chart-point-down"/>)}</svg><figcaption className="router-scale-labels"><span>−5 мин</span><span>{new Date(end*1000).toLocaleTimeString('ru-RU')}</span></figcaption></figure>:<Description>{valid===1?'Ожидание следующего измерения.':'Радиопоказателей для этой SIM пока нет.'}</Description>}
{changes.length?<ol className="router-events">{changes.map((c,i)=><li key={i}><time>{new Date(c.at*1000).toLocaleTimeString('ru-RU')}</time><span>{c.text}</span></li>)}</ol>:<Description>Смен диапазона или соты в непрерывных наблюдениях пока нет.</Description>}
</SettingsCard>;})}
</div>;
}
@@ -0,0 +1,22 @@
import {useState} from 'react';
import {Description,Select,SettingsCard} from '@nodedc/ui-react';
import {metric,modeLabel,simLabel,simChannels,type RouterDevice} from './contracts';
import {vendorTime,type EvidenceData,type FlightSample} from './evidence';
import {RouterFacts} from './RouterVPN';
export function recordingState(v:string){return ({completed:'Запись завершена',capturing_after:'Записывается состояние после события',interrupted_module_shutdown:'Запись прервана при остановке',interrupted_previous_process:'Запись прервана перезапуском'} as Record<string,string>)[v]??'Состояние не определено';}
export function RouterRecording({data,device}:{data:EvidenceData;device:RouterDevice}){
const samples=data.samples??[],[selected,setSelected]=useState('0');const sample:FlightSample|undefined=samples[Number(selected)]??samples[0];
const order=simChannels(device).map(s=>s.slot),wans=[...(sample?.state.wan??[])];
if(sample?.boot_id===device.client_api?.boot_id)wans.sort((a,b)=>order.indexOf(Number(a.slot?.slice(1)))-order.indexOf(Number(b.slot?.slice(1))));
const registration=(v:string|undefined|null)=>({home:'Домашняя сеть',roaming:'Роуминг',idle:'Не зарегистрирован',searching:'Поиск сети',denied:'Регистрация отклонена',unknown:'Не определена'} as Record<string,string>)[v??'']??v??'';
const when=(s:FlightSample)=>{const delta=data.started_utc==null?null:s.observed_utc-data.started_utc;return `${new Date(s.observed_utc*1000).toLocaleTimeString('ru-RU')}${delta==null?'':delta<0?` · ${Math.abs(delta)} с до события`:` · ${delta} с после`}`;};
return <div className="router-form">
<Description>{recordingState(data.state??'')} · {vendorTime(data.started_utc)}. {data.truncated?'Часть контекста сокращена роутером. ':''}Запись показывает последовательность наблюдений; причина события по ней не установлена.</Description>
{samples.length?<Select label="Момент записи" value={selected} options={samples.map((s,i)=>({value:String(i),label:when(s)}))} onChange={setSelected}/>:<Description>Измерения в записи отсутствуют.</Description>}
{sample&&<>
<RouterFacts items={[["Время",vendorTime(sample.observed_utc)],["Время после загрузки",metric(sample.uptime,'с')],["Режим",modeLabel(sample.state.observed?.active??'')],["VPN",sample.state.vpn?.verified===true?'Подтверждён':sample.state.vpn?.verified===false?'Не подтверждён':'Нет сведений'],["Готовый резерв",sample.state.reserve?.count==null?'Нет сведений':String(sample.state.reserve.count)],["SIM в резерве",sample.state.reserve?.distinct_sim_count==null?'Нет сведений':String(sample.state.reserve.distinct_sim_count)]]}/>
{sample.boot_id!==device.client_api?.boot_id&&<Description>Запись относится к предыдущей загрузке. Привязка старых номеров каналов к физическим SIM не подтверждена.</Description>}
<div className="router-channel-grid">{wans.map((wan,i)=>{const slot=Number(wan.slot?.slice(1)),radio=wan.radio;return <SettingsCard key={`${wan.slot}:${i}`} title={sample.boot_id===device.client_api?.boot_id?simLabel(device,slot):`Канал ${slot||i+1}`} description={wan.operator||'Оператор не записан'}><RouterFacts items={[["Соединение",wan.up===true?'Поднято':wan.up===false?'Не поднято':'Нет сведений'],["Регистрация",registration(wan.network_registration?.registration_state)],["Диапазон",radio?.band??''],["RSRP",metric(radio?.rsrp_dbm,'dBm')],["RSRQ",metric(radio?.rsrq_db,'dB')],["SINR",metric(radio?.sinr_db,'dB')],["Сота",radio?.cell_id??'']]}/></SettingsCard>;})}</div>
</>}
</div>;
}
+25
View File
@@ -0,0 +1,25 @@
import {Description,Tooltip} from '@nodedc/ui-react';
import {metric} from './contracts';
import {signalBands,signalLevel} from './overview';
export function RouterSignal({rsrp}:{rsrp:number|null|undefined}){
const level=signalLevel(rsrp);
return <div className="router-signal">
<div className="router-metric-line"><span>Сигнал</span><strong>{level==null?'—':metric(rsrp,'dBm')}</strong></div>
<div className="router-signal-scale" role="group" aria-label={level==null?'Уровень сигнала неизвестен':`${signalBands[level].label} сигнал · RSRP ${metric(rsrp,'dBm')}`}>
{signalBands.map((band,i)=>{
const current=level===i,position=current?Math.max(0.12,Math.min(0.88,(rsrp!-band.min)/(band.max-band.min))):0;
const fill=level==null||level<i?0:level>i?100:position*100;
return <Tooltip key={band.label} focusable className="router-signal-zone"
label={`${band.label} сигнал: ${band.range}${current?' · текущий уровень':''}`}
content={<><strong>{band.label} сигнал</strong><Description>{band.range}</Description><Description>{level==null?'Текущий уровень не получен':`Сейчас: ${metric(rsrp,'dBm')} · ${signalBands[level].label.toLowerCase()}`}</Description></>}>
<span className="router-signal-track" aria-hidden="true" data-current={current}>
<span className="router-signal-fill" style={{width:`${fill}%`}}/>
{current&&<span className="router-signal-marker" style={{left:`${position*100}%`}}/>}
</span>
</Tooltip>;
})}
</div>
<div className="router-scale-labels"><span>Слабый</span><span>Отличный</span></div>
</div>;
}
+28
View File
@@ -0,0 +1,28 @@
import {useId} from 'react';
import {Description,Icon} from '@nodedc/ui-react';
import {trafficArea,trafficCeiling,trafficPath,trafficRate,trafficSegments,trafficWindow,type TrafficPoint} from './overview';
export function RouterTraffic({points,ready,down,up}:{points:TrafficPoint[];ready:boolean;down:number|null;up:number|null}){
const gradient=`router-traffic-${useId().replaceAll(':','')}`;
const latest=points.at(-1)?.at??Date.now()/1000,start=latest-trafficWindow,max=trafficCeiling(points);
const hasTrend=points.filter(p=>p.down!=null||p.up!=null).length>=2;
return <>
<div className="router-traffic-values">
<div><span className="router-download"><i className="router-traffic-key"/><Icon name="download"/> Приём</span><strong>{ready?trafficRate(down):'—'}</strong></div>
<div><span className="router-upload"><i className="router-traffic-key"/><Icon name="upload"/> Передача</span><strong>{ready?trafficRate(up):'—'}</strong></div>
</div>
{hasTrend?<figure className="router-traffic-chart">
<div className="router-scale-labels"><span>{trafficRate(max)}</span><span>{ready?'Последние 5 минут':'Последние полученные измерения'}</span></div>
<svg viewBox="0 0 320 82" preserveAspectRatio="none" role="img" aria-label="Трафик за последние пять минут: приём — светлая линия, передача — серая точечная. Плавные линии проходят через измерения; разрывы означают отсутствие данных.">
<defs><linearGradient id={gradient} x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="var(--nodedc-text-primary)" stopOpacity=".14"/><stop offset="100%" stopColor="var(--nodedc-text-primary)" stopOpacity="0"/></linearGradient></defs>
<path d={trafficArea(points,'down',start,latest,max)} fill={`url(#${gradient})`} className="router-chart-area"/>
<line x1="2" x2="318" y1="78" y2="78" className="router-chart-baseline"/>
<path d={trafficPath(points,'up',start,latest,max)} className="router-chart-line router-chart-up"/>
<path d={trafficPath(points,'down',start,latest,max)} className="router-chart-line router-chart-down"/>
{(['down','up'] as const).flatMap(field=>trafficSegments(points,field,start,latest,max).filter(s=>s.length===1).map((s,i)=><circle key={`${field}:${i}`} cx={s[0].x} cy={s[0].y} r="1.2" className={`router-chart-point router-chart-point-${field}`}/>))}
</svg>
<figcaption className="router-scale-labels"><span>−5 мин</span><span>{new Date(latest*1000).toLocaleTimeString('ru-RU')}</span></figcaption>
</figure>:<div className="router-chart-empty"><Description>{!ready?'Нет свежих измерений для графика':down==null&&up==null?'Скорость пока не получена от роутера':'Ожидание следующего измерения для графика'}</Description></div>}
<Description>Текущий трафик, а не предел скорости интернета.</Description>
</>;
}
+18
View File
@@ -0,0 +1,18 @@
import {Description,SettingsCard} from '@nodedc/ui-react';
import {metric,simLabel,type RouterDevice} from './contracts';
export function RouterFacts({items}:{items:[string,string][]}){return <dl className="router-facts router-connection-facts">{items.map(([label,value])=><div key={label}><dt>{label}</dt><dd>{value||'Нет сведений'}</dd></div>)}</dl>;}
const flag=(v:boolean|null|undefined,yes='Да',no='Нет')=>v==null?'Нет сведений':v?yes:no;
const phase=(v:string)=>({no_keys:'Нет ключей резерва',ready:'Готов',preparing:'Подготовка',pending:'Выполняется',manual:'Ручной выбор',idle:'Ожидание',running:'Работает',healthy:'В порядке',failed:'Не подтверждён'} as Record<string,string>)[v]||v||'Нет сведений';
export function RouterVPN({device,ready}:{device:RouterDevice;ready:boolean}){
const d=device.client_api?.details;if(!d)return null;const v=d.vpn,r=d.reserve;
const label=(sim:string)=>/^M[1-3]$/.test(sim)?simLabel(device,Number(sim.slice(1))):'Не определена';
const stale=r.age!=null&&r.ttl!=null&&r.age>r.ttl;
return <SettingsCard title="VPN и резерв" description={!ready?'Последние полученные сведения':d.fallback?'Роутер использует резервный путь':'Текущее состояние по данным роутера'}>
<RouterFacts items={[
['VPN выбран',flag(v.selected)],['VPN активен',flag(v.active)],['VPN проверен',flag(v.verified,'Подтверждён','Не подтверждён')],['SIM для VPN',label(v.sim)],['Сервер VPN',v.server],['Контроль VPN',phase(v.watch_state)],['Возраст контроля',metric(v.watch_age,'с')],['Последний успех',v.last_success_age==null?'Нет сведений':`${metric(v.last_success_age,'с')} назад`],['Возраст подтверждения',metric(v.proof_age,'с')],
['Готовые варианты резерва',`${r.count??'—'} из ${r.target??'—'}`],['Независимые SIM в резерве',r.distinct_sims==null?'Нет сведений':String(r.distinct_sims)],['Подготовка резерва',phase(r.phase)],['Служба резерва',flag(r.running,'Запущена','Остановлена')],['Сведения о резерве',flag(r.available,'Доступны','Недоступны')],['Возраст резерва',`${metric(r.age,'с')}${stale?' · устарел':''}`],['Срок подтверждения',metric(r.ttl,'с')],['Восстановление',flag(d.pending,'Выполняется','Нет ожидающего действия')],['Последняя попытка',flag(d.last_attempt_current,'Для текущих настроек','Нет подтверждения для текущих настроек')],
]}/>
{!!r.pairs.length&&<ul className="router-events">{r.pairs.map((p,i)=><li key={i}><strong>{label(p.sim)} · {p.server||'Сервер не указан'}</strong><span>{p.transport||'Транспорт не указан'} · подтверждение {metric(p.age,'с')} назад</span></li>)}</ul>}
<Description>Вариант резерва — пара сервера и SIM. Несколько вариантов могут использовать одну SIM. Запущенная служба сама по себе не подтверждает связь.</Description>
</SettingsCard>;
}
@@ -0,0 +1,36 @@
import {useEffect,useState} from 'react';
import {Button,Description,Select,StatusBadge} from '@nodedc/ui-react';
import type {RouterDevice,RouterSnapshot,RouterTransport} from './contracts';
import {useRouterEvidence} from './useRouterEvidence';
import {downloadEvidence,vendorTime,type EvidenceResource,type VendorEvent,type Recording,type VendorOperation} from './evidence';
import {RouterRecording,recordingState} from './RouterRecording';
export function RouterVendorHistory({device,value,transport}:{device:RouterDevice;value:RouterSnapshot;transport:RouterTransport}){
const [source,setSource]=useState<EvidenceResource>('events'),[events,setEvents]=useState<VendorEvent[]>([]),[operations,setOperations]=useState<VendorOperation[]>([]),[records,setRecords]=useState<Recording[]>([]),[cursor,setCursor]=useState(''),[selected,setSelected]=useState(''),[pageFull,setPageFull]=useState(false);
const read=useRouterEvidence(device,value,transport),allowed=value.read_version===1&&!!device.client_api?.rights.includes('read');
const busy=read.busy||value.results.some(r=>r.state==='queued'||r.state==='applying');
async function load(after=''){
const doc=await read.load(source,'',after);if(!doc)return;
const data=doc.data,next=source==='recovery_history'?data.entries??[]:data.events??[];
setEvents(previous=>[...(after?previous:[]),...next].filter((e,i,all)=>all.findIndex(a=>a.source===e.source&&(a.boot_id??a.boot)===(e.boot_id??e.boot)&&a.sequence===e.sequence)===i).slice(-200));
setOperations(data.operations??[]);setRecords(data.recordings??[]);setCursor(data.cursor??'');setPageFull(next.length>=50);setSelected('');
}
useEffect(()=>{setEvents([]);setOperations([]);setRecords([]);setCursor('');setSelected('');setPageFull(false);if(allowed)void load();},[source,allowed,read.load]);
return <div className="router-form">
<Select label="История роутера" value={source} disabled={busy} options={[{value:'events',label:'События прошивки'},{value:'recovery_history',label:'Восстановление и команды'},{value:'recordings',label:'Записи до и после события'}]} onChange={s=>setSource(s as EvidenceResource)}/>
<div className="router-evidence-actions"><Button disabled={!allowed||busy} onClick={()=>void load()}>Обновить список</Button>{selected&&<Button disabled={busy} onClick={()=>setSelected('')}>К списку записей</Button>}<Button disabled={!read.document||busy} onClick={()=>downloadEvidence(selected?read.document:{schema:'missioncore.router-history-view/v1',device_id:device.id,source,events,operations,recordings:records},selected?'router-recording.json':'router-history.json')}>Скачать</Button></div>
{read.busy&&<Description>Загрузка{read.progress>0?` · ${Math.round(read.progress*100)}%`:''}…</Description>}{read.error&&<StatusBadge tone="warning">{read.error}</StatusBadge>}
{!allowed&&<Description>Чтение истории недоступно для этой версии борта или ключа.</Description>}
{source==='recordings'?selected&&read.document?.resource==='recording'&&read.document.data.id===selected?<RouterRecording key={selected} data={read.document.data} device={device}/>:<>
<Description>Роутер сохраняет короткие пассивные записи вокруг изменений связи. Это наблюдения состояния, а не запись сетевых пакетов.</Description>
{!read.busy&&!records.length&&<Description>Записей пока нет.</Description>}
<ol className="router-events">{records.map(r=><li key={r.id}><time>{vendorTime(r.started_utc)}</time><strong>{recordingState(r.state)}</strong><span>{typeof r.samples==='number'?r.samples:r.samples.length} измерений{r.truncated?' · контекст сокращён':''}</span><Button disabled={busy} onClick={async()=>{const doc=await read.load('recording',r.id);if(doc)setSelected(r.id);}}>Открыть запись</Button></li>)}</ol>
</>:<>
<Description>Время — по часам роутера. Порядок событий сохраняется внутри источника; соседство по времени не доказывает причину. Обозначения каналов относятся к моменту записи.</Description>
{!read.busy&&!events.length&&<Description>Событий в этом окне нет.</Description>}
<ol className="router-events">{events.map((e,i)=><li key={`${e.source}:${e.boot_id??e.boot}:${e.sequence}:${i}`}><time>{vendorTime(e.observed_utc??e.epoch)}{e.uptime!=null?` · ${Math.floor(e.uptime)} с после загрузки`:''}</time><strong>{e.topic||'Событие'} · {e.summary||e.message||e.recorded_code||e.code||'Нет описания'}</strong><span>{e.source==='firmware'?'Прошивка':e.source==='client_api'?'Клиент API':e.source||'Источник не указан'}{e.initiator_kind==='not_recorded'?' · инициатор не записан':''}</span></li>)}</ol>
{pageFull&&<Button disabled={busy||!cursor} onClick={()=>void load(cursor)}>Следующие события</Button>}
{events.length>=200&&<Description>В окне оставлены последние 200 загруженных событий.</Description>}
{!!operations.length&&<><Description>Последние команды API</Description><ol className="router-events">{operations.map((op,i)=><li key={op.operation_id??i}><time>{vendorTime(op.accepted_utc)}</time><strong>{{policy:'Смена режима',recovery:'Восстановление',reboot:'Перезагрузка',diagnostics:'Диагностика'}[op.kind??'']??'Команда'} · {{succeeded:'Выполнена',failed:'Отклонена',running:'Выполняется',accepted:'Принята',interrupted:'Прервана'}[op.state??'']??'Результат не подтверждён'}</strong><span>{op.actor?`Инициатор: ${op.actor}`:'Инициатор не указан'}</span></li>)}</ol></>}
</>}
</div>;
}
+36 -5
View File
@@ -1,24 +1,43 @@
import type {ClientDetails,EvidenceChunk,EvidenceRequest} from './evidence';
export interface RouterPolicy {
mode:'direct'|'vpn'|'aggregation'|'whitelist';preferred_sim?:'M1'|'M2'|'M3'|null;
allow_fallback:boolean;return_to_preferred:boolean;persist:boolean;
fail_seconds:number;recover_seconds:number;min_vpn_seconds:number;fallback_sims?:string[];
}
export interface RouterClientAPI {
details?:ClientDetails|null;
module_version:string;schema_version:string;clock_quality:string;boot_id:string;revision:string;rights:string[];policy:RouterPolicy;
wan:{slot:number;wan:string;interface:string;up:boolean|null;sim_present:boolean|null;modem_present:boolean|null;registration:string;failure_reason:string;fresh:boolean|null;age_seconds:number|null;traffic?:{rx_bytes:number|null;tx_bytes:number|null;rx_packets:number|null;tx_packets:number|null;rx_errors:number|null;tx_errors:number|null;rx_dropped:number|null;tx_dropped:number|null}|null;observed_uptime?:number|null;session_uptime?:number|null}[];
recovery_phase:string;recovery_reason:string;checks:{id:string;state:string;code:string}[];
}
export interface RouterModem {
radio_age_seconds?:number|null;earfcn?:number|null;tac?:string;
slot:number;operator:string;connectivity:string;radio:string;ip:string;technology:string;band:string;
bandwidth:number|null;rsrp:number|null;rsrq:number|null;sinr:number|null;rssi:number|null;cell_id:string;pci:number|null;down_kbps:number|null;up_kbps:number|null;
}
export interface RouterDevice {
id:string;family:'DexaFlow';identity:'local_mac';address:string;interface:string;local_ip:string;
name?:string;model_name?:string;board_id?:string;slot_map?:{slot:number;sim:number;position:'right'|'center'|'left'}[]|null;
attached?:boolean|null;connection?:''|'ethernet';web_access?:boolean;web_username?:string;
id:string;family:'DexaFlow';identity:'local_mac'|'device_ca';model_id?:string;adapter?:string;client_api?:RouterClientAPI|null;address:string;interface:string;local_ip:string;
state:'ready'|'access_required'|'access_rejected'|'unreachable'|'incompatible';observed_at:number;
firmware:string;uptime:number|null;selected_mode:string;active_mode:string;persisted_mode:string;reboot_resets:boolean|null;
manual_mode?:string;active_slots?:number[];
active_wan:string;internet:'unknown'|'verified';public_ip:string;vps_up:boolean|null;rtt_ms:number|null;down_kbps:number|null;up_kbps:number|null;modems:RouterModem[];
}
export interface RouterIncident {sequence:number;at:number;boot_id:string;elapsed_ms:number;device_id:string;code:string;slot?:number;before?:string;after?:string}
export interface RouterReceipt {operation_id:string;state:'queued'|'applying'|'complete'|'error'|'unknown';error?:string;device_id?:string;action?:string}
export interface SpeedMeasurement {phase:'latency'|'download'|'upload'|'complete'|'cancelled'|'error';server_id:string;interface:string;started_at:number;finished_at?:number;sampled_at?:number;current_bps?:number;download_bps:number;upload_bps:number;latency_ms:number;jitter_ms:number;error?:string}
export interface RouterReceipt {measurement?:SpeedMeasurement;at?:number;evidence?:EvidenceChunk;vendor_id?:string;operation_id:string;state:'queued'|'applying'|'complete'|'error'|'unknown';error?:string;device_id?:string;action?:string}
export interface RouterSnapshot {
speedtest_version?:number;
read_version?:number;evidence?:EvidenceChunk|null;
control_version?:number;available:boolean;fresh?:boolean;runtime_id?:string;observed_at?:number;received_at?:number;
items:RouterDevice[];events:RouterIncident[];results:RouterReceipt[];
journal?:{first_sequence:number;last_sequence:number;dropped:number;limit:number;retention_days:number;error:boolean};
}
export interface RouterAccess {operation_id:string;runtime_id:string;device_id:string;deadline:number;username:string;password:string}
export interface RouterControl {operation_id:string;runtime_id:string;device_id:string;deadline:number;action:'mode'|'reboot';mode:'direct'|'aggregation'|'';slots:number[]}
export interface RouterAccess {operation_id:string;runtime_id:string;device_id:string;deadline:number;username?:string;password?:string;model_id?:string;client_api?:{token:string;ca:string};settings?:{name:string;address:string;username:string;password:string}}
export interface RouterControl {operation_id:string;runtime_id:string;device_id:string;deadline:number;action:'mode'|'reboot'|'policy'|'recovery'|'diagnostics';mode:'direct'|'aggregation'|'';slots:number[];policy?:RouterPolicy|null;recovery?:string;sim?:string;expected_boot_id?:string;expected_revision?:string}
export interface RouterTransport {
inspect?:(value:EvidenceRequest)=>Promise<RouterReceipt>;
read:()=>Promise<RouterSnapshot>;
control:(value:RouterControl)=>Promise<RouterReceipt>;
authorize:(value:RouterAccess)=>Promise<RouterReceipt>;
@@ -31,10 +50,22 @@ export function routerLabel(value:RouterSnapshot|null,device:RouterDevice,now=Da
if(!routerFresh(value,device,now))return 'Нет свежих данных';
return {ready:'Роутер доступен',access_required:'Нужен доступ',access_rejected:'Проверьте доступ',unreachable:'Нет связи с роутером',incompatible:'Ответ роутера не поддерживается'}[device.state];
}
export function modeLabel(value:string):string{return ({direct:'Одна SIM-карта',aggregation:'Агрегация',proxy:'Агрегация',whitelist:'Выбранные каналы',vpn:'VPN',auto:'Автоматически',off:'Выключено'} as Record<string,string>)[value]??'Нет сведений';}
export function modeLabel(value:string):string{return ({direct:'Прямой выход через SIM',aggregation:'Агрегация',proxy:'Агрегация',whitelist:'Белый список (whitelist)',vpn:'VPN',auto:'Автоматически',off:'Выключено'} as Record<string,string>)[value]??'Нет сведений';}
export function metric(value:number|null|undefined,unit:string):string{return value==null?'Нет сведений':`${value.toLocaleString('ru-RU',{maximumFractionDigits:1})} ${unit}`;}
export const incidentLabels:Record<string,string>={discovered:'Роутер обнаружен',availability:'Доступность роутера изменилась',address_changed:'Локальный адрес изменился',router_restarted:'Роутер перезагрузился',mode_changed:'Активный режим изменился',internet_verification:'Проверка интернета изменилась',firmware_changed:'Версия прошивки изменилась',modem_state:'Состояние модема изменилось',operator_changed:'Оператор изменился',signal_weak:'Слабый радиосигнал сохраняется',signal_recovered:'Радиосигнал восстановился',access_rejected:'Доступ отклонён',access_granted:'Доступ подтверждён',command_requested:'Команда отправлена',command_complete:'Команда подтверждена',command_unconfirmed:'Результат команды не подтверждён',command_failed:'Команда отклонена'};
export function incidentValue(value:string|undefined):string{
if(!value)return '';
return ({mode:'смена режима',reboot:'перезагрузка',router_busy:'роутер занят',sim_unavailable:'SIM недоступна',command_rejected:'отклонено',ready:'доступен',access_required:'нужен доступ',access_rejected:'доступ отклонён',unreachable:'нет связи',incompatible:'ответ не поддерживается',unknown:'не проверен',verified:'подтверждён',direct:'одна SIM',aggregation:'агрегация',proxy:'агрегация'} as Record<string,string>)[value]??value;
}
export function routerModel(device:RouterDevice):string{return device.model_name||device.family||'Роутер';}
export function routerName(device:RouterDevice):string{return device.name||routerModel(device);}
export function simChannels(device:RouterDevice){
const map=device.slot_map;
if(map?.length===3&&new Set(map.map(x=>x.sim)).size===3&&new Set(map.map(x=>x.slot)).size===3){
return [...map].sort((a,b)=>a.sim-b.sim).map(x=>({...x,label:`SIM${x.sim}`,detail:`M.2 · ${x.position}`}));
}
return [1,2,3].map(slot=>({slot,sim:null,position:'',label:`Канал ${slot}`,detail:`M${slot}`}));
}
export function simLabel(device:RouterDevice,slot:number):string{return simChannels(device).find(s=>s.slot===slot)?.label||'Канал не определён';}
export function visibleRouters(items:RouterDevice[]):RouterDevice[]{return items.filter(d=>d.attached??d.state!=='unreachable');}
+5 -1
View File
@@ -4,7 +4,11 @@ export function availableSlots(device:RouterDevice):number[]{return device.modem
export function controlEnabled(value:RouterSnapshot,device:RouterDevice,ready:boolean):boolean{return ready&&value.control_version===1&&!!value.runtime_id&&!value.results.some(controlBusy)&&device.state==='ready';}
export function controlMessage(result:RouterReceipt):string{
if(result.state==='queued')return 'Ожидание команды на борту…';
if(result.state==='applying'&&['policy','recovery','diagnostics'].includes(result.action??''))return 'Ожидаем результат операции роутера…';
if(result.state==='complete'&&result.action==='policy')return 'Политика сохранена и применена роутером. Фактический канал показан в обзоре.';
if(result.state==='complete'&&result.action==='recovery')return 'Действие восстановления выполнено. Доступность интернета проверяйте по текущему состоянию.';
if(result.state==='complete'&&result.action==='diagnostics')return 'Диагностика завершена.';
if(result.state==='applying')return result.action==='reboot'?'Ожидание роутера после перезагрузки…':'Проверяем режим и выбранные SIM…';
if(result.state==='complete')return result.action==='reboot'?'Перезагрузка подтверждена. Текущий режим показан в обзоре.':'Режим и выбранные SIM подтверждены роутером.';
return ({expired:'Команда не выполнена: срок запроса истёк.',access_rejected:'Роутер отклонил доступ. Проверьте вкладку «Доступ».',router_unavailable:'Роутер недоступен.',storage_error:'Не удалось сохранить команду на борту.',sim_unavailable:'Выбранная SIM недоступна или ещё не получила IP-адрес.',router_busy:'Роутер занят переключением. Дождитесь обновления состояния.',command_rejected:'Роутер отклонил команду.',unsupported_response:'Прошивка не подтвердила совместимость команды.'} as Record<string,string>)[result.error??'']??'Результат не подтверждён. Проверьте текущее состояние перед новой командой.';
return ({router_conflict:'Состояние изменилось или роутер занят. Обновите настройки перед новой командой.',router_certificate_rejected:'Сертификат роутера не прошёл проверку.',expired:'Команда не выполнена: срок запроса истёк.',access_rejected:'Роутер отклонил доступ. Проверьте вкладку «Доступ».',router_unavailable:'Роутер недоступен.',storage_error:'Не удалось сохранить команду на борту.',sim_unavailable:'Выбранная SIM недоступна или ещё не получила IP-адрес.',router_busy:'Роутер занят переключением. Дождитесь обновления состояния.',command_rejected:'Роутер отклонил команду.',unsupported_response:'Прошивка не подтвердила совместимость команды.'} as Record<string,string>)[result.error??'']??'Результат не подтверждён. Проверьте текущее состояние перед новой командой.';
}
+48
View File
@@ -0,0 +1,48 @@
import type {RouterDevice,RouterReceipt,RouterSnapshot,RouterTransport} from './contracts';
export type EvidenceResource='diagnostics_latest'|'diagnostic'|'bundle'|'events'|'recovery_history'|'recordings'|'recording'|'targets';
export interface EvidenceQuery {resource:EvidenceResource;id:string;after:string;transfer:string;offset:number}
export interface EvidenceRequest {operation_id:string;runtime_id:string;device_id:string;deadline:number;action:'inspect';expected_boot_id:string;query:EvidenceQuery}
export interface EvidenceChunk {operation_id:string;device_id:string;boot_id:string;resource:EvidenceResource;id:string;transfer:string;offset:number;total:number;at:number;data:string}
export interface EvidenceDocument<T=EvidenceData> {schema:'missioncore.router-evidence/v1';resource:EvidenceResource;omitted_fields:number;data:T}
export interface Check {id:string;check_id?:string;state:string;code?:string;title?:string;summary?:string;facts?:string[];scope?:string;impact?:string;cause?:string;checked?:number;checked_utc?:number}
export interface Report {id?:string;boot_id?:string;clock_quality?:string;state?:string;started?:number;finished?:number;started_utc?:number;finished_utc?:number;duration_ms?:number;checks?:Check[];machine_checks?:Check[];service_report?:Report;result_available?:boolean;path?:string;active?:string;selected?:string;path_changed_during_run?:boolean;lan_client_tested?:boolean;snapshot_omitted?:boolean;target_probes?:Probe[];snapshot?:{generated_utc?:number};operation_id?:string}
export interface Probe {target_id?:string;path?:string;sim?:string;state?:string;success?:boolean;reason?:string;stages?:Record<string,{state?:string;duration_ms?:number;code?:string;success?:boolean}>}
export interface VendorEvent {source?:string;sequence?:number;boot?:string;boot_id?:string;epoch?:number;observed_utc?:number;uptime?:number;clock_quality?:string;topic?:string;message?:string;summary?:string;code?:string;recorded_code?:string;category?:string;initiator_kind?:string;actor?:string;operation_id?:string;level?:string;severity?:string}
export interface VendorOperation {operation_id?:string;kind?:string;state?:string;accepted_utc?:number;accepted_boot_id?:string;accepted_uptime?:number;actor?:string;result?:Report}
export interface FlightWAN {slot?:string;up?:boolean|null;operator?:string;sim_present?:boolean|null;network_registration?:{registration_state?:string|null;failure_reason?:string|null};radio?:{rsrp_dbm?:number|null;rsrq_db?:number|null;sinr_db?:number|null;band?:string|null;cell_id?:string|null}}
export interface FlightSample {observed_utc:number;boot_id:string;uptime:number;clock_quality?:string;state:{effective_wan?:string|null;observed?:{active?:string;pending?:boolean;phase?:string;reason?:string};wan?:FlightWAN[];vpn?:{active?:boolean;verified?:boolean};reserve?:{count?:number;distinct_sim_count?:number}}}
export interface Recording {id:string;state:string;started_utc:number;updated_utc?:number;trigger_codes?:string[];samples:number|FlightSample[];truncated?:boolean;cause?:string}
export interface EvidenceData {report?:Report|null;operation_id?:string;state?:string;result?:Report;cursor?:string;events?:VendorEvent[];entries?:VendorEvent[];operations?:VendorOperation[];recordings?:Recording[];id?:string;samples?:FlightSample[];started_utc?:number;updated_utc?:number;trigger_codes?:string[];truncated?:boolean;cause?:string;targets?:{id:string;label?:string}[];captured_snapshot?:{generated_utc?:number};current_snapshot?:{generated_utc?:number};operation?:VendorOperation}
export interface ClientDetails {vpn:{selected:boolean|null;active:boolean|null;verified:boolean|null;sim:string;server:string;watch_state:string;watch_age:number|null;proof_age:number|null;last_success_age:number|null};reserve:{available:boolean|null;running:boolean|null;count:number|null;target:number|null;distinct_sims:number|null;age:number|null;ttl:number|null;phase:string;pairs:{sim:string;server:string;transport:string;age:number|null}[]};pending:boolean|null;fallback:boolean|null;fallback_reason:string;recovery_age:number|null;last_attempt_current:boolean|null}
const errors:Record<string,string>={result_expired:'Этот отчёт уже удалён роутером. Обновите список.',router_conflict:'Роутер перезапущен или журнал изменился. Обновите список.',access_rejected:'У ключа нет доступа к этому отчёту.',unsupported_response:'Формат отчёта не поддерживается.',expired:'Время ожидания истекло. Повторите чтение.',router_unavailable:'Связь с роутером потеряна.'};
export const evidenceError=(code?:string)=>errors[code??'']??'Не удалось получить отчёт. Обновите состояние и повторите чтение.';
export function decodeChunk(c:EvidenceChunk,q:EvidenceQuery,device:string,boot:string):Uint8Array {
if(c.device_id!==device||c.boot_id!==boot||c.resource!==q.resource||c.id!==q.id||c.offset!==q.offset||!Number.isInteger(c.total)||c.total<=0||c.total>2097152||!/^[a-f0-9]{64}$/.test(c.transfer)||(q.transfer&&c.transfer!==q.transfer))throw Error(evidenceError('unsupported_response'));
const bytes=Uint8Array.from(atob(c.data),c=>c.charCodeAt(0));
if(bytes.length!==Math.min(32768,c.total-c.offset)||bytes.length<=0)throw Error(evidenceError('unsupported_response'));
return bytes;
}
export async function readEvidence(transport:RouterTransport,value:RouterSnapshot,device:RouterDevice,resource:EvidenceResource,id:string,after:string,signal:AbortSignal,progress:(fraction:number)=>void):Promise<EvidenceDocument> {
if(!transport.inspect||!value.runtime_id||!device.client_api||value.read_version!==1)throw Error('Обновите версию борта для чтения отчётов.');
const boot=device.client_api.boot_id,q:EvidenceQuery={resource,id,after,transfer:'',offset:0};let output:Uint8Array|null=null,stamp=0;
do {
signal.throwIfAborted();const operation_id='op_'+crypto.randomUUID().replaceAll('-','');
let receipt:RouterReceipt=await transport.inspect({operation_id,runtime_id:value.runtime_id,device_id:device.id,expected_boot_id:boot,deadline:Math.floor(Date.now()/1000)+85,action:'inspect',query:{...q}});
const end=Date.now()+90000;
while(receipt.state==='queued'||receipt.state==='applying'){
signal.throwIfAborted();if(Date.now()>end)throw Error(evidenceError('expired'));
await new Promise(resolve=>setTimeout(resolve,1000));signal.throwIfAborted();receipt=await transport.operation(operation_id);
}
signal.throwIfAborted();if(receipt.state!=='complete'||!receipt.evidence)throw Error(evidenceError(receipt.error));
const c=receipt.evidence;if(c.operation_id!==operation_id)throw Error(evidenceError('unsupported_response'));
const bytes=decodeChunk(c,q,device.id,boot);
if(output&&(output.length!==c.total||stamp!==c.at))throw Error(evidenceError('unsupported_response'));
if(!output){output=new Uint8Array(c.total);stamp=c.at}output.set(bytes,q.offset);q.offset+=bytes.length;q.transfer=c.transfer;progress(q.offset/c.total);
}while(q.offset<output.length);
if(globalThis.crypto?.subtle){const digest=await crypto.subtle.digest('SHA-256',output as Uint8Array<ArrayBuffer>);const hash=Array.from(new Uint8Array(digest),b=>b.toString(16).padStart(2,'0')).join('');if(hash!==q.transfer)throw Error(evidenceError('unsupported_response'));}
const doc=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(output)) as EvidenceDocument;
if(doc.schema!=='missioncore.router-evidence/v1'||doc.resource!==resource||!doc.data||typeof doc.data!=='object')throw Error(evidenceError('unsupported_response'));return doc;
}
export function downloadEvidence(value:unknown,name:string){const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
export function vendorTime(at:number|undefined){return at!=null&&at>0?new Date(at*1000).toLocaleString('ru-RU'):'Время не указано';}
export const checkState=(state:string)=>({ok:'В порядке',worked:'В порядке',error:'Ошибка',fail:'Ошибка',warn:'Требует внимания',unknown:'Не подтверждено',na:'Не проверялось',skip:'Не проверялось'} as Record<string,string>)[state]??'Нет результата';
+34
View File
@@ -0,0 +1,34 @@
import {modeLabel,simLabel,type RouterDevice} from './contracts';
const knownMode=(mode:string|undefined)=>['direct','aggregation','proxy','vpn','whitelist','auto','off'].includes(mode??'');
const canonicalMode=(mode:string|undefined)=>mode==='proxy'?'aggregation':mode;
// Policy is operator intent. The current route is an observation: online SIMs
// and their traffic never establish participation in aggregation or selection.
export function routerMode(device:RouterDevice,ready:boolean){
const configuredMode=device.selected_mode||device.client_api?.policy?.mode||device.persisted_mode;
const configured=modeLabel(configuredMode);
const details=device.client_api?.details;
const activeMode=ready&&knownMode(device.active_mode)?device.active_mode:'';
const slots=device.active_slots??[];
const legacySlot=/^wan[1-3]$/.test(device.active_wan)?Number(device.active_wan.slice(-1)):null;
const candidate=device.client_api?(slots.length===1?slots[0]:null):(slots.length===1?slots[0]:legacySlot);
const activeSlot=activeMode==='direct'&&candidate!=null&&[1,2,3].includes(candidate)?candidate:null;
const channel=activeSlot==null?'SIM не определена':simLabel(device,activeSlot);
const current=!ready?'Нет свежих данных':activeMode==='direct'?`Прямой выход · ${channel}`:activeMode?modeLabel(activeMode):'Текущий режим не определён';
const pending=ready&&details?.pending===true;
const fallback=ready&&details?.fallback===true;
// whitelist/auto are strategies whose active transport may legitimately differ.
const mismatch=!!activeMode&&['direct','vpn','aggregation','proxy'].includes(configuredMode)&&canonicalMode(configuredMode)!==canonicalMode(activeMode);
let message='';
if(!ready)message='Текущий путь не подтверждён. Показаны последние полученные настройки.';
else if(pending)message=fallback?'Роутер применяет настройки; пока используется резервный путь.':'Роутер применяет настройки. Текущий путь показан отдельно.';
else if(!activeMode)message='Роутер не сообщил фактический режим. Заданные настройки не подтверждают его работу.';
else if(fallback){
const prefix=canonicalMode(configuredMode)==='aggregation'&&canonicalMode(activeMode)!=='aggregation'?'Агрегация сейчас не используется. ':'';
message=prefix+'По данным роутера включён резервный путь.';
const preferred=device.client_api?.policy?.preferred_sim;
if(configuredMode==='direct'&&preferred&&/^M[1-3]$/.test(preferred))message+=` Предпочтительная SIM — ${simLabel(device,Number(preferred.slice(1)))}.`;
}else if(mismatch)message='Заданный режим отличается от фактического. Причина не подтверждена.';
return {configured,current,activeMode,activeSlot,pending,fallback,mismatch,message};
}
+54 -8
View File
@@ -27,13 +27,59 @@ export function collectTraffic(previous:TrafficHistory,key:string,device:RouterD
}
return {key,day,points};
}
// Qualitative RSRP bands, not a percentage of connection quality or throughput.
export const signalBands=[
{label:'Слабый',range:'Ниже −100 dBm',min:-120,max:-100},
{label:'Средний',range:'От −100 до −90 dBm',min:-100,max:-90},
{label:'Хороший',range:'От −90 до −80 dBm',min:-90,max:-80},
{label:'Отличный',range:'−80 dBm и выше',min:-80,max:-60},
] as const;
export function signalLevel(rsrp:number|null|undefined):number|null {
if(rsrp==null||!Number.isFinite(rsrp))return null;
return rsrp>=-80?3:rsrp>=-90?2:rsrp>=-100?1:0;
}
export function trafficCeiling(points:TrafficPoint[]):number {
const peak=Math.max(1,...points.flatMap(p=>[finiteRate(p.down)??0,finiteRate(p.up)??0]));
const power=10**Math.floor(Math.log10(peak)),step=peak/power;
return (step<=1?1:step<=2?2:step<=5?5:10)*power;
}
export interface ChartPoint {x:number;y:number}
export function trafficSegments(points:TrafficPoint[],field:'down'|'up',start:number,end:number,max:number):ChartPoint[][] {
const segments:ChartPoint[][]=[];let segment:ChartPoint[]=[],last:number|null=null;
for(const p of points){
const value=finiteRate(p[field]);
if(value==null||!Number.isFinite(p.at)||p.at<start||p.at>end){segment=[];last=null;continue;}
if(last==null||p.at-last>30||p.at<=last){segment=[];segments.push(segment);}
segment.push({x:2+316*(p.at-start)/Math.max(1,end-start),y:78-70*Math.min(value/Math.max(1,max),1)});
last=p.at;
}
return segments;
}
// Shape-preserving cubic Hermite. Every sample is retained; local extrema and
// gaps are preserved. Control points remain inside each measured interval.
export function smoothTrafficSegment(points:ChartPoint[]):string {
if(!points.length)return '';
const f=(n:number)=>n.toFixed(2),path=[`M${f(points[0].x)},${f(points[0].y)}`];
if(points.length===1)return path[0];
const slopes=points.slice(1).map((p,i)=>(p.y-points[i].y)/(p.x-points[i].x));
const tangents=points.map((_,i)=>i===0?slopes[0]:i===points.length-1?slopes.at(-1)!:
slopes[i-1]*slopes[i]<=0?0:2*slopes[i-1]*slopes[i]/(slopes[i-1]+slopes[i]));
slopes.forEach((s,i)=>{
if(s===0){tangents[i]=0;tangents[i+1]=0;return;}
const a=tangents[i]/s,b=tangents[i+1]/s,scale=Math.hypot(a,b);
if(scale>3){tangents[i]=3*a*s/scale;tangents[i+1]=3*b*s/scale;}
});
points.slice(1).forEach((p,i)=>{
const previous=points[i],dx=(p.x-previous.x)/3;
path.push(`C${f(previous.x+dx)},${f(previous.y+dx*tangents[i])} ${f(p.x-dx)},${f(p.y-dx*tangents[i+1])} ${f(p.x)},${f(p.y)}`);
});
return path.join(' ');
}
export function trafficPath(points:TrafficPoint[],field:'down'|'up',start:number,end:number,max:number):string {
let last:number|null=null;
return points.map(p=>{
const value=p[field];
if(value==null||!Number.isFinite(value)||value<0||p.at<start||p.at>end){last=null;return '';}
const x=2+316*(p.at-start)/Math.max(1,end-start),y=78-74*value/Math.max(1,max);
const command=last==null||p.at-last>30?'M':'L';last=p.at;
return `${command}${x.toFixed(2)},${y.toFixed(2)}`;
}).join(' ');
return trafficSegments(points,field,start,end,max).map(smoothTrafficSegment).join(' ');
}
export function trafficArea(points:TrafficPoint[],field:'down'|'up',start:number,end:number,max:number):string {
return trafficSegments(points,field,start,end,max).filter(s=>s.length>1).map(s=>
`${smoothTrafficSegment(s)} L${s.at(-1)!.x.toFixed(2)},78 L${s[0].x.toFixed(2)},78 Z`).join(' ');
}
+23
View File
@@ -0,0 +1,23 @@
import type {RouterDevice} from './contracts';
import {smoothTrafficSegment,type ChartPoint} from './overview';
export interface RadioSample {at:number;slot:number;rsrp:number|null;rsrq:number|null;sinr:number|null;band:string;cell:string}
export interface RadioHistory {key:string;day:number;samples:RadioSample[]}
export function collectRadio(previous:RadioHistory,key:string,device:RouterDevice,ready:boolean,now:number):RadioHistory {
const day=Math.floor(now/86400),samples=(previous.key===key&&previous.day===day?previous.samples:[]).filter(s=>s.at>=now-300&&s.at<=now+30);
if(ready&&device.observed_at>=now-40&&device.observed_at<=now+30)for(const m of device.modems){
const age=m.radio_age_seconds;if(device.client_api&&(age==null||age>40||age<0))continue;
const at=device.observed_at-(age??0),last=samples.filter(s=>s.slot===m.slot).at(-1);
if(at<now-300||last&&at<=last.at+1)continue;
samples.push({at,slot:m.slot,rsrp:m.rsrp,rsrq:m.rsrq,sinr:m.sinr,band:m.band,cell:m.cell_id});
}
return {key,day,samples:samples.slice(-270)};
}
export const radioMetrics={rsrp:{label:'Уровень · RSRP',unit:'dBm',min:-120,max:-60},rsrq:{label:'Качество · RSRQ',unit:'dB',min:-20,max:0},sinr:{label:'Сигнал / помехи · SINR',unit:'dB',min:-10,max:30}};
export function radioSegments(samples:RadioSample[],field:keyof typeof radioMetrics,end:number):ChartPoint[][] {
const metric=radioMetrics[field],segments:ChartPoint[][]=[];let part:ChartPoint[]=[],last:RadioSample|undefined;
for(const s of samples){const v=s[field];if(v==null||!Number.isFinite(v)||last&&(s.at-last.at>40||s.band!==last.band||s.cell!==last.cell)){if(part.length)segments.push(part);part=[];}
if(v!=null&&Number.isFinite(v)){part.push({x:2+316*Math.max(0,Math.min(1,(s.at-(end-300))/300)),y:78-72*Math.max(0,Math.min(1,(v-metric.min)/(metric.max-metric.min)))});}last=s;
}if(part.length)segments.push(part);return segments;
}
export function radioPath(samples:RadioSample[],field:keyof typeof radioMetrics,end:number){return radioSegments(samples,field,end).map(s=>smoothTrafficSegment(s)).join(' ');}
export function radioChanges(samples:RadioSample[]){return samples.flatMap((s,i)=>{const p=samples[i-1];if(!p||s.at-p.at>40)return [];const changes=[];if(p.band&&s.band&&p.band!==s.band)changes.push(`${p.band} → ${s.band}`);if(p.cell&&s.cell&&p.cell!==s.cell)changes.push(`Сота ${p.cell} → ${s.cell}`);return changes.length?[{at:s.at,text:changes.join(' · ')}]:[];}).slice(-6).reverse();}
+26 -10
View File
@@ -1,11 +1,14 @@
.router-details,.router-form{display:flex;flex-direction:column;gap:var(--nodedc-space-4);min-width:0;}
.router-details{font-size:var(--nodedc-font-size-md);line-height:1.4;}
.router-facts{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,220px),1fr));gap:var(--nodedc-space-4);margin:0;}
.router-facts>div{min-width:0;}
.router-facts dt,.router-note,.router-events time{color:var(--nodedc-text-secondary);font-size:var(--nodedc-font-size-sm);}
.router-facts dd{margin:var(--nodedc-space-1) 0 0;overflow-wrap:anywhere;}
.router-facts dd{font-size:var(--nodedc-font-size-md);line-height:1.4;margin:var(--nodedc-space-1) 0 0;overflow-wrap:anywhere;}
.router-connection-facts dd{font-size:var(--nodedc-font-size-md);line-height:1.4;}
.router-note{margin:0;}
.router-actions{display:flex;justify-content:flex-end;}
.router-events{display:flex;flex-direction:column;gap:var(--nodedc-space-4);margin:0;padding:0;list-style:none;}
.router-events{font-size:var(--nodedc-font-size-md);line-height:1.4;display:flex;flex-direction:column;gap:var(--nodedc-space-4);margin:0;padding:0;list-style:none;}
.router-events strong{font-weight:var(--nodedc-font-weight-medium);}
.router-events li{display:flex;flex-direction:column;gap:var(--nodedc-space-1);overflow-wrap:anywhere;}
.router-overview,.router-channel-content{display:flex;flex-direction:column;gap:var(--nodedc-space-4);min-width:0;}
.router-channel-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:var(--nodedc-space-3);}
@@ -16,9 +19,13 @@
.router-path>svg{color:var(--nodedc-text-secondary);}
.router-path strong,.router-radio-summary{font-size:var(--nodedc-font-size-md);font-weight:var(--nodedc-font-weight-medium);}
.router-metric-line{display:flex;flex-wrap:wrap;justify-content:space-between;gap:var(--nodedc-space-1);font-size:var(--nodedc-font-size-sm);}
.router-signal-scale{width:100%;height:32px;margin-top:var(--nodedc-space-2);}
.router-signal-lit{fill:var(--nodedc-text-primary);}
.router-signal-empty{fill:var(--nodedc-text-secondary);opacity:0.16;}
.router-signal-scale{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin-top:var(--nodedc-space-1);}
.router-signal-zone{width:100%;align-items:center;min-height:36px;cursor:help;}
.router-signal-track{position:relative;display:block;width:100%;height:6px;border-radius:var(--nodedc-radius-circle);background:color-mix(in srgb,var(--nodedc-text-primary) 9%,transparent);}
.router-signal-fill{display:block;height:100%;border-radius:inherit;background:var(--nodedc-text-primary);opacity:.36;transition:width var(--nodedc-duration-slow) var(--nodedc-ease-standard);}
.router-signal-track[data-current="true"] .router-signal-fill{opacity:.8;}
.router-signal-marker{position:absolute;top:50%;width:10px;height:10px;border-radius:var(--nodedc-radius-circle);background:var(--nodedc-text-primary);transform:translate(-50%,-50%);transition:left var(--nodedc-duration-slow) var(--nodedc-ease-standard);}
.router-signal-marker::before{content:"";position:absolute;inset:-6px;border-radius:inherit;background:radial-gradient(circle,color-mix(in srgb,var(--nodedc-text-primary) 16%,transparent),transparent 70%);}
.router-scale-labels{display:flex;justify-content:space-between;gap:var(--nodedc-space-2);font-size:var(--nodedc-font-size-xs);}
.router-channel-rates{display:flex;flex-direction:column;gap:var(--nodedc-space-2);}
.router-channel-rates>div{display:flex;align-items:center;gap:var(--nodedc-space-1);}
@@ -26,14 +33,23 @@
.router-traffic-values{display:flex;gap:var(--nodedc-space-8);flex-wrap:wrap;}
.router-traffic-values>div{display:flex;flex-direction:column;gap:var(--nodedc-space-2);}
.router-traffic-values span{display:flex;align-items:center;gap:var(--nodedc-space-1);font-size:var(--nodedc-font-size-sm);}
.router-traffic-values strong{font-size:var(--nodedc-font-size-lg);font-weight:var(--nodedc-font-weight-medium);font-variant-numeric:tabular-nums;}
.router-traffic-values strong{font-size:var(--nodedc-font-size-md);font-weight:var(--nodedc-font-weight-medium);font-variant-numeric:tabular-nums;}
.router-download{color:var(--nodedc-text-primary);}
.router-upload{color:var(--nodedc-text-secondary);}
.router-traffic-key{display:block;width:18px;height:3px;border-radius:var(--nodedc-radius-circle);background:currentColor;}
.router-upload .router-traffic-key{background:radial-gradient(circle,currentColor 1.2px,transparent 1.4px) left center/6px 3px repeat-x;}
.router-traffic-chart{margin:var(--nodedc-space-4) 0;}
.router-traffic-chart svg{width:100%;height:96px;overflow:visible;}
.router-traffic-chart path{fill:none;stroke-width:1.6;vector-effect:non-scaling-stroke;}
.router-chart-grid{stroke:var(--nodedc-text-secondary);stroke-opacity:0.14;vector-effect:non-scaling-stroke;}
.router-traffic-chart svg{display:block;width:100%;height:132px;overflow:visible;margin-block:var(--nodedc-space-2);}
.router-chart-line{fill:none;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;vector-effect:non-scaling-stroke;}
.router-chart-baseline{stroke:var(--nodedc-text-secondary);stroke-opacity:.12;stroke-dasharray:1 7;stroke-linecap:round;vector-effect:non-scaling-stroke;}
.router-chart-down{stroke:var(--nodedc-text-primary);}
.router-chart-up{stroke:var(--nodedc-text-secondary);stroke-dasharray:4 4;}
.router-chart-up{stroke:var(--nodedc-text-secondary);stroke-dasharray:1 6;stroke-width:1.8;}
.router-chart-point-down{fill:var(--nodedc-text-primary);}.router-chart-point-up{fill:var(--nodedc-text-secondary);}
.router-chart-empty{padding-block:var(--nodedc-space-6);}
@media(prefers-reduced-motion:reduce){.router-signal-fill,.router-signal-marker{transition:none;}}
@media(max-width:640px){.router-channel-grid{grid-template-columns:1fr;}.router-path{gap:var(--nodedc-space-1);}.router-path>div>span{font-size:var(--nodedc-font-size-xs);}}
.router-evidence-actions{display:flex;gap:var(--nodedc-space-2);flex-wrap:wrap;}
.router-report-facts{padding-left:var(--nodedc-space-4);margin-block:var(--nodedc-space-2);font-size:var(--nodedc-font-size-md);line-height:1.6;}
.router-report-facts li{overflow-wrap:anywhere;}
.router-events .nodedc-button{align-self:flex-start;}
@@ -0,0 +1,16 @@
import {useCallback,useEffect,useRef,useState} from 'react';
import type {RouterDevice,RouterSnapshot,RouterTransport} from './contracts';
import {readEvidence,type EvidenceDocument,type EvidenceResource} from './evidence';
export function useRouterEvidence(device:RouterDevice,value:RouterSnapshot,transport:RouterTransport){
const [document,setDocument]=useState<EvidenceDocument|null>(null),[busy,setBusy]=useState(false),[error,setError]=useState(''),[progress,setProgress]=useState(0);
const latest=useRef({device,value});latest.current={device,value};const running=useRef<AbortController|null>(null);
const key=`${value.runtime_id}:${device.id}:${device.client_api?.boot_id}`;
useEffect(()=>{setDocument(null);setError('');setBusy(false);return()=>{running.current?.abort();running.current=null;};},[key]);
const load=useCallback(async(resource:EvidenceResource,id='',after='')=>{
if(running.current)return null;const controller=new AbortController();running.current=controller;setBusy(true);setError('');setProgress(0);
try{const current=latest.current;const doc=await readEvidence(transport,current.value,current.device,resource,id,after,controller.signal,setProgress);if(controller.signal.aborted)return null;setDocument(doc);return doc;}
catch(e){if(!controller.signal.aborted)setError(e instanceof Error?e.message:'Не удалось прочитать отчёт.');return null;}
finally{if(!controller.signal.aborted){running.current=null;setBusy(false);}}
},[key,transport]);
return {document,busy,error,progress,load};
}
@@ -0,0 +1,30 @@
import {useEffect,useRef,useState} from 'react';
import type {RouterAccess,RouterSnapshot,RouterTransport} from './contracts';
const errors:Record<string,string>={access_rejected:'Роутер отклонил доступ. Проверьте логин и пароль или ключ API.',router_certificate_rejected:'Сертификат не соответствует этому роутеру.',router_unavailable:'Роутер недоступен по указанному адресу.',expired:'Запрос устарел. Повторите после обновления состояния.',unsupported_response:'Ответ роутера не поддерживается.',storage_error:'Не удалось сохранить настройки на борту.'};
export function useRouterRequest(value:RouterSnapshot,transport:RouterTransport){
const [pending,setPending]=useState(''),[sending,setSending]=useState(false),[message,setMessage]=useState('');
const active=useRef(true);useEffect(()=>{active.current=true;return()=>{active.current=false;};},[]);
useEffect(()=>{
if(!pending)return;
let stopped=false,timer:ReturnType<typeof setTimeout>;const end=Date.now()+95000;
async function poll(){
try{const result=await transport.operation(pending);if(stopped)return;
if(result.state!=='queued'&&result.state!=='applying'){
setPending('');setMessage(result.state==='complete'?'Сохранено на борту.':errors[result.error??'']??'Результат не подтверждён. Обновите состояние перед повтором.');return;
}
}catch{/* Read receipt; never repeat an ambiguous write. */}
if(stopped)return;
if(Date.now()>=end){setPending('');setMessage('Результат не подтверждён. Обновите состояние перед повтором.');return;}
timer=setTimeout(()=>void poll(),2000);
}
void poll();return()=>{stopped=true;clearTimeout(timer);};
},[pending,transport]);
async function send(fields:Omit<RouterAccess,'operation_id'|'runtime_id'|'deadline'>){
if(!value.runtime_id)return;
const id='op_'+crypto.randomUUID().replaceAll('-','');setSending(true);setMessage('');
try{await transport.authorize({...fields,operation_id:id,runtime_id:value.runtime_id,deadline:Math.floor(Date.now()/1000)+85});}
catch{if(active.current)setMessage('Проверяем результат отправки.');}
finally{if(active.current){setSending(false);setPending(id);}}
}
return {send,busy:sending||!!pending,message};
}
+3 -3
View File
@@ -4,12 +4,12 @@ import type {RouterSnapshot,RouterTransport} from './contracts';
export function useRouters(transport:RouterTransport){
const [value,setValue]=useState<RouterSnapshot|null>(null),[error,setError]=useState('');
useEffect(()=>{
let active=true;let timer:ReturnType<typeof setTimeout>;
let active=true;let cadence=3000;let timer:ReturnType<typeof setTimeout>;
setValue(null);setError('');
async function poll(){
try{const next=await transport.read();if(active){setValue(next);setError('');}}
try{const next=await transport.read();if(active){setValue(next);setError('');cadence=next.results.some(r=>r.action==='speedtest'&&(r.state==='queued'||r.state==='applying'))?1000:3000;}}
catch{if(active){setValue(previous=>previous?{...previous,fresh:false}:previous);setError('Не удалось обновить сведения о роутере.');}}
finally{if(active)timer=setTimeout(()=>void poll(),3000);}
finally{if(active)timer=setTimeout(()=>void poll(),cadence);}
}
void poll();return()=>{active=false;clearTimeout(timer);};
},[transport]);
+2 -2
View File
@@ -1,5 +1,5 @@
import {useEffect,useSyncExternalStore,type ReactNode} from 'react';
import {Button,Icon,Inspector,LoadingRegion} from '@nodedc/ui-react';
import { Description,Button,Icon,Inspector,LoadingRegion} from '@nodedc/ui-react';
import type {BoardLayoutStore} from './boardLayout';
export interface BoardSectionsProps {
@@ -11,7 +11,7 @@ export function BoardSections({layout,computer,description,settings,devices}:Boa
const state=useSyncExternalStore(layout.subscribe,layout.getSnapshot);
useEffect(()=>{void layout.load();},[layout]);
return <div className="sensor-content">
{state.error&&<div role="alert"><p>{state.error}</p><Button onClick={()=>void layout.load()}>Повторить</Button></div>}
{state.error&&<div role="alert"><Description>{state.error}</Description><Button onClick={()=>void layout.load()}>Повторить</Button></div>}
<LoadingRegion loading={!state.ready&&!state.error} label="Загрузка раскладки аппарата">
<Inspector variant="panel" openSections={state.value.open_sections} onOpenSectionsChange={layout.change} sections={[
{id:'computer',label:'Бортовой компьютер',description,icon:<Icon name="apps"/>,disabled:!state.ready,content:computer},
+3 -3
View File
@@ -1,5 +1,5 @@
import {useEffect,useRef,useState,type RefObject} from 'react';
import {LoadingRegion,Icon,IconButton,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import { Description,LoadingRegion,Icon,IconButton,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import type {Sensor,SensorTransport} from './contracts';
import {PointViewport} from './PointViewport';
import {useSensorPreview} from './useSensorPreview';
@@ -19,13 +19,13 @@ export function LiveViewportSurface({device,layer,title,note,inactiveMessage,ena
const state=failed?'Нет свежих данных':pending?'Подключение просмотра':preview.state;
useEffect(()=>{const escape=(e:KeyboardEvent)=>{if(e.key==='Escape')setExpanded(false);};document.addEventListener('keydown',escape);return()=>document.removeEventListener('keydown',escape);},[]);
return <div className={expanded?'sensor-viewer sensor-viewer-expanded':'sensor-viewer'}><SettingsCard title={title??(layer==='points'?'Облако точек':layer==='motion'?'Движение':({color:'RGB',depth:'Глубина',infrared1:'ИК · 1',infrared2:'ИК · 2'}[layer]??layer))} actions={<div className="nodedc-viewport-controls sensor-actions"><StatusBadge tone={active&&live?'success':'neutral'}>{state}</StatusBadge><IconButton label={expanded?'Восстановить размер просмотра':'Развернуть просмотр'} onClick={()=>setExpanded(!expanded)}><Icon name={expanded?'minimize':'expand'}/></IconButton></div>}>
{!active&&!pending&&!failed&&<p>{inactiveMessage??'Нажмите «Начать просмотр» или «Начать запись» для запуска камеры.'}</p>}
{!active&&!pending&&!failed&&<Description>{inactiveMessage??'Нажмите «Начать просмотр» или «Начать запись» для запуска камеры.'}</Description>}
<LoadingRegion loading={!failed&&(pending||(active&&(state==='Подключение просмотра'||state==='Ожидание изображения')))} label={state}>
<div hidden={!active}>
{layer==='points'?<PointViewport points={telemetry.points??[]}/>:layer==='motion'?<dl className="sensor-facts">{Object.entries(telemetry.motion??{}).map(([kind,v])=><div key={kind}><dt>{kind==='accel'?'Ускорение · м/с²':'Угловая скорость · рад/с'}</dt><dd>X {v.x.toFixed(3)} · Y {v.y.toFixed(3)} · Z {v.z.toFixed(3)}</dd></div>)}</dl>:<video ref={video} className="sensor-media" autoPlay muted playsInline/>}
</div>
</LoadingRegion>
{failed&&<p role="status">Нет свежих данных</p>}
{failed&&<Description role="status">Нет свежих данных</Description>}
{active&&<p className="sensor-note">{note??(layer==='points'?'Предпросмотр до 2 000 точек · координаты камеры · метры':layer==='depth'?'Цветное представление глубины. Исходная глубина записывается без видеосжатия.':'Предпросмотр камеры. Исходная запись хранится на БК.')}</p>}
</SettingsCard></div>;
}
+8 -8
View File
@@ -1,6 +1,6 @@
import {SensorDetailBack} from './SensorDetailBack';
import {useEffect,useState} from 'react';
import {Button,Icon,IconButton,Select,SettingsCard,TextField} from '@nodedc/ui-react';
import { Description,Button,Icon,IconButton,Select,SettingsCard,TextField} from '@nodedc/ui-react';
import {perform,type Sensor,type SensorTransport} from './contracts';
import {LiveViewport} from './LiveViewport';
export function SensorDetail({device,transport,back,navigationTarget,refresh,failure,enabled=true}:{enabled?:boolean;device:Sensor;transport:SensorTransport;back:()=>void;navigationTarget?:HTMLElement|null;refresh:()=>Promise<void>;failure:(e:unknown)=>void}){
@@ -15,17 +15,17 @@ export function SensorDetail({device,transport,back,navigationTarget,refresh,fai
const currentOption=detail?.options?.find(v=>v.id===option);const active=device.snapshot.acquisition==='streaming'||device.snapshot.acquisition==='starting'||device.snapshot.acquisition==='stopping';
return <div className="sensor-content"><SensorDetailBack back={back} target={navigationTarget}/>
<SettingsCard title={device.name} description={`${device.model} · USB ${device.usb}${device.firmware?' · '+device.firmware:''}`}>
{!device.online&&!device.snapshot.message&&<p>Камера отключена от БК.</p>}
{device.snapshot.message&&<p>{device.snapshot.message}</p>}
{!device.online&&!device.snapshot.message&&<Description>Камера отключена от БК.</Description>}
{device.snapshot.message&&<Description>{device.snapshot.message}</Description>}
<div className="sensor-actions"><Button loading={pendingAction==='preview.start'} disabled={!enabled||pending||!detail||active||!device.online} onClick={()=>void act('start',{profiles:Object.values(selected).filter(Boolean),record:false})}>Начать просмотр</Button><Button loading={pendingAction==='record.start'} disabled={!enabled||pending||!detail||active||!device.online} onClick={()=>void act('start',{profiles:Object.values(selected).filter(Boolean),record:true})}>Начать запись</Button><Button disabled={!enabled||pending||(!active&&device.snapshot.acquisition!=='failed')} loading={pendingAction==='stop'} onClick={()=>void act('stop')}>{device.playback_id?'Закрыть запись':'Остановить захват'}</Button></div>
{device.playback_id&&<p>Просмотр исходной записи · повтор. Камера для него не запускается.</p>}
{device.snapshot.acquisition==='stopping'&&<p>Сохранение исходной записи и проверка целостности.</p>}
{device.recording&&device.snapshot.acquisition!=='stopping'&&<p>Идёт исходная запись на БК. Она продолжится после закрытия окна.</p>}
{device.playback_id&&<Description>Просмотр исходной записи · повтор. Камера для него не запускается.</Description>}
{device.snapshot.acquisition==='stopping'&&<Description>Сохранение исходной записи и проверка целостности.</Description>}
{device.recording&&device.snapshot.acquisition!=='stopping'&&<Description>Идёт исходная запись на БК. Она продолжится после закрытия окна.</Description>}
</SettingsCard>
{detail&&<><Select label="Слой камеры" value={layer} options={available.map(value=>({value,label:videoNames[value]??value}))} onChange={setLayer}/><LiveViewport enabled={enabled&&device.online} device={device} layer={layer} transport={transport} failure={failure}/>
<SettingsCard title="Профили потоков" description="Применяются при следующем запуске захвата."><div className="sensor-fields">{groups.map(group=><Select key={group} label={group} value={selected[group]??''} options={[{value:'',label:'Выключен'},...(detail.profiles??[]).filter(p=>p.stream+':'+p.index===group&&['rgb8','bgr8','z16','y8','motion_xyz32f'].includes(p.format)).map(p=>({value:p.id,label:`${p.width?p.width+' × '+p.height+' · ':''}${p.fps} Гц · ${p.format}`}))]} onChange={value=>setSelected(v=>({...v,[group]:value}))} disabled={!enabled||pending||active}/>)}</div></SettingsCard>
<SettingsCard title="Параметры камеры"><div className="sensor-fields"><Select searchable label="Параметр" value={option} options={(detail.options??[]).map(v=>({value:v.id,label:v.label,description:v.sensor}))} onChange={id=>{setOption(id);setOptionValue(String(detail.options?.find(v=>v.id===id)?.value??''));}}/>{currentOption&&<><TextField type="number" label={`${currentOption.min} … ${currentOption.max}${currentOption.read_only?' · только чтение':''}`} min={currentOption.min} max={currentOption.max} step={currentOption.step||'any'} value={optionValue} onChange={e=>setOptionValue(e.target.value)} disabled={!enabled||pending||currentOption.read_only||!!device.playback_id}/><Button disabled={!enabled||pending||currentOption.read_only||!!device.playback_id||optionValue===''} loading={pendingAction==='option'} onClick={()=>void act('option',{id:option,value:Number(optionValue)})}>Применить параметр</Button></>}</div></SettingsCard>
<SettingsCard title="Исходные записи">{detail.recordings?.length?detail.recordings.map(item=><div className="sensor-record" key={item.id}><span>{new Date(item.started_at).toLocaleString('ru-RU')}</span><span>{item.state==='complete'?'Запись завершена':item.state==='recording'?'Идёт запись':item.state==='finalizing'?'Сохранение записи':item.state==='interrupted'?'Запись прервана':'Запись не завершена'}</span><span>{item.bytes?`${(item.bytes/1048576).toFixed(1)} МиБ`:''}</span><IconButton label={`Открыть запись: ${new Date(item.started_at).toLocaleString('ru-RU')}`} disabled={!enabled||pending||active||item.state!=='complete'} loading={pendingAction==='replay:'+item.id} onClick={()=>void act('replay',{recording_id:item.id})}><Icon name="eye"/></IconButton></div>):<p>Записей пока нет.</p>}</SettingsCard></>}
{!detail&&<p>{!enabled||!device.online?'Возможности камеры будут прочитаны после подключения.':device.prepared?'Получение возможностей камеры…':'Подготовьте устройство в списке.'}</p>}
<SettingsCard title="Исходные записи">{detail.recordings?.length?detail.recordings.map(item=><div className="sensor-record" key={item.id}><span>{new Date(item.started_at).toLocaleString('ru-RU')}</span><span>{item.state==='complete'?'Запись завершена':item.state==='recording'?'Идёт запись':item.state==='finalizing'?'Сохранение записи':item.state==='interrupted'?'Запись прервана':'Запись не завершена'}</span><span>{item.bytes?`${(item.bytes/1048576).toFixed(1)} МиБ`:''}</span><IconButton label={`Открыть запись: ${new Date(item.started_at).toLocaleString('ru-RU')}`} disabled={!enabled||pending||active||item.state!=='complete'} loading={pendingAction==='replay:'+item.id} onClick={()=>void act('replay',{recording_id:item.id})}><Icon name="eye"/></IconButton></div>):<Description>Записей пока нет.</Description>}</SettingsCard></>}
{!detail&&<Description>{!enabled||!device.online?'Возможности камеры будут прочитаны после подключения.':device.prepared?'Получение возможностей камеры…':'Подготовьте устройство в списке.'}</Description>}
</div>;
}
+2 -2
View File
@@ -1,5 +1,5 @@
import {useCallback,useEffect,useRef,useState,type ReactNode} from 'react';
import {LoadingRegion,Button,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge,ToastStack,Window} from '@nodedc/ui-react';
import { Description,LoadingRegion,Button,Icon,IconButton,ResourceList,ResourceRow,SettingsCard,StatusBadge,ToastStack,Window} from '@nodedc/ui-react';
import {perform,enrolledDevice,type Sensor,type SensorInventory,type SensorTransport} from './contracts';
import {SensorDetail} from './SensorDetail';
import {SensorGeneralSettings} from './SensorGeneralSettings';
@@ -67,7 +67,7 @@ export function SensorWorkspace({onOpenDetail,sceneSeedKey,transport,enabled=tru
<SensorPreparations inventory={enabled&&fresh?inventory:null}/>
</>;
const boardSettings=contributions.filter(value=>value.BoardSettings&&contributions.filter(other=>other.kind===value.kind).length===1);
const settingsView=<div className="sensor-content">{boardSettings.map(contribution=>{const View=contribution.BoardSettings!;return <View key={contribution.kind} inventory={inventory} transport={transport} enabled={enabled&&fresh} refresh={refresh} failure={failure} openDevice={setSelected}/>;})}{!boardSettings.length&&<p>Для подключённых устройств общие настройки пока недоступны.</p>}</div>;
const settingsView=<div className="sensor-content">{boardSettings.map(contribution=>{const View=contribution.BoardSettings!;return <View key={contribution.kind} inventory={inventory} transport={transport} enabled={enabled&&fresh} refresh={refresh} failure={failure} openDevice={setSelected}/>;})}{!boardSettings.length&&<Description>Для подключённых устройств общие настройки пока недоступны.</Description>}</div>;
const detail=device&&Detail?<Detail sceneSeedKey={sceneSeedKey} key={device.snapshot.context.session_id} enabled={enabled&&fresh} previewEnabled={previewEnabled} device={device} generalSettings={settingsFor(device)} transport={transport} back={()=>setSelected(null)} navigationTarget={detailActionsTarget} refresh={refresh} failure={failure} createRerunHost={createRerunHost} reconnect={transport.enrollment?()=>setAdding(true):undefined}/>:null;
return <div className="sensor-workspace">{device&&!modal?detail??<div className="sensor-content"><SensorDetailBack back={()=>setSelected(null)} target={detailActionsTarget}/><SettingsCard title="Просмотр устройства недоступен" description="Интеграция этого устройства не установлена."/></div>:(renderBoard?renderBoard({settings:settingsView,devices:inventoryView,showingSavedDevices:connected.length>0&&(!enabled||!fresh),refresh,addDevice:()=>setAdding(true),canAddDevice:!!transport.enrollment&&wirelessContributions(contributions).length>0}):board?<BoardSections {...board} settings={settingsView} devices={inventoryView}/>:inventoryView)}
{modal&&detail}
@@ -1,8 +1,8 @@
import {Icon} from '@nodedc/ui-react';
import { Description,Icon} from '@nodedc/ui-react';
export function EmptySpatialStage({settings, title='Визуальный источник не назначен', detail='Область сцены не подставляет демонстрационные точки. Назначьте RRD или Rerun gRPC, чтобы открыть реальные данные.'}: {settings:{showGrid:boolean};title?:string;detail?:string}) {
return <div className="empty-spatial-stage" data-grid={settings.showGrid?'true':undefined}>
<div className="empty-spatial-stage__grid" aria-hidden="true"/>
<div className="spatial-axis" aria-hidden="true"><span data-axis="x">X</span><span data-axis="z">Z</span></div>
<div className="empty-spatial-stage__message"><span className="empty-spatial-stage__icon"><Icon name="globe" size={20}/></span><strong>{title}</strong><p>{detail}</p></div>
<div className="empty-spatial-stage__message"><span className="empty-spatial-stage__icon"><Icon name="globe" size={20}/></span><strong>{title}</strong><Description>{detail}</Description></div>
</div>;
}
+2 -2
View File
@@ -251,13 +251,13 @@
.empty-spatial-stage__message strong {
color: var(--nodedc-text-primary);
font-size: 0.82rem;
font-size: var(--nodedc-font-size-md);
}
.empty-spatial-stage__message p {
margin: 0;
color: var(--nodedc-text-muted);
font-size: 0.67rem;
font-size: var(--nodedc-font-size-sm);
line-height: 1.5;
}