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:
@@ -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>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user