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} 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(null),running=useRef(false),mounted=useRef(true); const [catalog,setCatalog]=useState(null),[selected,setSelected]=useState(null),[installed,setInstalled]=useState(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(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=(action:string,parameters:Record={},timeout=60000)=>perform(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){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');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('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('inspect',{id});if(mounted.current)setSelected(v);}); async function importFile(event:ChangeEvent){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('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('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={})=>run(async()=>{clear();const v=await call(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
Автор распространяет каталог по HTTP. Перед установкой проверьте описание, совместимость и состав выбранного пакета. void importFile(e)}/> {!supported&&Прошивка контроллера {status.identity?.version??'не определена'}. Каталог и импорт доступны; запись расширений поддерживается для VESC 6.00. Обновление каталога не меняет прошивку.} {installed&&{installed.installed?`${installed.installed.name} · ${installed.installed.id.slice(0,12)}`:installed.empty?'Lisp и QML приложения отсутствуют.':'Есть пользовательский код. Его пакет не определён.'}} {pending&&Предыдущее изменение не подтверждено. Проверьте содержимое или восстановите исходную копию.} {pending&&} {selected&&
  • {selected.description&&} {selected.library?Библиотеку используют через import в проекте Lisp. Она не заменяет приложение контроллера. Примеры pkg@ и pkg:: из README работают в редакторе Lisp: вложения берутся из сохранённого каталога.:<> {selected.compatible==null&&} Запись заменит Lisp и QML приложения, включая пустые части пакета. Исходная копия сохраняется. Запуск здесь не выполняется; поведение после перезагрузки определяется прошивкой контроллера. {selected.fits===false&&Код не помещается во flash текущего профиля.} } {selected.imported&&}
    } {selected?.qml_source&&} {preview&& {preview.package?`Запись: ${preview.package.name}.`:'Удаление кода приложения или восстановление пользовательского кода.'} При потере связи автоматического повтора не будет. Проверка результата и восстановление доступны выше. } {message&&{message}} {catalog&& setQuery(e.target.value)}/>