Files
NODEDC_MISSION_CORE/plugins/vesc/frontend/src/VescCodeTools.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

69 lines
13 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,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,downloadText,validateProject,type CodeProject} from './editorFiles';
interface Preview {preview_id:string;kind?:string;bytes?:number;sha256?:string;erase?:boolean;command?:string;text?:string}
interface Reading {project:CodeProject;bytes:number;sha256:string;pending:boolean;execution_pending:boolean}
export function VescCodeTools(props:ReadProps&{kind:'lisp'|'qml';active?:boolean}){
const {kind}=props,status=vescStatus(props.device),label=kind==='lisp'?'LispBM':'QML';
const [project,setProject]=useState<CodeProject>({kind,source:'',imports:{},fullscreen:false}),[reading,setReading]=useState<Reading|null>(null);
const [preview,setPreview]=useState<Preview|null>(null),[confirmed,setConfirmed]=useState(false),[busy,setBusy]=useState(false),[message,setMessage]=useState('');
const [repl,setRepl]=useState(''),[output,setOutput]=useState(''),[stats,setStats]=useState<Record<string,unknown>|null>(null);
const running=useRef(false),mounted=useRef(true),file=useRef<HTMLInputElement>(null),attachment=useRef<HTMLInputElement>(null);
useEffect(()=>{mounted.current=true;return()=>{mounted.current=false;};},[]);
const supported=status.identity?.version==='6.00'&&status.identity.hardware_type===0&&status.identity.test_firmware===0&&status.engine?.contract?.methods.includes('code_read')===true;
const available=props.enabled&&props.device.online&&props.device.verified&&supported;
const disabled=busy||props.blocked,unavailable=disabled||!available;
const call=<T,>(name:string,p:Record<string,unknown>={},timeout=60000)=>perform<T>(props.transport,props.device,'vesc.code.'+name,p,timeout);
function clear(){setPreview(null);setConfirmed(false);setMessage('');}
async function run(work:()=>Promise<void>){if(running.current||unavailable)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);}}
const read=(hardware=false)=>run(async()=>{clear();const v=await call<Reading>('read',{kind:hardware?'qml_hw':kind});if(mounted.current){setReading(v);setProject(v.project);setMessage(hardware?'Прочитан встроенный QML. Его можно сохранить или использовать как основу приложения.':'Код прочитан. Загрузка и запуск выполняются отдельно.');}});
const prepare=()=>run(async()=>{
clear();const checked=validateProject(project,kind),data=new TextEncoder().encode(JSON.stringify(checked));
const sha256=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',data))).map(v=>v.toString(16).padStart(2,'0')).join('');
const upload=await call<{upload_id:string;chunk_bytes:number}>('begin',{kind,size:data.length,sha256});
for(let at=0;at<data.length;at+=upload.chunk_bytes){const chunk=data.slice(at,at+upload.chunk_bytes),r=await call<{offset:number}>('chunk',{upload_id:upload.upload_id,offset:at,data:bytesBase64(chunk)});if(r.offset!==at+chunk.length)throw new Error('Передача проекта не подтверждена.');}
const p=await call<Preview>('prepare',{upload_id:upload.upload_id});if(mounted.current)setPreview(p);
});
const prepareAction=(name:string,p:Record<string,unknown>)=>run(async()=>{clear();const v=await call<Preview>(name,p);if(mounted.current)setPreview(v);});
const apply=()=>run(async()=>{if(!preview||!confirmed)return;const p=preview;clear();const r=await call<{verified?:boolean;outcome?:string;message?:string;acknowledged?:boolean;command?:string;output?:string}>(p.command?'control_apply':'apply',{preview_id:p.preview_id,confirmed:true,inputs_isolated:true},180000);if(mounted.current){if(r.output)setOutput(r.output);setMessage(r.message??(p.command?(r.acknowledged?'Смена состояния Lisp подтверждена.':'Команда REPL отправлена. Вывод относится только к этому запросу; завершение программы не подтверждается.'):r.verified?'Код записан и проверен. Запуск не выполнялся.':'Итог записи неизвестен.'));if(!p.command)setReading(v=>v?{...v,pending:!r.verified}:null);}await props.refresh();});
const reconcile=()=>run(async()=>{clear();const v=await call<{verified:boolean;outcome:string}>('reconcile',{kind});if(mounted.current){setMessage(v.verified?'Содержимое подтверждено повторным чтением.':'Содержимое отличается от исходного и ожидаемого. Доступно восстановление копии.');setReading(r=>r?{...r,pending:!v.verified}:null);}await props.refresh();});
async function open(event:ChangeEvent<HTMLInputElement>){const f=event.target.files?.[0];event.target.value='';if(!f)return;try{if(f.size>256*1024)throw new Error('Файл превышает 256 КБ.');const text=await f.text();const value=f.name.endsWith('.json')?validateProject(JSON.parse(text),kind):validateProject({kind,source:text,imports:{},fullscreen:false},kind);setProject(value);clear();}catch(e){props.failure(e);}}
async function attach(event:ChangeEvent<HTMLInputElement>){const files=Array.from(event.target.files??[]);event.target.value='';try{const imports={...project.imports};for(const f of files){if(f.size>120*1024)throw new Error('Вложение слишком велико.');imports[f.name]=bytesBase64(new Uint8Array(await f.arrayBuffer()));}setProject(validateProject({...project,imports},kind));clear();}catch(e){props.failure(e);}}
const pending=reading?.pending||status.code_pending;
return <div className="sensor-content">
<SettingsCard title={`${label} · редактор`} description={kind==='lisp'?'Исходный код и вложения LispBM. Запись во flash и запуск программы — отдельные действия.':'Исходный код интерфейса Qt Quick. Доступны чтение и запись QML приложения; встроенный QML читается отдельно.'}>
{!supported&&<Description role="status">На этом контроллере прошивка {status.identity?.version??'не определена'}. Чтение и запись программ в памяти контроллера доступны для профиля VESC 6.00. Здесь можно открыть, отредактировать и сохранить проект.</Description>}
<Button disabled={unavailable} loading={busy} onClick={()=>void read()}>Прочитать {label}</Button>
{kind==='qml'&&<Button disabled={unavailable} onClick={()=>void read(true)}>Прочитать встроенный QML</Button>}
<input hidden ref={file} type="file" accept={kind==='lisp'?'.lisp,.lbm,.json':'.qml,.json'} onChange={e=>void open(e)}/><Button disabled={disabled} onClick={()=>file.current?.click()}>Открыть файл или проект</Button>
<TextAreaField label={`Исходный код ${label}`} value={project.source} rows={18} disabled={disabled} onChange={e=>{setProject(p=>({...p,source:e.target.value}));clear();}}/>
{kind==='qml'&&<Checker label="Открывать QML на весь экран в VESC Tool" checked={project.fullscreen} onChange={fullscreen=>{setProject(p=>({...p,fullscreen}));clear();}} disabled={disabled}/>}
{kind==='lisp'&&<><input ref={attachment} type="file" hidden multiple onChange={e=>void attach(e)}/><Button disabled={disabled} onClick={()=>attachment.current?.click()}>Добавить файлы import</Button><Description>В import укажите имя прикреплённого файла без пути к папке или ссылку pkg@ / pkg:: на библиотеку из сохранённого каталога расширений. Исходный код и вложения вместе — до 120 КБ.</Description>
<ResourceList aria-label="Вложения Lisp">{Object.keys(project.imports).map(name=><li key={name}><ResourceRow title={name} actions={<Button disabled={disabled} onClick={()=>{setProject(p=>({...p,imports:Object.fromEntries(Object.entries(p.imports).filter(([key])=>key!==name))}));clear();}}>Убрать</Button>}/></li>)}</ResourceList></>}
<Button disabled={disabled} onClick={()=>downloadText(`vesc-${kind}.${kind==='lisp'?'lisp':'qml'}`,project.source)}>Скачать исходный код</Button>
<Button disabled={disabled} onClick={()=>{try{downloadText(`vesc-${kind}-project.json`,JSON.stringify(validateProject(project,kind),null,2),'application/json');}catch(e){props.failure(e);}}}>Скачать проект с вложениями</Button>
<Button disabled={unavailable||pending||!project.source.trim()} onClick={()=>void prepare()}>Подготовить запись {label}</Button>
<Button disabled={unavailable||pending} onClick={()=>void prepareAction('erase_prepare',{kind})}>Подготовить удаление {label}</Button>
</SettingsCard>
{kind==='qml'&&<VescQmlPreview {...props} source={project.source} active={props.active}/>}
{pending&&<SettingsCard title="Проверка записи кода" description="Предыдущая запись не подтверждена. Автоматического повторения нет."><Button disabled={unavailable} onClick={()=>void reconcile()}>Проверить запись</Button><Button disabled={unavailable} onClick={()=>void prepareAction('restore',{kind})}>Подготовить восстановление копии</Button></SettingsCard>}
{kind==='lisp'&&<SettingsCard title="LispBM · выполнение" description="Программа и REPL могут управлять выходами, включая мотор. Перед запуском отключите внешние входы и подготовьте безопасный стенд.">
<Button disabled={unavailable||pending} onClick={()=>void prepareAction('control_prepare',{command:'start',text:''})}>Подготовить запуск Lisp</Button><Button disabled={unavailable} onClick={()=>void prepareAction('control_prepare',{command:'stop',text:''})}>Подготовить остановку Lisp</Button>
<TextField label="Выражение REPL" value={repl} disabled={disabled} onChange={e=>{setRepl(e.target.value);clear();}}/>
<Button disabled={unavailable||pending||!repl.trim()} onClick={()=>void prepareAction('control_prepare',{command:'repl',text:repl})}>Подготовить команду REPL</Button>
<Button disabled={unavailable} onClick={()=>void run(async()=>{const v=await call<Record<string,unknown>>('stats');if(mounted.current)setStats(v);})}>Прочитать статистику Lisp</Button>
{stats&&<ResourceList aria-label="Статистика Lisp">{[['cpu_use','CPU, %'],['heap_use','Куча, %'],['mem_use','Память, %'],['stack_use','Стек, %'],['done_ctx_r','Результат завершённого контекста']].map(([key,title])=><li key={key}><ResourceRow title={title} description={String(stats[key]??'—')}/></li>)}</ResourceList>}
{output&&<TextAreaField label="Полученный вывод REPL" value={output} rows={8} readOnly/>}
</SettingsCard>}
{preview&&<SettingsCard title="Подтверждение операции" description="Подтверждение действует пять минут и привязано к этому контроллеру и сеансу.">
<Description>{preview.command?(preview.command==='repl'?`REPL: ${preview.text}`:preview.command==='start'?'Запуск сохранённой программы Lisp.':'Остановка Lisp.'):(preview.erase?`Удаление ${label} из контроллера.`:`Запись ${label}: ${preview.bytes} байт. Исходная копия сохраняется автоматически. Lisp не запускается.`)}</Description>
<Checker label="Подтверждаю операцию; внешние входы отключены, стенд подготовлен" checked={confirmed} onChange={setConfirmed} disabled={disabled}/><Button variant="primary" disabled={unavailable||!confirmed} onClick={()=>void apply()}>Выполнить подтверждённую операцию</Button>
</SettingsCard>}
{message&&<SettingsCard title="Результат"><Description role="status">{message}</Description></SettingsCard>}
</div>;
}