feat(bms): discover JK batteries and integrate read-only telemetry scenes
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
import {useRef,useState} from 'react';
|
||||
import {Button,ColorField,ControlRow,Description,FeatureSettingsWindow,Icon,IconButton,RangeControl,SettingsCard} from '@nodedc/ui-react';
|
||||
import {parseBatteryAppearance,type BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
import type {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
|
||||
type Section='markings'|'panels';
|
||||
export function BatteryAppearanceSettings({open,onClose,profile}:{open:boolean;onClose:()=>void;profile:ReturnType<typeof useBatteryAppearance>}){
|
||||
const [section,setSection]=useState<Section>('markings'),input=useRef<HTMLInputElement>(null);
|
||||
const {value,update}=profile,p=value.panels,m=value.markings;
|
||||
const panel=(patch:Partial<BatteryAppearance['panels']>)=>update({...value,panels:{...p,...patch}});
|
||||
const glass=(patch:Partial<typeof p.glass>)=>panel({glass:{...p.glass,...patch}});
|
||||
const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=><RangeControl label={label} value={value} min={min} max={max} step={1} exactValueBounds={{min,max}} onChange={onChange}/>;
|
||||
const exportJson=()=>{const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download='battery-ui.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);};
|
||||
return <FeatureSettingsWindow open={open} title="Настройки батареи" identity={{title:'Интерфейс батареи',subtitle:'Локальный профиль',avatarLabel:'АКБ'}} sections={[{id:'markings',label:'Маркировка ячеек',icon:'layers'},{id:'panels',label:'Плашки показаний',icon:'settings'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
headerActions={<><IconButton label="Отменить настройку батареи" disabled={!profile.canUndo} onClick={profile.undo}><Icon name="undo"/></IconButton><IconButton label="Повторить настройку батареи" disabled={!profile.canRedo} onClick={profile.redo}><Icon name="redo"/></IconButton></>}
|
||||
footer={<><Button onClick={exportJson}>Экспорт JSON</Button><Button onClick={()=>input.current?.click()}>Импорт JSON</Button><input ref={input} type="file" accept="application/json,.json" hidden onChange={async event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(!file)return;try{if(file.size>32000)throw new Error('Файл настроек слишком большой.');update(parseBatteryAppearance(JSON.parse(await file.text())));}catch(error){profile.setError(error instanceof Error?error.message:'Не удалось прочитать профиль.');}}}/></>}>
|
||||
{section==='markings'?<SettingsCard title="Маркировка ячеек" description="Номер и напряжение на заводских площадках модели. Размер меняет надпись внутри площадки.">
|
||||
<ControlRow label="Цвет маркировки"><ColorField label="Цвет маркировки" value={m.color} onChange={color=>update({...value,markings:{...m,color}})}/></ControlRow>
|
||||
{range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))}
|
||||
</SettingsCard>:<SettingsCard title="Плашки показаний" description="Общий вид верхних и нижних плашек над моделью.">
|
||||
{range('Высота плашек, px',p.height,56,160,height=>panel({height}))}
|
||||
{range('Радиус углов, px',p.radius,0,48,radius=>panel({radius}))}
|
||||
{range('Размер подписей, px',p.labelSize,10,20,labelSize=>panel({labelSize}))}
|
||||
{range('Размер значений, px',p.valueSize,12,30,valueSize=>panel({valueSize}))}
|
||||
<ControlRow label="Цвет текста"><ColorField label="Цвет текста" value={p.textColor} onChange={textColor=>panel({textColor})}/></ControlRow>
|
||||
<ControlRow label="Цвет стекла"><ColorField label="Цвет стекла" value={p.glass.tintHex} onChange={tintHex=>glass({tintHex})}/></ControlRow>
|
||||
{range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))}
|
||||
{range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))}
|
||||
</SettingsCard>}
|
||||
<Description>Сохраняется на этом компьютере для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор.</Description>
|
||||
</FeatureSettingsWindow>;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import {useEffect,useRef} from 'react';
|
||||
import * as pc from 'playcanvas';
|
||||
import type {PlayCanvasViewerProps} from '../rover/playcanvas/PlayCanvasViewer';
|
||||
import type {CellMarkingAppearance} from '../../core/batteryScene/appearance';
|
||||
import {cellDisplayIndex,drawCellDisplay} from '../../core/batteryScene/cellDisplay';
|
||||
type Api=Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0];
|
||||
/** GPU textures on the thirteen original Blender faces. Opaque geometry owns occlusion. */
|
||||
export function BatteryCellLabels({api,values,ready,appearance}:{api:Api|null;values:readonly number[];ready:boolean;appearance:CellMarkingAppearance}){
|
||||
const latest=useRef({values,appearance});latest.current={values,appearance};
|
||||
useEffect(()=>{
|
||||
if(!api||!ready)return;
|
||||
const displays=(api.modelRoot.findComponents('render') as pc.RenderComponent[]).flatMap(component=>component.meshInstances).flatMap(mesh=>{
|
||||
const index=cellDisplayIndex(mesh.node.name);if(index===null)return [];
|
||||
const canvas=document.createElement('canvas');canvas.width=canvas.height=256;const ctx=canvas.getContext('2d');if(!ctx)return [];
|
||||
const texture=new pc.Texture(api.app.graphicsDevice,{name:mesh.node.name,format:pc.PIXELFORMAT_SRGBA8,mipmaps:true,addressU:pc.ADDRESS_CLAMP_TO_EDGE,addressV:pc.ADDRESS_CLAMP_TO_EDGE});
|
||||
const original=mesh.material,material=new pc.StandardMaterial();material.name=mesh.node.name;
|
||||
material.diffuse.set(0,0,0);material.emissive.set(1,1,1);material.emissiveMap=texture;material.opacityMap=texture;material.opacityMapChannel='a';
|
||||
material.useLighting=false;material.useFog=false;material.blendType=pc.BLEND_NORMAL;material.depthTest=true;material.depthWrite=false;material.cull=pc.CULLFACE_BACK;material.update();
|
||||
return [{mesh,index,canvas,ctx,texture,material,original,signature:''}];
|
||||
});
|
||||
const update=()=>{for(const display of displays){
|
||||
const {values,appearance}=latest.current,value=values[display.index],signature=JSON.stringify([Number.isFinite(value)?value:null,appearance.color,appearance.size]);
|
||||
if(display.signature!==signature){drawCellDisplay(display.ctx,display.index,value,appearance);display.texture.setSource(display.canvas);display.texture.upload();display.signature=signature;}
|
||||
// These material slots carry live readings; their appearance is owned by battery settings.
|
||||
display.mesh.material=display.material;
|
||||
}};
|
||||
update();api.app.on('prerender',update);
|
||||
let disposed=false;
|
||||
const dispose=()=>{if(disposed)return;disposed=true;api.app.off('prerender',update);api.app.off('destroy',dispose);for(const display of displays){if(display.mesh.material===display.material)display.mesh.material=display.original;display.material.destroy();display.texture.destroy();}};
|
||||
// Viewer cleanup precedes sibling effect cleanup. Release GPU resources before the device.
|
||||
api.app.on('destroy',dispose);
|
||||
return dispose;
|
||||
},[api,ready]);
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type {CellMarkingAppearance} from '../../core/batteryScene/appearance';
|
||||
import {BatteryCellLabels} from './BatteryCellLabels';
|
||||
import type {PlayCanvasViewerProps} from '../rover/playcanvas/PlayCanvasViewer';
|
||||
import {useMemo,useState} from 'react';
|
||||
import {Description} from '@nodedc/ui-react';
|
||||
import {SceneEditor} from '../rover/editor/RoverScene';
|
||||
import {useSceneDocument} from '../../core/roverScene/useSceneDocument';
|
||||
import {batterySceneProfile,defaultBatteryScene} from '../../core/batteryScene/profile';
|
||||
|
||||
export function BatteryScene({editing,soc,fresh,deviceId,seedKey,cellVoltages=[],markingAppearance}:{editing:boolean;soc:number|null;fresh:boolean;deviceId:string;seedKey?:string;cellVoltages?:readonly number[];markingAppearance:CellMarkingAppearance}){
|
||||
const profile=useMemo(()=>batterySceneProfile(seedKey),[seedKey]);
|
||||
const scene=useSceneDocument(deviceId,profile);
|
||||
const [api,setApi]=useState<Parameters<NonNullable<PlayCanvasViewerProps['onSceneReady']>>[0]|null>(null);
|
||||
const [phase,setPhase]=useState<'loading'|'ready'|'error'>('loading');
|
||||
return <div className="bms-scene" data-editing={editing} aria-label="3D-модель батареи R04">
|
||||
<SceneEditor scene={scene} defaults={defaultBatteryScene} editing={editing} modelUrl="/battery-scene/catl-r04.glb?objects-v5" minFitDistance={.6} chargeState={{soc,fresh}} onModelState={setPhase} onSceneReady={setApi}/>
|
||||
<BatteryCellLabels api={api} ready={phase==='ready'} values={cellVoltages} appearance={markingAppearance}/>
|
||||
{phase!=='ready'&&<div className="bms-scene-status"><Description role="status">{phase==='error'?'Модель не загрузилась. Показания BMS доступны ниже.':'Загружается модель аккумулятора…'}</Description></div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import {BatteryAppearanceSettings} from './BatteryAppearanceSettings';
|
||||
import {useBatteryAppearance} from '../../core/batteryScene/useBatteryAppearance';
|
||||
import type {BatteryAppearance} from '../../core/batteryScene/appearance';
|
||||
import {useEffect,useState,type ReactNode} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {EditorWorkspace,Icon,IconButton,ResizableViewport,ToastStack,useApplicationPanelFullscreen} from '@nodedc/ui-react';
|
||||
import {batteryViewHeight,batteryViewHeightKey,minBatteryViewHeight,maxBatteryViewHeight} from '../../core/batteryScene/viewHeight';
|
||||
|
||||
export function BatteryWorkspace({children,deviceId,title,headerActionsTarget,back}:{deviceId:string;title:string;headerActionsTarget?:HTMLElement|null;back:()=>void;children:(controls:{editing:boolean;appearance:BatteryAppearance;renderViewport:(children:ReactNode)=>ReactNode})=>ReactNode}){
|
||||
const full=useApplicationPanelFullscreen(),[editing,setEditing]=useState(false),[error,setError]=useState(''),[settings,setSettings]=useState(false);
|
||||
const profile=useBatteryAppearance(deviceId,settings);
|
||||
const [height,setHeight]=useState(()=>{try{return batteryViewHeight(localStorage.getItem(batteryViewHeightKey(deviceId)),window.innerHeight);}catch{return batteryViewHeight(null,window.innerHeight);}});
|
||||
const fullscreen=full?.fullscreen??false,setFullscreen=full?.setFullscreen;
|
||||
useEffect(()=>()=>{setFullscreen?.(false);},[setFullscreen]);
|
||||
useEffect(()=>{const escape=(event:KeyboardEvent)=>{
|
||||
if(event.key!=='Escape'||event.defaultPrevented||document.querySelector('[role=dialog],[role=listbox]'))return;
|
||||
event.preventDefault();if(fullscreen)setFullscreen?.(false);else if(editing)setEditing(false);else back();
|
||||
};window.addEventListener('keydown',escape);return()=>window.removeEventListener('keydown',escape);},[editing,fullscreen,setFullscreen,back]);
|
||||
const commitHeight=(value:number)=>{try{localStorage.setItem(batteryViewHeightKey(deviceId),JSON.stringify({height:value}));setError('');}catch{setError('Не удалось сохранить высоту окна на этом компьютере.');}};
|
||||
const actions=<>{full&&<IconButton label={fullscreen?'Восстановить окно батареи':'Развернуть окно батареи'} onClick={()=>setFullscreen?.(!fullscreen)}><Icon name={fullscreen?'minimize':'expand'}/></IconButton>}<IconButton label={editing?'Завершить редактирование сцены':'Редактировать сцену'} aria-pressed={editing} onClick={()=>{setSettings(false);setEditing(value=>!value);}}><Icon name="edit"/></IconButton><IconButton label="Настройки батареи" aria-pressed={settings} onClick={()=>{setEditing(false);setSettings(true);}}><Icon name="settings"/></IconButton></>;
|
||||
return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}{children({editing,appearance:profile.value,renderViewport:content=><ResizableViewport resizeIndicator={false} className="bms-stage" height={height} minHeight={minBatteryViewHeight} maxHeight={maxBatteryViewHeight} onHeightChange={setHeight} onHeightCommit={commitHeight}><EditorWorkspace editing={editing} title={title} subtitle="Редактирование сцены аккумулятора" onBack={()=>setEditing(false)}><div className="bms-stage bms-editor-content">{content}</div></EditorWorkspace></ResizableViewport>})}<BatteryAppearanceSettings open={settings} onClose={()=>setSettings(false)} profile={profile}/><ToastStack items={(error||profile.error)?[{id:'battery-view-save',title:error||profile.error,tone:'error'}]:[]} onDismiss={()=>{setError('');profile.setError('');}}/></>;
|
||||
}
|
||||
Reference in New Issue
Block a user