Files
NODEDC_MISSION_CORE/plugins/vesc/frontend/src/VescPackages.tsx
T
DCCONSTRUCTIONS f32c7b400b feat(vesc): extend motor diagnostics, configuration and transport recovery
Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
2026-10-29 09:09:59 +03:00

90 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {useEffect,useRef,useState,type ChangeEvent} from 'react';
import {Button,Checker,Description,ResourceList,ResourceRow,Select,SettingsCard,TextAreaField,TextField} from '@nodedc/ui-react';
import {perform} from '../../../../packages/sensor-ui/src/contracts';
import type {ReadProps} from './useVescRead';
import {vescStatus} from './model';
import {VescQmlPreview} from './VescQmlPreview';
import {bytesBase64} from './editorFiles';
interface Item {id:string;name:string;path:string;library:boolean;imported?:boolean;bytes:number;lisp_bytes:number;qml_bytes:number;description:string;qml_source?:string;compatible?:boolean|null;fits?:boolean}
interface Catalog {sha256:string;items:Item[];source:string}
interface Installed {pending:boolean;recognized:boolean;empty:boolean;installed:{id:string;name:string;path:string}|null}
interface Preview {preview_id:string;package:{id:string;name:string}|null;before:Record<string,{bytes:number}>}
const hash=async(data:Uint8Array)=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new Uint8Array(data)))).map(v=>v.toString(16).padStart(2,'0')).join('');
export function VescPackages(props:ReadProps){
const status=vescStatus(props.device),file=useRef<HTMLInputElement>(null),running=useRef(false),mounted=useRef(true);
const [catalog,setCatalog]=useState<Catalog|null>(null),[selected,setSelected]=useState<Item|null>(null),[installed,setInstalled]=useState<Installed|null>(null);
const [busy,setBusy]=useState(false),[query,setQuery]=useState(''),[category,setCategory]=useState('all'),[message,setMessage]=useState('');
const [library,setLibrary]=useState(false),[compatible,setCompatible]=useState(false),[confirmed,setConfirmed]=useState(false),[preview,setPreview]=useState<Preview|null>(null);
const available=props.enabled&&props.device.online&&props.device.verified,disabled=busy||props.blocked||!available;
const supported=status.identity?.version==='6.00'&&status.identity.hardware_type===0&&status.identity.test_firmware===0;
const pending=installed?.pending||status.package_pending;
const call=<T,>(action:string,parameters:Record<string,unknown>={},timeout=60000)=>perform<T>(props.transport,props.device,'vesc.packages.'+action,parameters,timeout);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
function clear(){setPreview(null);setConfirmed(false);setMessage('');}
async function run(work:()=>Promise<void>){if(running.current||disabled)return;running.current=true;setBusy(true);props.onBusyChange(true);props.failure(null);try{await work();}catch(e){if(mounted.current)props.failure(e);}finally{running.current=false;props.onBusyChange(false);if(mounted.current)setBusy(false);}}
async function list(){const c=await call<Catalog>('catalog');if(mounted.current){setCatalog(c);setSelected(old=>old&&c.items.some(i=>i.id===old.id)?old:null);}}
async function read(){const v=await call<Installed>('status',{},90000);if(mounted.current)setInstalled(v);}
const load=()=>run(async()=>{clear();await list();});
const inspect=(id:string)=>run(async()=>{clear();setCompatible(false);const v=await call<Item>('inspect',{id});if(mounted.current)setSelected(v);});
async function importFile(event:ChangeEvent<HTMLInputElement>){const f=event.target.files?.[0];event.target.value='';if(!f)return;await run(async()=>{
clear();const kind=f.name.toLowerCase().endsWith('.rcc')?'catalog':'package',limit=kind==='catalog'?8*1024*1024:1024*1024;
if(f.size>limit)throw new Error('Файл превышает предел: пакет — 1 МБ, каталог — 8 МБ.');
const data=new Uint8Array(await f.arrayBuffer()),sha256=await hash(data);
const b=await call<{upload_id:string;chunk_bytes:number}>('begin',{kind,name:f.name.replace(/[^A-Za-z0-9_. -]/g,'_').slice(0,128),size:data.length,sha256,library,source:'import'});
for(let at=0;at<data.length;at+=b.chunk_bytes){const chunk=data.slice(at,at+b.chunk_bytes),v=await call<{offset:number}>('chunk',{upload_id:b.upload_id,offset:at,data:bytesBase64(chunk)});if(v.offset!==at+chunk.length)throw new Error('Фрагмент файла не подтверждён.');}
await call('load',{upload_id:b.upload_id});await list();if(mounted.current)setMessage('Импорт проверен и добавлен в каталог. Контроллер не изменён.');
});}
const download=()=>run(async()=>{if(!selected)return;const pieces:Uint8Array[]=[];let at=0;
while(at<selected.bytes){const v=await call<{id:string;bytes:number;offset:number;data:string}>('download',{id:selected.id,offset:at});const part=Uint8Array.from(atob(v.data),c=>c.charCodeAt(0));if(v.id!==selected.id||v.offset!==at||v.bytes!==selected.bytes||!part.length||at+part.length>selected.bytes)throw new Error('Получен неполный пакет.');pieces.push(part);at+=part.length;}
const data=new Uint8Array(at);at=0;for(const p of pieces){data.set(p,at);at+=p.length;}if(await hash(data)!==selected.id)throw new Error('Контрольная сумма пакета не совпала.');
const url=URL.createObjectURL(new Blob([data],{type:'application/octet-stream'})),a=document.createElement('a');a.href=url;a.download=selected.path.split('/').at(-1)||'extension.vescpkg';a.click();setTimeout(()=>URL.revokeObjectURL(url),0);
});
const prepare=(action:string,p:Record<string,unknown>={})=>run(async()=>{clear();const v=await call<Preview>(action,p,90000);if(mounted.current)setPreview(v);});
const apply=()=>run(async()=>{if(!preview||!confirmed)return;const id=preview.preview_id;clear();const v=await call<{verified:boolean;message?:string}>('apply',{preview_id:id,confirmed:true,inputs_isolated:true},350000);if(mounted.current){setMessage(v.message??(v.verified?'Расширение записано и проверено. Lisp не запускался.':'Итог записи неизвестен.'));setInstalled(old=>old?{...old,pending:!v.verified}:null);}await props.refresh();if(v.verified)await read();});
const items=catalog?.items.filter(i=>(category==='all'||(category==='libraries')===i.library)&&`${i.name} ${i.path}`.toLowerCase().includes(query.toLowerCase()))??[];
const updating=Boolean(installed?.installed&&selected&&installed.installed.path===selected.path&&installed.installed.id!==selected.id);
return <div className="sensor-content">
<SettingsCard title="Расширения VESC" description="Готовые приложения и библиотеки Lisp/QML из каталога VESC Tool. Загрузка пакета в каталог, запись на контроллер и запуск Lisp выполняются отдельно.">
<Button loading={busy} disabled={disabled} onClick={()=>void load()}>Открыть сохранённый каталог</Button>
<Button disabled={disabled} onClick={()=>void run(async()=>{clear();await call('refresh',{},180000);await list();if(mounted.current)setMessage('Каталог автора обновлён. Установленное расширение не изменено.');})}>Обновить каталог автора</Button>
<Description>Автор распространяет каталог по HTTP. Перед установкой проверьте описание, совместимость и состав выбранного пакета.</Description>
<input hidden type="file" ref={file} accept=".vescpkg,.rcc" onChange={e=>void importFile(e)}/>
<Button disabled={disabled} onClick={()=>file.current?.click()}>Импорт пакета или каталога</Button>
<Checker label="Импортировать отдельный пакет как библиотеку" checked={library} onChange={setLibrary} disabled={disabled}/>
{!supported&&<Description role="status">Прошивка контроллера {status.identity?.version??'не определена'}. Каталог и импорт доступны; запись расширений поддерживается для VESC 6.00. Обновление каталога не меняет прошивку.</Description>}
</SettingsCard>
<SettingsCard title="На контроллере" description="Состояние определяется чтением обеих частей: Lisp и QML. После ручного изменения кода старое название пакета не считается подтверждённым.">
<Button disabled={disabled||!supported} onClick={()=>void run(async()=>{clear();await read();})}>Прочитать установленное расширение</Button>
{installed&&<Description>{installed.installed?`${installed.installed.name} · ${installed.installed.id.slice(0,12)}`:installed.empty?'Lisp и QML приложения отсутствуют.':'Есть пользовательский код. Его пакет не определён.'}</Description>}
{pending&&<Description role="status">Предыдущее изменение не подтверждено. Проверьте содержимое или восстановите исходную копию.</Description>}
{pending&&<Button disabled={disabled||!supported} onClick={()=>void run(async()=>{clear();const v=await call<{verified:boolean}>('reconcile',{},90000);await props.refresh();await read();if(mounted.current)setMessage(v.verified?'Содержимое подтверждено.':'Содержимое отличается от исходного и ожидаемого. Доступно восстановление.');})}>Проверить запись</Button>}
<Button disabled={disabled||!supported} onClick={()=>void prepare('restore')}>Подготовить восстановление копии</Button>
<Button disabled={disabled||!supported||pending} onClick={()=>void prepare('remove_prepare')}>Подготовить удаление расширения</Button>
</SettingsCard>
{selected&&<SettingsCard title={selected.name} description={`${selected.library?'Библиотека':'Приложение'} · ревизия ${selected.id.slice(0,12)}`}>
<ResourceList aria-label="Состав расширения"><li><ResourceRow title="Lisp с вложениями" description={`${selected.lisp_bytes} байт`}/></li><li><ResourceRow title="QML-интерфейс" description={`${selected.qml_bytes} байт`}/></li><li><ResourceRow title="Совместимость по описанию автора" description={selected.compatible===true?'Тип контроллера разрешён автором':selected.compatible===false?'Этот контроллер исключён автором':'Условия не определены или не удалось проверить'}/></li></ResourceList>
{selected.description&&<TextAreaField label="README автора" value={selected.description} readOnly rows={12}/>}
{selected.library?<Description>Библиотеку используют через import в проекте Lisp. Она не заменяет приложение контроллера. Примеры pkg@ и pkg:: из README работают в редакторе Lisp: вложения берутся из сохранённого каталога.</Description>:<>
{selected.compatible==null&&<Checker label="Совместимость проверена по документации автора" checked={compatible} onChange={setCompatible} disabled={disabled}/>}
<Description>Запись заменит Lisp и QML приложения, включая пустые части пакета. Исходная копия сохраняется. Запуск здесь не выполняется; поведение после перезагрузки определяется прошивкой контроллера.</Description>
<Button disabled={disabled||!supported||pending||selected.compatible===false||selected.fits===false||(selected.compatible==null&&!compatible)} onClick={()=>void prepare('prepare',{id:selected.id,compatibility_confirmed:compatible})}>{updating?'Подготовить обновление':'Подготовить установку'}</Button>
{selected.fits===false&&<Description>Код не помещается во flash текущего профиля.</Description>}
</>}
<Button disabled={disabled} onClick={()=>void download()}>Скачать .vescpkg</Button>
{selected.imported&&<Button disabled={disabled} onClick={()=>void run(async()=>{await call('forget',{id:selected.id});if(mounted.current)setSelected(null);await list();})}>Убрать импорт из каталога</Button>}
</SettingsCard>}
{selected?.qml_source&&<VescQmlPreview {...props} source={selected.qml_source}/>}
{preview&&<SettingsCard title="Подтверждение записи" description="Операция привязана к UUID, прошивке, текущему коду и сеансу контроллера; подтверждение действует пять минут.">
<Description>{preview.package?`Запись: ${preview.package.name}.`:'Удаление кода приложения или восстановление пользовательского кода.'} При потере связи автоматического повтора не будет. Проверка результата и восстановление доступны выше.</Description>
<Checker label="Операция подтверждена, внешние входы отключены" checked={confirmed} onChange={setConfirmed} disabled={disabled}/>
<Button variant="primary" disabled={disabled||!confirmed} onClick={()=>void apply()}>Выполнить запись без запуска</Button>
</SettingsCard>}
{message&&<SettingsCard title="Результат"><Description role="status">{message}</Description></SettingsCard>}
{catalog&&<SettingsCard title="Каталог" description={`${catalog.items.length} пакетов · ревизия ${catalog.sha256.slice(0,12)}`}>
<TextField label="Поиск расширения" value={query} onChange={e=>setQuery(e.target.value)}/><Select label="Тип пакета" value={category} onChange={setCategory} options={[{value:'all',label:'Все'},{value:'applications',label:'Приложения'},{value:'libraries',label:'Библиотеки'}]}/>
<ResourceList aria-label="Расширения VESC">{items.map(item=><li key={item.path+item.id}><ResourceRow title={item.name} description={`${item.library?'Библиотека':'Приложение'} · ${item.id.slice(0,12)}`} actions={<Button disabled={disabled} onClick={()=>void inspect(item.id)}>Открыть</Button>}/></li>)}</ResourceList>
{!items.length&&<Description>Подходящих пакетов нет.</Description>}
</SettingsCard>}
</div>;
}