Integrate tracker commands into the settings tab
Device Core qualification / qualify (push) Failing after 3m29s
Device Core qualification / qualify (push) Failing after 3m29s
This commit is contained in:
@@ -10,7 +10,7 @@ export function B2TrackerSettings({projectRef,device,initialSection='identity',o
|
||||
const [data,setData]=useState<TrackerState|null>(null), [name,setName]=useState(device.name);
|
||||
const [policy,setPolicy]=useState<Policy>({parameters:{},connectivity:{mode:'preserve'}});
|
||||
const [profile,setProfile]=useState(''),[profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false);
|
||||
const [busy,setBusy]=useState('load'),[dirty,setDirty]=useState(false),[commandsOpen,setCommandsOpen]=useState(initialSection==='commands');
|
||||
const [busy,setBusy]=useState('load'),[dirty,setDirty]=useState(false),[commandRefresh,setCommandRefresh]=useState(0);
|
||||
const [bootstrapFirmware,setBootstrapFirmware]=useState(''),[bootstrapPassword,setBootstrapPassword]=useState('');
|
||||
const profileIntent=useRef<Record<string,unknown>|null>(null);
|
||||
const [latest,setLatest]=useState<Operation|null>(null);
|
||||
@@ -65,11 +65,11 @@ export function B2TrackerSettings({projectRef,device,initialSection='identity',o
|
||||
const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=filename;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
|
||||
}
|
||||
return <>
|
||||
<FeatureSettingsWindow open={!profileOpen&&!commandsOpen} title="Настройки устройства" subtitle={`ARNavi B2 · ${device.number}`}
|
||||
<FeatureSettingsWindow open={!profileOpen} title="Настройки устройства" subtitle={`ARNavi B2 · ${device.number}`}
|
||||
identity={{title:'ARNavi B2',subtitle:`IMEI ${device.identifier.masked}`,avatarLabel:'AR'}}
|
||||
sections={[{id:'identity',label:'Устройство и проект'},{id:'connection',label:'Сервер и связь'},{id:'commands',label:'Команды'},{id:'firmware',label:'Прошивка'},...groupNames.map((group,index)=>({id:group,label:group,group:index===0?'Параметры профиля':undefined}))]}
|
||||
activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
headerActions={<IconButton label="Обновить сведения о трекере" disabled={Boolean(busy)} loading={busy==='refresh'} onClick={()=>void run('refresh',async()=>{await refresh();})}><Icon name="refresh" /></IconButton>}
|
||||
headerActions={<IconButton label={section==='commands'?'Обновить журнал команд':'Обновить сведения о трекере'} disabled={Boolean(busy)} loading={busy==='refresh'} onClick={()=>void run('refresh',async()=>{if(section==='commands')setCommandRefresh(value=>value+1);await refresh();})}><Icon name="refresh" /></IconButton>}
|
||||
footer={section!=='commands'&§ion!=='firmware'?<WindowFooterActions><Button disabled={disabled||!dirty||!data} loading={busy==='save'} onClick={()=>void run('save',async()=>{await save();})}>Сохранить настройки</Button><Button disabled={disabled||!data} onClick={()=>{profileIntent.current=null;setProfileName('');setProfileOpen(true);}}>Сохранить профиль</Button></WindowFooterActions>:undefined}>
|
||||
<div className="b2-tracker-form" aria-busy={Boolean(busy)}>
|
||||
<StatusBadge tone={connected?'success':'neutral'}>{connected?'Передаёт данные на VPS':data?'Нет свежих данных':'Загрузка…'}</StatusBadge>
|
||||
@@ -102,7 +102,7 @@ export function B2TrackerSettings({projectRef,device,initialSection='identity',o
|
||||
</div></SettingsCard>
|
||||
</>:null}
|
||||
{groupNames.includes(section)&&data?<><span>Пустое поле — сохранить значение трекера.</span>{data.fields.filter(field=>field.group===section).map(field=><TextField key={field.id} label={field.label} hint={`${field.minimum} … ${field.maximum}`} type="number" step={1} min={field.minimum} max={field.maximum} disabled={disabled||!Object.hasOwn(data.observed?.parameters||{},field.id)} placeholder={String(data.observed?.parameters[field.id]??'Недоступно на этой прошивке')} value={policy.parameters[field.id]??''} onChange={event=>{const parameters={...policy.parameters};if(event.target.value==='')delete parameters[field.id];else parameters[field.id]=Number(event.target.value);edit({...policy,parameters});}} />)}</>:null}
|
||||
{section==='commands'?<SettingsCard title="Команды устройства"><Button onClick={()=>setCommandsOpen(true)}>Открыть консоль команд</Button></SettingsCard>:null}
|
||||
<B2CommandPanel projectRef={projectRef} device={device} data={data} canCommand={canCommand} active={section==='commands'} refreshKey={commandRefresh} onError={onError} />
|
||||
{section==='firmware'&&data?<><SettingsCard title="Прошивка устройства"><ResourceRow title={`Установлена ${data.firmware||'неизвестная версия'}`} metadata="Архив файлов · установка по сети недоступна" /></SettingsCard>
|
||||
<SettingsCard title="Архив прошивок" actions={<IconButton label="Добавить прошивку" disabled={disabled} onClick={()=>file.current?.click()}><Icon name="plus" /></IconButton>}>
|
||||
<input ref={file} type="file" accept=".dfw" hidden onChange={event=>{const selected=event.target.files?.[0];event.target.value='';if(selected)void run('firmware',()=>uploadFirmware(selected));}} />
|
||||
@@ -111,25 +111,26 @@ export function B2TrackerSettings({projectRef,device,initialSection='identity',o
|
||||
</SettingsCard></>:null}
|
||||
</div>
|
||||
</FeatureSettingsWindow>
|
||||
{commandsOpen?<B2CommandWindow projectRef={projectRef} device={device} data={data} canCommand={canCommand} onClose={()=>setCommandsOpen(false)} onError={onError} />:null}
|
||||
<Window open={profileOpen} title="Сохранить профиль" size="sm" onClose={()=>setProfileOpen(false)} footer={<WindowFooterActions><Button loading={busy==='profile'} disabled={Boolean(busy)||!profileName.trim()} onClick={()=>void run('profile',async()=>{profileIntent.current ||= {action:'profile-save',id:newIntent(),name:profileName,policy};try{await request(profileIntent.current);profileIntent.current=null;}catch(error){if(error instanceof B2RequestError&&error.rejected)profileIntent.current=null;throw error;}setProfileOpen(false);await refresh();})}>Сохранить профиль</Button></WindowFooterActions>}><TextField label="Название профиля" disabled={Boolean(busy)||Boolean(profileIntent.current)} autoFocus value={profileName} onChange={event=>setProfileName(event.target.value)} /></Window>
|
||||
</>;
|
||||
}
|
||||
|
||||
const presets=[{id:'position',label:'Запросить координаты',command:{kind:'request-position'}},{id:'restart',label:'Перезапустить B2',command:{kind:'restart'}},...[4,5,6].flatMap(pin=>[...([true,false] as const).map(enabled=>({id:`pin${pin}-${enabled}`,label:`${enabled?'Включить':'Выключить'} выход PIN${pin}`,command:{kind:'set-output',pin,enabled}})),{id:`pin${pin}-pulse`,label:`Импульс PIN${pin} · 5 с`,command:{kind:'pulse-output',pin,seconds:5}}])];
|
||||
function B2CommandWindow({projectRef,device,data,canCommand,onClose,onError}:{projectRef:string;device:TrackerRef;data:TrackerState|null;canCommand:boolean;onClose:()=>void;onError:(error:unknown)=>void}) {
|
||||
function B2CommandPanel({projectRef,device,data,canCommand,active,refreshKey,onError}:{projectRef:string;device:TrackerRef;data:TrackerState|null;canCommand:boolean;active:boolean;refreshKey:number;onError:(error:unknown)=>void}) {
|
||||
const [filter,setFilter]=useState('all');
|
||||
const [selection,setSelection]=useState('position'),[rows,setRows]=useState<Operation[]>([]),[before,setBefore]=useState<number|null>(null),[busy,setBusy]=useState(false),[details,setDetails]=useState<string[]>([]),[history,setHistory]=useState<Record<string,unknown>>({});
|
||||
const intent=useRef<Record<string,unknown>|null>(null),alive=useRef(true);
|
||||
const request=<T,>(body:Record<string,unknown>)=>trackerRequest<T>(projectRef,device,body);
|
||||
async function refresh(append=false) {const result=await request<{items:Operation[];before:number|null}>({action:'journal',...(append&&before?{before}:{})});if(alive.current){setRows(old=>append?[...old,...result.items]:result.items);setBefore(result.before);}}
|
||||
useEffect(()=>{alive.current=true;void refresh().catch(onError);return()=>{alive.current=false;};},[]);
|
||||
useEffect(()=>{if(!rows.some(row=>['queued','dispatched'].includes(row.state)))return;const timer=setTimeout(()=>void refresh().catch(onError),3000);return()=>clearTimeout(timer);},[rows]);
|
||||
useEffect(()=>{alive.current=true;return()=>{alive.current=false;};},[]);
|
||||
useEffect(()=>{if(active)void refresh().catch(onError);},[active,refreshKey]);
|
||||
useEffect(()=>{if(!active||!rows.some(row=>['queued','dispatched'].includes(row.state)))return;const timer=setTimeout(()=>void refresh().catch(onError),3000);return()=>clearTimeout(timer);},[active,rows]);
|
||||
const selected=presets.find(item=>item.id===selection)!;
|
||||
const pin='pin' in selected.command?selected.command.pin:null;
|
||||
const available=data?.capabilities.configuration&&(!pin||data.observed?.output_modes[String(pin)]===1);
|
||||
async function send(command:Record<string,unknown>=selected.command) {setBusy(true);try {intent.current ||= {action:'command',id:newIntent(),command};await request(intent.current);intent.current=null;await refresh();}catch(error){if(error instanceof B2RequestError&&error.rejected)intent.current=null;onError(error);}finally{setBusy(false);}}
|
||||
return <Window open title="Команды устройства" subtitle={`ARNavi B2 · ${device.number}`} size="lg" onClose={onClose} headerActions={<IconButton label="Обновить журнал команд" disabled={busy} onClick={()=>void refresh().catch(onError)}><Icon name="refresh" /></IconButton>}>
|
||||
// Keep the panel mounted across tabs so an uncertain send retains its intent ID.
|
||||
return <div hidden={!active}>
|
||||
<div className="b2-tracker-form">
|
||||
<SettingsCard title="Отправка команды"><div className="b2-tracker-form"><Select label="Команда" value={selection} disabled={busy||Boolean(intent.current)} options={presets.map(item=>({value:item.id,label:item.label,disabled:'pin' in item.command&&data?.observed?.output_modes[String(item.command.pin)]!==1}))} onChange={setSelection} />
|
||||
{pin?<span>Подтверждение доставки не определяет положение контактов реле.</span>:null}
|
||||
@@ -139,6 +140,6 @@ function B2CommandWindow({projectRef,device,data,canCommand,onClose,onError}:{pr
|
||||
{details.includes(row.id)?<div className="b2-disclosure__body"><dl className="b2-tracker-facts"><dt>Попытки</dt><dd>{row.attempt_count??0}</dd><dt>Отправлена</dt><dd>{formatTime(row.dispatched_at)}</dd><dt>Ответ</dt><dd>{formatTime(row.received_at||row.delivered_at||row.verified_at)}</dd><dt>Результат</dt><dd>{stateName(row.state)}</dd><dt>ID</dt><dd>{row.id}</dd></dl><AttemptRows value={history[row.id]} onMore={before=>void request<{items:Operation[];next_before:number|null}>({action:'attempts',operation:row.id,before}).then(value=>setHistory(old=>({...old,[row.id]:{...value,items:[...((old[row.id] as {items:Operation[]})?.items||[]),...value.items]}}))).catch(onError)} /></div>:null}
|
||||
</li>)}</ResourceList>{!rows.length?<span>Команд пока нет</span>:null}{before?<Button onClick={()=>void refresh(true).catch(onError)}>Предыдущие команды</Button>:null}</SettingsCard>
|
||||
</div>
|
||||
</Window>;
|
||||
</div>;
|
||||
}
|
||||
function AttemptRows({value,onMore}:{value:unknown;onMore:(before:number)=>void}) { const page=value as {items?:Operation[];next_before?:number|null}|undefined;return page?.items?.length?<><ResourceList>{page.items.map((item,index)=><li key={item.id||index}><ResourceRow title={`Попытка ${item.number??index+1}`} metadata={formatTime(item.dispatched_at)} status={<StatusBadge tone={operationTone(item.state)}>{stateName(item.state)}</StatusBadge>} /></li>)}</ResourceList>{page.next_before?<Button onClick={()=>onMore(page.next_before!)}>Предыдущие попытки</Button>:null}</>:null; }
|
||||
|
||||
@@ -22,7 +22,20 @@ USB читает операторский браузер через Web Serial,
|
||||
восстановление остаётся доступно в архиве. История ключей раскрывается вместе
|
||||
с приложением, отдельного глазика нет. Жёлтое видео и общие компоненты не менялись.
|
||||
|
||||
Проверки: 298 Node tests, TypeScript; 315 VPS tests (изолированный TCP отдельно
|
||||
Проверки выпуска r32: 300 Node tests, TypeScript; 315 VPS tests (изолированный TCP отдельно
|
||||
вне ограничения loopback песочницы), ruff; 74 теста совместимости Mission Core.
|
||||
Реальная форма Mission Core прочитала B2 по USB: firmware 0.06. Это эталонная
|
||||
проверка; собственный путь Web Serial требует отдельного браузерного подтверждения.
|
||||
Реальная форма Mission Core прочитала B2 по USB: firmware 0.06. Пользователь
|
||||
2026-10-01 подтвердил успешное чтение ARNavi по USB в новой форме Device Core
|
||||
после выдачи браузеру разрешения на устройство. Агент сам этот Web Serial read
|
||||
не выполнял. Установка на чистой Ubuntu остаётся непроверенной; обновление
|
||||
действующего VPS прошло штатным plan/apply.
|
||||
|
||||
## Команды во вкладке настроек
|
||||
|
||||
Кнопка команд в строке трекера открывает единственное окно настроек сразу на
|
||||
вкладке «Команды». В ней находятся выбор и отправка команды, фильтр журнала,
|
||||
состояния, повтор, отмена, история попыток и подгрузка предыдущих записей.
|
||||
Отдельного окна команд и промежуточной ссылки больше нет. Крестик и Escape
|
||||
закрывают настройки целиком. Переключение вкладок сохраняет выбор команды,
|
||||
фильтр и идентификатор незавершённой отправки; возврат обновляет журнал.
|
||||
Кнопка обновления в шапке на вкладке команд обновляет журнал и состояние трекера.
|
||||
|
||||
Reference in New Issue
Block a user