From f3d0c25ccd85d309a6e2ac52a048e690e60e885a Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Wed, 4 Nov 2026 00:43:00 +0300 Subject: [PATCH] feat(bms): discover JK batteries and integrate read-only telemetry scenes --- .../public/battery-scene/catl-r04.glb | 3 + .../public/battery-scene/catl-r04.json | 119 +++++ .../battery/BatteryAppearanceSettings.tsx | 31 ++ .../components/battery/BatteryCellLabels.tsx | 35 ++ .../src/components/battery/BatteryScene.tsx | 20 + .../components/battery/BatteryWorkspace.tsx | 22 + .../src/composition/devicePlugins.ts | 11 +- .../src/core/batteryScene/appearance.ts | 14 + .../src/core/batteryScene/cellDisplay.ts | 12 + .../src/core/batteryScene/profile.ts | 34 ++ .../src/core/batteryScene/r04.json | 501 ++++++++++++++++++ .../core/batteryScene/useBatteryAppearance.ts | 21 + .../src/core/batteryScene/viewHeight.ts | 7 + .../workspaces/fleet/VehicleDeviceView.tsx | 22 + .../src/workspaces/fleet/VehicleFleetRow.tsx | 4 +- .../src/workspaces/fleet/VehicleSensors.tsx | 4 +- .../workspaces/fleet/VehiclesWorkspace.tsx | 10 +- .../test/batteryScene.test.mjs | 100 ++++ apps/node-agent/internal/node/sensor_bms.go | 16 + .../internal/node/sensor_bms_test.go | 27 + .../node-agent/internal/node/sensor_models.go | 2 + apps/node-agent/internal/node/sensors.go | 3 + apps/node-agent/ui/src/NodeSensors.tsx | 3 +- docs/node/JK_BMS_BLUETOOTH.md | 211 ++++++++ packages/sensor-ui/src/contracts.ts | 1 + .../jk-bms/frontend/src/BatteryTelemetry.tsx | 19 + plugins/jk-bms/frontend/src/BmsDetail.tsx | 49 ++ plugins/jk-bms/frontend/src/bms.css | 39 ++ plugins/jk-bms/frontend/src/model.ts | 28 + plugins/jk-bms/frontend/src/plugin.ts | 8 + .../jk-bms/packaging/mission-core-jk-bms.conf | 17 + .../packaging/mission-core-jk-bms.service | 40 ++ plugins/jk-bms/packaging/payload.py | 17 + plugins/jk-bms/packaging/qualify_package.py | 85 +++ plugins/jk-bms/packaging/repack_node.py | 142 +++++ plugins/jk-bms/runtime/__init__.py | 5 + plugins/jk-bms/runtime/bluez.py | 252 +++++++++ plugins/jk-bms/runtime/protocol.py | 139 +++++ plugins/jk-bms/runtime/server.py | 96 ++++ plugins/jk-bms/runtime/service.py | 171 ++++++ plugins/jk-bms/tests/test_bluez.py | 143 +++++ plugins/jk-bms/tests/test_bms.py | 143 +++++ src/k1link/fleet/registry.py | 1 + src/k1link/fleet/sensor_transient.py | 46 ++ tests/fleet/test_bms_transient.py | 68 +++ tools/battery-scene/export_battery.py | 156 ++++++ 46 files changed, 2887 insertions(+), 10 deletions(-) create mode 100644 apps/control-station/public/battery-scene/catl-r04.glb create mode 100644 apps/control-station/public/battery-scene/catl-r04.json create mode 100644 apps/control-station/src/components/battery/BatteryAppearanceSettings.tsx create mode 100644 apps/control-station/src/components/battery/BatteryCellLabels.tsx create mode 100644 apps/control-station/src/components/battery/BatteryScene.tsx create mode 100644 apps/control-station/src/components/battery/BatteryWorkspace.tsx create mode 100644 apps/control-station/src/core/batteryScene/appearance.ts create mode 100644 apps/control-station/src/core/batteryScene/cellDisplay.ts create mode 100644 apps/control-station/src/core/batteryScene/profile.ts create mode 100644 apps/control-station/src/core/batteryScene/r04.json create mode 100644 apps/control-station/src/core/batteryScene/useBatteryAppearance.ts create mode 100644 apps/control-station/src/core/batteryScene/viewHeight.ts create mode 100644 apps/control-station/src/workspaces/fleet/VehicleDeviceView.tsx create mode 100644 apps/control-station/test/batteryScene.test.mjs create mode 100644 apps/node-agent/internal/node/sensor_bms.go create mode 100644 apps/node-agent/internal/node/sensor_bms_test.go create mode 100644 docs/node/JK_BMS_BLUETOOTH.md create mode 100644 plugins/jk-bms/frontend/src/BatteryTelemetry.tsx create mode 100644 plugins/jk-bms/frontend/src/BmsDetail.tsx create mode 100644 plugins/jk-bms/frontend/src/bms.css create mode 100644 plugins/jk-bms/frontend/src/model.ts create mode 100644 plugins/jk-bms/frontend/src/plugin.ts create mode 100644 plugins/jk-bms/packaging/mission-core-jk-bms.conf create mode 100644 plugins/jk-bms/packaging/mission-core-jk-bms.service create mode 100644 plugins/jk-bms/packaging/payload.py create mode 100644 plugins/jk-bms/packaging/qualify_package.py create mode 100644 plugins/jk-bms/packaging/repack_node.py create mode 100644 plugins/jk-bms/runtime/__init__.py create mode 100644 plugins/jk-bms/runtime/bluez.py create mode 100644 plugins/jk-bms/runtime/protocol.py create mode 100644 plugins/jk-bms/runtime/server.py create mode 100644 plugins/jk-bms/runtime/service.py create mode 100644 plugins/jk-bms/tests/test_bluez.py create mode 100644 plugins/jk-bms/tests/test_bms.py create mode 100644 tests/fleet/test_bms_transient.py create mode 100644 tools/battery-scene/export_battery.py diff --git a/apps/control-station/public/battery-scene/catl-r04.glb b/apps/control-station/public/battery-scene/catl-r04.glb new file mode 100644 index 00000000..9fcf5e10 --- /dev/null +++ b/apps/control-station/public/battery-scene/catl-r04.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f4ac32560ac1906abd92e7c3be35f852ce166ead700f5e27c3b3ce2bdcc7dd3 +size 39541516 diff --git a/apps/control-station/public/battery-scene/catl-r04.json b/apps/control-station/public/battery-scene/catl-r04.json new file mode 100644 index 00000000..6034f19a --- /dev/null +++ b/apps/control-station/public/battery-scene/catl-r04.json @@ -0,0 +1,119 @@ +{ + "source": "Cattle_Battery_Enclosure_R04.blend", + "source_sha256": "ec802dfbc2866ab474ce5f809ea9289f2402ec791c0abccb22826620af78a42b", + "model": "catl-r04.glb", + "sha256": "1f4ac32560ac1906abd92e7c3be35f852ce166ead700f5e27c3b3ce2bdcc7dd3", + "bytes": 39541516, + "groups": 63, + "cell_bodies": 13, + "objects": [ + "bms/Cable / red silicone", + "bms/Cable / graphite silicone", + "bms/Mount / G10 dielectric", + "bms/Nickel plated copper / busbars", + "bms/Sense / warm yellow", + "bms/labels/electronics", + "bms/Connector / ivory polymer", + "bms/BMS / green PCB", + "bms/Aluminium / satin", + "bms/Lid / insulating black", + "bms/Mount / adhesive film", + "bms/Steel / fasteners", + "bms/cells/C01", + "bms/Cell / wrapped lower edge", + "bms/labels/cells", + "bms/cell-display/C01", + "bms/cells/C02", + "bms/cell-display/C02", + "bms/cells/C03", + "bms/cell-display/C03", + "bms/cells/C04", + "bms/cell-display/C04", + "bms/cells/C05", + "bms/cell-display/C05", + "bms/cells/C06", + "bms/cell-display/C06", + "bms/cells/C07", + "bms/cell-display/C07", + "bms/cells/C08", + "bms/cell-display/C08", + "bms/cells/C09", + "bms/cell-display/C09", + "bms/cells/C10", + "bms/cell-display/C10", + "bms/cells/C11", + "bms/cell-display/C11", + "bms/cells/C12", + "bms/cell-display/C12", + "bms/cells/C13", + "bms/cell-display/C13", + "bms/CASE | bead-blasted graphite/CASE | base tray", + "bms/CASE | bead-blasted graphite/CASE | front endplate", + "bms/CASE | bead-blasted graphite/CASE | rear endplate", + "bms/glass/CASE | removable solid top", + "bms/glass/CASE | slotted side -1", + "bms/glass/CASE | slotted side 1", + "bms/R04 | elastomer seal", + "bms/R04 | graphite moulded polymer", + "bms/labels/enclosure", + "bms/R04 | smoked polycarbonate", + "bms/R04 | display protective polycarbonate", + "bms/DISPLAY | black glass", + "bms/CASE | recessed black", + "bms/CASE | darker frame", + "bms/CASE | bead-blasted graphite/HANDLE | folded aperture return", + "bms/CASE | bead-blasted graphite/HANDLE | folded aperture return.001", + "bms/CASE | bead-blasted graphite/HANDLE | integral web underside", + "bms/CASE | dielectric liner", + "bms/CASE | dielectric liner/left", + "bms/CASE | dielectric liner/right", + "bms/Connector / gold plated contacts", + "bms/XT90-S / anti spark green insert", + "bms/XT90-S / yellow PA housing" + ], + "materials": [ + "bms/Cable / red silicone", + "bms/Cable / graphite silicone", + "bms/Mount / G10 dielectric", + "bms/Nickel plated copper / busbars", + "bms/Sense / warm yellow", + "bms/labels", + "bms/Connector / ivory polymer", + "bms/BMS / green PCB", + "bms/Aluminium / satin", + "bms/Lid / insulating black", + "bms/Mount / adhesive film", + "bms/Steel / fasteners", + "bms/cells", + "bms/Cell / wrapped lower edge", + "bms/cell-display/C01", + "bms/cell-display/C02", + "bms/cell-display/C03", + "bms/cell-display/C04", + "bms/cell-display/C05", + "bms/cell-display/C06", + "bms/cell-display/C07", + "bms/cell-display/C08", + "bms/cell-display/C09", + "bms/cell-display/C10", + "bms/cell-display/C11", + "bms/cell-display/C12", + "bms/cell-display/C13", + "bms/CASE | bead-blasted graphite", + "bms/glass", + "bms/R04 | elastomer seal", + "bms/R04 | graphite moulded polymer", + "bms/R04 | smoked polycarbonate", + "bms/R04 | display protective polycarbonate", + "bms/DISPLAY | black glass", + "bms/CASE | recessed black", + "bms/CASE | darker frame", + "bms/CASE | dielectric liner", + "bms/Connector / gold plated contacts", + "bms/XT90-S / anti spark green insert", + "bms/XT90-S / yellow PA housing" + ], + "cell_displays": 13, + "uv": "cube_projection; original cell display faces use planar X/Z UV", + "source_modified": false +} diff --git a/apps/control-station/src/components/battery/BatteryAppearanceSettings.tsx b/apps/control-station/src/components/battery/BatteryAppearanceSettings.tsx new file mode 100644 index 00000000..7dc39357 --- /dev/null +++ b/apps/control-station/src/components/battery/BatteryAppearanceSettings.tsx @@ -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}){ + const [section,setSection]=useState
('markings'),input=useRef(null); + const {value,update}=profile,p=value.panels,m=value.markings; + const panel=(patch:Partial)=>update({...value,panels:{...p,...patch}}); + const glass=(patch:Partial)=>panel({glass:{...p.glass,...patch}}); + const range=(label:string,value:number,min:number,max:number,onChange:(v:number)=>void)=>; + 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 } + footer={<>{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'? + update({...value,markings:{...m,color}})}/> + {range('Размер маркировки, %',m.size,50,160,size=>update({...value,markings:{...m,size}}))} + : + {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}))} + panel({textColor})}/> + glass({tintHex})}/> + {range('Прозрачность стекла, %',100-p.glass.tintOpacity,0,100,transparency=>glass({tintOpacity:100-transparency}))} + {range('Размытие стекла, px',p.glass.blur,0,60,blur=>glass({blur}))} + } + Сохраняется на этом компьютере для этой батареи. Ctrl Z / ⌘ Z — отмена, Shift Ctrl Z / ⇧ ⌘ Z — повтор. + ; +} diff --git a/apps/control-station/src/components/battery/BatteryCellLabels.tsx b/apps/control-station/src/components/battery/BatteryCellLabels.tsx new file mode 100644 index 00000000..c6ed0a0b --- /dev/null +++ b/apps/control-station/src/components/battery/BatteryCellLabels.tsx @@ -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>[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; +} diff --git a/apps/control-station/src/components/battery/BatteryScene.tsx b/apps/control-station/src/components/battery/BatteryScene.tsx new file mode 100644 index 00000000..bc9e1ede --- /dev/null +++ b/apps/control-station/src/components/battery/BatteryScene.tsx @@ -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>[0]|null>(null); + const [phase,setPhase]=useState<'loading'|'ready'|'error'>('loading'); + return
+ + + {phase!=='ready'&&
{phase==='error'?'Модель не загрузилась. Показания BMS доступны ниже.':'Загружается модель аккумулятора…'}
} +
; +} diff --git a/apps/control-station/src/components/battery/BatteryWorkspace.tsx b/apps/control-station/src/components/battery/BatteryWorkspace.tsx new file mode 100644 index 00000000..bf3b4533 --- /dev/null +++ b/apps/control-station/src/components/battery/BatteryWorkspace.tsx @@ -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&&setFullscreen?.(!fullscreen)}>}{setSettings(false);setEditing(value=>!value);}}>{setEditing(false);setSettings(true);}}>; + return <>{headerActionsTarget?createPortal(actions,headerActionsTarget):actions}{children({editing,appearance:profile.value,renderViewport:content=>setEditing(false)}>
{content}
})}setSettings(false)} profile={profile}/>{setError('');profile.setError('');}}/>; +} diff --git a/apps/control-station/src/composition/devicePlugins.ts b/apps/control-station/src/composition/devicePlugins.ts index 6aa1fb34..1d810a83 100644 --- a/apps/control-station/src/composition/devicePlugins.ts +++ b/apps/control-station/src/composition/devicePlugins.ts @@ -1,4 +1,11 @@ import {usbCanSensorUi} from '../../../../plugins/usb-can/frontend/src/plugin'; +import {createElement} from 'react'; +import {jkBmsSensorUi} from '../../../../plugins/jk-bms/frontend/src/plugin'; +import {BmsDetail} from '../../../../plugins/jk-bms/frontend/src/BmsDetail'; +import type {BatteryState} from '../../../../plugins/jk-bms/frontend/src/model'; +import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions'; +import {BatteryScene} from '../components/battery/BatteryScene'; +import {BatteryWorkspace} from '../components/battery/BatteryWorkspace'; import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin'; import type { DeviceUiPlugin } from "../core/device-plugins/contracts"; import { xgridsK1Plugin } from "@xgrids-k1/frontend/plugin"; @@ -12,4 +19,6 @@ export const installedDevicePlugins: readonly DeviceUiPlugin[] = Object.freeze([ // Node-executed camera controls use the existing sensor contribution contract; // they do not register a desktop capture/AI runtime or a new product workspace. -export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi,usbCanSensorUi]); + +const CoreBmsDetail=(props:SensorDetailProps)=>createElement(BatteryWorkspace,{key:props.device.id,deviceId:props.device.id,title:`Аккумулятор / ${props.device.name}`,headerActionsTarget:props.headerActionsTarget,back:props.back,children:controls=>createElement(BmsDetail,{...props,presentation:'page',editing:controls.editing,panelAppearance:controls.appearance.panels,renderViewport:controls.renderViewport,renderScene:(state:BatteryState)=>createElement(BatteryScene,{editing:controls.editing,markingAppearance:controls.appearance.markings,deviceId:props.device.id,seedKey:props.sceneSeedKey,soc:state.sample?.soc_percent??null,fresh:state.fresh,cellVoltages:state.sample?.cell_voltages_v})})}); +export const installedNodeSensorContributions = Object.freeze([insta360X4SensorUi,vescSensorUi,usbCanSensorUi,{...jkBmsSensorUi,detailPresentation:'workspace' as const,Detail:CoreBmsDetail}]); diff --git a/apps/control-station/src/core/batteryScene/appearance.ts b/apps/control-station/src/core/batteryScene/appearance.ts new file mode 100644 index 00000000..d8620b26 --- /dev/null +++ b/apps/control-station/src/core/batteryScene/appearance.ts @@ -0,0 +1,14 @@ +import {defaultGlassMaterial,type GlassMaterialSettings} from '@nodedc/ui-core'; +export type CellMarkingAppearance={color:string;size:number}; +export type BatteryPanelAppearance={height:number;radius:number;labelSize:number;valueSize:number;textColor:string;glass:GlassMaterialSettings}; +export type BatteryAppearance={schema:'missioncore.battery-ui/v1';markings:CellMarkingAppearance;panels:BatteryPanelAppearance}; +export const batteryAppearanceKey=(id:string)=>`missioncore.battery-ui/v1:${id}`; +export function defaultBatteryAppearance():BatteryAppearance{return {schema:'missioncore.battery-ui/v1',markings:{color:'#ffffff',size:100},panels:{height:76,radius:24,labelSize:12,valueSize:18,textColor:'#f1f1ef',glass:{...defaultGlassMaterial,tintOpacity:52,blur:18}}};} +const object=(v:unknown):Record=>v!==null&&typeof v==='object'?v as Record:{}; +const number=(v:unknown,fallback:number,min:number,max:number)=>typeof v==='number'&&Number.isFinite(v)?Math.min(max,Math.max(min,v)):fallback; +const color=(v:unknown,fallback:string)=>typeof v==='string'&&/^#[0-9a-f]{6}$/i.test(v)?v.toLowerCase():fallback; +export function parseBatteryAppearance(raw:unknown):BatteryAppearance{ + const source=object(raw);if(source.schema!=='missioncore.battery-ui/v1')throw new Error('Это не профиль интерфейса батареи.'); + const d=defaultBatteryAppearance(),m=object(source.markings),p=object(source.panels),g=object(p.glass); + return {schema:d.schema,markings:{color:color(m.color,d.markings.color),size:number(m.size,100,50,160)},panels:{height:number(p.height,76,56,160),radius:number(p.radius,24,0,48),labelSize:number(p.labelSize,12,10,20),valueSize:number(p.valueSize,18,12,30),textColor:color(p.textColor,d.panels.textColor),glass:{...d.panels.glass,tintHex:color(g.tintHex,d.panels.glass.tintHex),tintOpacity:number(g.tintOpacity,52,0,100),blur:number(g.blur,18,0,60)}}}; +} diff --git a/apps/control-station/src/core/batteryScene/cellDisplay.ts b/apps/control-station/src/core/batteryScene/cellDisplay.ts new file mode 100644 index 00000000..7afc0f0f --- /dev/null +++ b/apps/control-station/src/core/batteryScene/cellDisplay.ts @@ -0,0 +1,12 @@ +import type {CellMarkingAppearance} from './appearance'; +export function cellDisplayIndex(name:string){const match=/^bms\/cell-display\/C(0[1-9]|1[0-3])$/.exec(name);return match?Number(match[1])-1:null;} +export function cellDisplayText(index:number,value:number|undefined){return {number:String(index+1).padStart(2,'0'),voltage:Number.isFinite(value)?`${value!.toLocaleString('ru-RU',{minimumFractionDigits:3,maximumFractionDigits:3})} В`:'— В'};} +/** One fixed composition on each existing 27 × 29 mm label face. No camera projection. */ +export function drawCellDisplay(ctx:CanvasRenderingContext2D,index:number,value:number|undefined,appearance:CellMarkingAppearance){ + const text=cellDisplayText(index,value),size=appearance.size/100; + ctx.clearRect(0,0,256,256);ctx.save();ctx.translate(128,128);ctx.scale(size,size); + ctx.fillStyle=appearance.color;ctx.textAlign='center';ctx.textBaseline='middle'; + ctx.font='600 76px sans-serif';ctx.fillText(text.number,0,-36); + ctx.font='500 40px sans-serif';ctx.fillText(text.voltage,0,46); + ctx.restore(); +} diff --git a/apps/control-station/src/core/batteryScene/profile.ts b/apps/control-station/src/core/batteryScene/profile.ts new file mode 100644 index 00000000..1a655a8a --- /dev/null +++ b/apps/control-station/src/core/batteryScene/profile.ts @@ -0,0 +1,34 @@ +import {defaultChargeGradient} from '../roverScene/chargeGradient'; +import r04 from './r04.json'; +import {defaultScene,parseScene,type SceneDocument} from '../roverScene/sceneDocument'; +import {readScene} from '../roverScene/sceneStorage'; +import type {SceneDocumentProfile} from '../roverScene/useSceneDocument'; + +export function defaultBatteryScene():SceneDocument { + return {...defaultScene(),schema:'missioncore.battery-scene/v1',model:'catl-r04/v1', + materials:{...structuredClone(r04.materials),'bms/cells':{...structuredClone(r04.materials['bms/cells']),chargeGradient:defaultChargeGradient()}},assignments:{},objects:{...r04.objects}}; +} +function database():Promise{return new Promise((resolve,reject)=>{ + const request=indexedDB.open('missioncore-battery-scenes',1); + request.onupgradeneeded=()=>request.result.createObjectStore('scenes'); + request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error); + request.onblocked=()=>reject(new Error('Хранилище батареи занято другим окном.')); +});} +async function save(id:string,document:SceneDocument){const db=await database();try{await new Promise((resolve,reject)=>{ + const tx=db.transaction('scenes','readwrite');tx.objectStore('scenes').put(document,id); + tx.oncomplete=()=>resolve();tx.onerror=()=>reject(tx.error);tx.onabort=()=>reject(tx.error); +});}finally{db.close();}} +export function batterySceneProfile(seedKey?:string):SceneDocumentProfile { + return {defaults:defaultBatteryScene,write:save,filename:'battery-r04-scene.json',read:async id=>{ + const db=await database();let raw:unknown;try{raw=await new Promise((resolve,reject)=>{ + const request=db.transaction('scenes').objectStore('scenes').get(id); + request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(request.error); + });}finally{db.close();} + if(raw)return parseScene(raw,defaultBatteryScene); + const seed=seedKey?await readScene(seedKey):null; + const doc=defaultBatteryScene(); + if(seed){doc.postFx=structuredClone(seed.postFx);doc.cameraAutoRotate=seed.cameraAutoRotate;doc.cameraZoomStrength=seed.cameraZoomStrength;} + // Copy once. Subsequent rover edits and battery edits have separate owners. + await save(id,doc);return doc; + }}; +} diff --git a/apps/control-station/src/core/batteryScene/r04.json b/apps/control-station/src/core/batteryScene/r04.json new file mode 100644 index 00000000..288208c6 --- /dev/null +++ b/apps/control-station/src/core/batteryScene/r04.json @@ -0,0 +1,501 @@ +{ + "materials": { + "bms/Cable / red silicone": { + "name": "Cable / red silicone", + "color": "#ac1922", + "metalness": 0, + "roughness": 0.47999998927116394, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Cable / graphite silicone": { + "name": "Cable / graphite silicone", + "color": "#22252a", + "metalness": 0.05000000074505806, + "roughness": 0.3700000047683716, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Mount / G10 dielectric": { + "name": "Mount / G10 dielectric", + "color": "#3e8572", + "metalness": 0, + "roughness": 0.5199999809265137, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Nickel plated copper / busbars": { + "name": "Nickel plated copper / busbars", + "color": "#c4ccd2", + "metalness": 0.8299999833106995, + "roughness": 0.27000001072883606, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Sense / warm yellow": { + "name": "Sense / warm yellow", + "color": "#f6c629", + "metalness": 0.05000000074505806, + "roughness": 0.3199999928474426, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/labels": { + "name": "Надписи", + "color": "#e5eee8", + "metalness": 0, + "roughness": 0.9, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#ffffff", + "emissiveIntensity": 0.08, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Connector / ivory polymer": { + "name": "Connector / ivory polymer", + "color": "#e4e2d2", + "metalness": 0.05000000074505806, + "roughness": 0.4000000059604645, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/BMS / green PCB": { + "name": "BMS / green PCB", + "color": "#266c50", + "metalness": 0.15000000596046448, + "roughness": 0.4000000059604645, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Aluminium / satin": { + "name": "Aluminium / satin", + "color": "#cdd6dd", + "metalness": 0.800000011920929, + "roughness": 0.3100000023841858, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Lid / insulating black": { + "name": "Lid / insulating black", + "color": "#15191e", + "metalness": 0, + "roughness": 0.6499999761581421, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Mount / adhesive film": { + "name": "Mount / adhesive film", + "color": "#6f756f", + "metalness": 0, + "roughness": 0.6200000047683716, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Steel / fasteners": { + "name": "Steel / fasteners", + "color": "#bdc4ca", + "metalness": 0.8799999952316284, + "roughness": 0.23000000417232513, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/cells": { + "name": "Ячейки · общий SOC", + "color": "#487b80", + "metalness": 0, + "roughness": 0.68, + "opacity": 0.82, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#ffffff", + "emissiveIntensity": 0.65, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Cell / wrapped lower edge": { + "name": "Cell / wrapped lower edge", + "color": "#223894", + "metalness": 0.20000000298023224, + "roughness": 0.3100000023841858, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/CASE | bead-blasted graphite": { + "name": "CASE | bead-blasted graphite", + "color": "#464a4f", + "metalness": 0.3199999928474426, + "roughness": 0.5199999809265137, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/glass": { + "name": "Прозрачная часть корпуса", + "color": "#7898a1", + "metalness": 0.05, + "roughness": 0.42, + "opacity": 0.12, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/R04 | elastomer seal": { + "name": "R04 | elastomer seal", + "color": "#121517", + "metalness": 0, + "roughness": 0.699999988079071, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/R04 | graphite moulded polymer": { + "name": "R04 | graphite moulded polymer", + "color": "#222930", + "metalness": 0, + "roughness": 0.36000001430511475, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/R04 | smoked polycarbonate": { + "name": "R04 | smoked polycarbonate", + "color": "#98aab5", + "metalness": 0, + "roughness": 0.15000000596046448, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/R04 | display protective polycarbonate": { + "name": "R04 | display protective polycarbonate", + "color": "#eef7fa", + "metalness": 0, + "roughness": 0.11999999731779099, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/DISPLAY | black glass": { + "name": "DISPLAY | black glass", + "color": "#121f23", + "metalness": 0.18000000715255737, + "roughness": 0.2199999988079071, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/CASE | recessed black": { + "name": "CASE | recessed black", + "color": "#1e2227", + "metalness": 0.11999999731779099, + "roughness": 0.5, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/CASE | darker frame": { + "name": "CASE | darker frame", + "color": "#41464c", + "metalness": 0.6499999761581421, + "roughness": 0.3199999928474426, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/CASE | dielectric liner": { + "name": "CASE | dielectric liner", + "color": "#313437", + "metalness": 0, + "roughness": 0.6499999761581421, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/Connector / gold plated contacts": { + "name": "Connector / gold plated contacts", + "color": "#d6a44a", + "metalness": 0.8500000238418579, + "roughness": 0.25, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/XT90-S / anti spark green insert": { + "name": "XT90-S / anti spark green insert", + "color": "#30a455", + "metalness": 0, + "roughness": 0.4300000071525574, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + }, + "bms/XT90-S / yellow PA housing": { + "name": "XT90-S / yellow PA housing", + "color": "#f9bd22", + "metalness": 0, + "roughness": 0.3799999952316284, + "opacity": 1, + "reflectivity": 1, + "clearCoat": 0, + "clearCoatRoughness": 0.3, + "emissive": "#000000", + "emissiveIntensity": 0, + "normalStrength": 1, + "doubleSided": true, + "tiling": 1, + "textures": {} + } + }, + "objects": { + "bms/Cable / red silicone": true, + "bms/Cable / graphite silicone": true, + "bms/Mount / G10 dielectric": true, + "bms/Nickel plated copper / busbars": true, + "bms/Sense / warm yellow": true, + "bms/labels/electronics": true, + "bms/Connector / ivory polymer": true, + "bms/BMS / green PCB": true, + "bms/Aluminium / satin": true, + "bms/Lid / insulating black": true, + "bms/Mount / adhesive film": true, + "bms/Steel / fasteners": true, + "bms/cells/C01": true, + "bms/Cell / wrapped lower edge": true, + "bms/labels/cells": true, + "bms/cell-display/C01": true, + "bms/cells/C02": true, + "bms/cell-display/C02": true, + "bms/cells/C03": true, + "bms/cell-display/C03": true, + "bms/cells/C04": true, + "bms/cell-display/C04": true, + "bms/cells/C05": true, + "bms/cell-display/C05": true, + "bms/cells/C06": true, + "bms/cell-display/C06": true, + "bms/cells/C07": true, + "bms/cell-display/C07": true, + "bms/cells/C08": true, + "bms/cell-display/C08": true, + "bms/cells/C09": true, + "bms/cell-display/C09": true, + "bms/cells/C10": true, + "bms/cell-display/C10": true, + "bms/cells/C11": true, + "bms/cell-display/C11": true, + "bms/cells/C12": true, + "bms/cell-display/C12": true, + "bms/cells/C13": true, + "bms/cell-display/C13": true, + "bms/CASE | bead-blasted graphite/CASE | base tray": true, + "bms/CASE | bead-blasted graphite/CASE | front endplate": true, + "bms/CASE | bead-blasted graphite/CASE | rear endplate": true, + "bms/glass/CASE | removable solid top": true, + "bms/glass/CASE | slotted side -1": true, + "bms/glass/CASE | slotted side 1": true, + "bms/R04 | elastomer seal": true, + "bms/R04 | graphite moulded polymer": true, + "bms/labels/enclosure": true, + "bms/R04 | smoked polycarbonate": true, + "bms/R04 | display protective polycarbonate": true, + "bms/DISPLAY | black glass": true, + "bms/CASE | recessed black": true, + "bms/CASE | darker frame": true, + "bms/CASE | bead-blasted graphite/HANDLE | folded aperture return": true, + "bms/CASE | bead-blasted graphite/HANDLE | folded aperture return.001": true, + "bms/CASE | bead-blasted graphite/HANDLE | integral web underside": true, + "bms/CASE | dielectric liner": true, + "bms/CASE | dielectric liner/left": true, + "bms/CASE | dielectric liner/right": true, + "bms/Connector / gold plated contacts": true, + "bms/XT90-S / anti spark green insert": true, + "bms/XT90-S / yellow PA housing": true + } +} diff --git a/apps/control-station/src/core/batteryScene/useBatteryAppearance.ts b/apps/control-station/src/core/batteryScene/useBatteryAppearance.ts new file mode 100644 index 00000000..16f354b2 --- /dev/null +++ b/apps/control-station/src/core/batteryScene/useBatteryAppearance.ts @@ -0,0 +1,21 @@ +import {useCallback,useEffect,useState} from 'react'; +import {SceneHistory,historyCommand} from '../roverScene/sceneHistory'; +import {batteryAppearanceKey,defaultBatteryAppearance,parseBatteryAppearance,type BatteryAppearance} from './appearance'; +export function useBatteryAppearance(id:string,active:boolean){ + const [error,setError]=useState(''); + const [history]=useState(()=>{let profile=defaultBatteryAppearance();try{const raw=localStorage.getItem(batteryAppearanceKey(id));if(raw)profile=parseBatteryAppearance(JSON.parse(raw));}catch{/* Keep the usable default if the local profile is unavailable. */}return new SceneHistory(profile);}); + const [value,setValue]=useState(history.present); + const publish=useCallback(()=>{setValue(history.present);try{localStorage.setItem(batteryAppearanceKey(id),JSON.stringify(history.present));setError('');}catch{setError('Не удалось сохранить настройки батареи на этом компьютере.');}},[history,id]); + const update=useCallback((next:BatteryAppearance)=>{if(JSON.stringify(next)!==JSON.stringify(history.present)){history.update(next);publish();}},[history,publish]); + const undo=useCallback(()=>{if(history.undo())publish();},[history,publish]); + const redo=useCallback(()=>{if(history.redo())publish();},[history,publish]); + useEffect(()=>{ + if(!active)return; + const begin=()=>history.begin(),end=()=>history.end(); + const key=(e:KeyboardEvent)=>{const command=historyCommand(e);if(command){e.preventDefault();e.stopImmediatePropagation();if(command==='undo')undo();else redo();}else if(!e.repeat&&e.key.startsWith('Arrow')&&(e.target as HTMLElement)?.closest?.('[role=slider],input[type=range]'))begin();}; + const up=(e:KeyboardEvent)=>{if(e.key.startsWith('Arrow'))end();}; + window.addEventListener('keydown',key,true);window.addEventListener('keyup',up,true);window.addEventListener('pointerdown',begin,true);window.addEventListener('pointerup',end);window.addEventListener('pointercancel',end);window.addEventListener('blur',end); + return()=>{end();window.removeEventListener('keydown',key,true);window.removeEventListener('keyup',up,true);window.removeEventListener('pointerdown',begin,true);window.removeEventListener('pointerup',end);window.removeEventListener('pointercancel',end);window.removeEventListener('blur',end);}; + },[active,history,undo,redo]); + return {value,update,undo,redo,canUndo:history.canUndo,canRedo:history.canRedo,error,setError}; +} diff --git a/apps/control-station/src/core/batteryScene/viewHeight.ts b/apps/control-station/src/core/batteryScene/viewHeight.ts new file mode 100644 index 00000000..7c000990 --- /dev/null +++ b/apps/control-station/src/core/batteryScene/viewHeight.ts @@ -0,0 +1,7 @@ +/** Local view geometry is independent of imported scene/material JSON. */ +export const minBatteryViewHeight=360,maxBatteryViewHeight=2160; +export const batteryViewHeightKey=(id:string)=>`missioncore.battery-view/v1:${encodeURIComponent(id)}`; +export function batteryViewHeight(raw:string|null,viewportHeight:number):number{ + const fallback=Math.max(minBatteryViewHeight,Math.min(900,Math.round(viewportHeight-300))); + try{const value=JSON.parse(raw??'null');return typeof value?.height==='number'&&Number.isFinite(value.height)?Math.max(minBatteryViewHeight,Math.min(maxBatteryViewHeight,Math.round(value.height))):fallback;}catch{return fallback;} +} diff --git a/apps/control-station/src/workspaces/fleet/VehicleDeviceView.tsx b/apps/control-station/src/workspaces/fleet/VehicleDeviceView.tsx new file mode 100644 index 00000000..0366cf25 --- /dev/null +++ b/apps/control-station/src/workspaces/fleet/VehicleDeviceView.tsx @@ -0,0 +1,22 @@ +import {useMemo,useState} from 'react'; +import {createPortal} from 'react-dom'; +import {Description,Icon,IconButton,LoadingRegion,SettingsCard,ToastStack} from '@nodedc/ui-react'; +import {useDevicePluginHost} from '../../core/device-plugins/DevicePluginHost'; +import {createFleetSensorTransport} from '../../core/fleet/sensorTransport'; +import type {Vehicle} from '../../core/fleet/useFleet'; +import {sensorContribution} from '../../../../../packages/sensor-ui/src/extensions'; +import {useObservationInventory} from './observation/useObservationInventory'; + +/** Equipment details own a full workspace, alongside observation and monitoring. */ +export function VehicleDeviceView({vehicle,deviceID,enabled,back,headerToolsHost,titlePrefix,headerTitleHost}:{vehicle:Vehicle;deviceID:string;enabled:boolean;back:()=>void;headerToolsHost?:HTMLElement|null;titlePrefix:string;headerTitleHost?:HTMLElement|null}){ + const {registry}=useDevicePluginHost(),transport=useMemo(()=>createFleetSensorTransport(vehicle.id),[vehicle.id]); + const {inventory,refresh}=useObservationInventory(transport); + const [error,setError]=useState(''); + const device=inventory?.items.find(item=>item.id===deviceID),contribution=device?sensorContribution(registry.sensorContributions,device):undefined; + const Detail=contribution?.Detail; + const navigation=; + return <>{headerTitleHost&&createPortal(`${titlePrefix}${device?` / ${device.name}`:""}`,headerTitleHost)}{headerToolsHost?createPortal(navigation,headerToolsHost):navigation} + {!inventory?:device&&Detail?{await refresh();}} failure={value=>setError(value instanceof Error?value.message:String(value??''))}/>:Вернитесь к оборудованию и обновите список устройств.} + setError('')}/> + ; +} diff --git a/apps/control-station/src/workspaces/fleet/VehicleFleetRow.tsx b/apps/control-station/src/workspaces/fleet/VehicleFleetRow.tsx index 1249c599..7f9cb113 100644 --- a/apps/control-station/src/workspaces/fleet/VehicleFleetRow.tsx +++ b/apps/control-station/src/workspaces/fleet/VehicleFleetRow.tsx @@ -5,13 +5,13 @@ import {boardStatus} from './BoardComputer'; import {platformLabel} from './NodeInvitationForm'; import {VehicleSensors} from './VehicleSensors'; -export function VehicleFleetRow({vehicle,available,expanded,onToggle,onObserve,onAddComputer,onBoardSettings,onMonitor,onUpdated}:{vehicle:Vehicle;available:boolean;expanded:boolean;onToggle:()=>void;onObserve:()=>void;onAddComputer:()=>void;onBoardSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){ +export function VehicleFleetRow({vehicle,available,expanded,onToggle,onObserve,onAddComputer,onBoardSettings,onMonitor,onUpdated,onDeviceView}:{vehicle:Vehicle;available:boolean;expanded:boolean;onToggle:()=>void;onObserve:()=>void;onAddComputer:()=>void;onBoardSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void;onDeviceView?:(id:string)=>void}){ const [settingsOpen,setSettingsOpen]=useState(false); const [equipmentActionsTarget,setEquipmentActionsTarget]=useState(null); const branchID=useId(); const enabled=available&&vehicle.enrollment==='paired'&&vehicle.connectivity==='online'; const label=available?boardStatus(vehicle):'Нет свежих данных'; - const sensors={vehicle,enabled,onAddComputer,onSettings:onBoardSettings,onMonitor,onUpdated}; + const sensors={vehicle,enabled,onAddComputer,onSettings:onBoardSettings,onMonitor,onUpdated,onDeviceView}; return
  • } title={vehicle.name} description={platformLabel(vehicle.platform)} metadata={label} statusPlacement="leading" status={} actions={<> {expanded&&!settingsOpen&&} diff --git a/apps/control-station/src/workspaces/fleet/VehicleSensors.tsx b/apps/control-station/src/workspaces/fleet/VehicleSensors.tsx index c26af4d7..8ac60bbb 100644 --- a/apps/control-station/src/workspaces/fleet/VehicleSensors.tsx +++ b/apps/control-station/src/workspaces/fleet/VehicleSensors.tsx @@ -7,11 +7,11 @@ import {createFleetSensorTransport} from '../../core/fleet/sensorTransport'; import type {Vehicle} from '../../core/fleet/useFleet'; import {VehicleEquipment} from './VehicleEquipment'; import {VehicleIdentitySettings} from './VehicleIdentitySettings'; -export function VehicleSensors({vehicle,enabled,mode='equipment',equipmentActionsTarget,onAddComputer,onSettings,onMonitor,onUpdated}:{vehicle:Vehicle;enabled:boolean;mode?:'equipment'|'settings';equipmentActionsTarget?:HTMLElement|null;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){ +export function VehicleSensors({vehicle,enabled,mode='equipment',equipmentActionsTarget,onAddComputer,onSettings,onMonitor,onUpdated,onDeviceView}:{vehicle:Vehicle;enabled:boolean;mode?:'equipment'|'settings';equipmentActionsTarget?:HTMLElement|null;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void;onDeviceView?:(id:string)=>void}){ const vehicleID=vehicle.id; const {registry}=useDevicePluginHost(); const sensorContributions=registry.sensorContributions; const layout=useMemo(()=>boardLayout(vehicleID),[vehicleID]); const transport=useMemo(()=>createFleetSensorTransport(vehicleID),[vehicleID]); - return mode==='settings'?
    {content.settings}
    :}/>; + return onDeviceView(device.id):undefined} sceneSeedKey={vehicleID} contributions={sensorContributions} createRerunHost={createIsolatedRerunHost} key={`${vehicleID}:${vehicle.node_id}`} transport={transport} enabled={enabled} previewEnabled={vehicle.enrollment==='paired'} readOfflineInventory detailActionsTarget={equipmentActionsTarget} renderBoard={content=>mode==='settings'?
    {content.settings}
    :}/>; } diff --git a/apps/control-station/src/workspaces/fleet/VehiclesWorkspace.tsx b/apps/control-station/src/workspaces/fleet/VehiclesWorkspace.tsx index b242e13f..f7d98179 100644 --- a/apps/control-station/src/workspaces/fleet/VehiclesWorkspace.tsx +++ b/apps/control-station/src/workspaces/fleet/VehiclesWorkspace.tsx @@ -6,13 +6,14 @@ import {BoardObservationCenter} from './observation/BoardObservationCenter'; import {BoardMonitorView} from './BoardMonitorView'; import {BoardComputerSettings} from './BoardComputer'; import {NodeInvitationForm,platformLabel} from './NodeInvitationForm'; +import {VehicleDeviceView} from './VehicleDeviceView'; import {VehicleFleetRow} from './VehicleFleetRow'; import {OperatorNetworkWindow} from '../../components/network/OperatorNetworkWindow'; import './fleet.css'; export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerToolsHost?:HTMLElement|null;headerTitleHost?:HTMLElement|null}){ const fleet=useFleet(); - const [view,setView]=useState<{vehicleID:string;mode:'observation'|'monitor'}|null>(null); + const [view,setView]=useState<{vehicleID:string;mode:'observation'|'monitor'|'device';deviceID?:string}|null>(null); const [expanded,setExpanded]=useState([]); const [adding,setAdding]=useState(); const [boardSettings,setBoardSettings]=useState(null); @@ -27,12 +28,13 @@ export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerTools const addButton=<>setOperatorNetwork(true)}>setAdding(null)}>; const headerAdd=!detail&&(headerToolsHost?createPortal(addButton,headerToolsHost):addButton); const titleSuffix=detail?` — ${detail.name} / ${platformLabel(detail.platform)}`:''; - const content=detail&&view?.mode==='observation'?setView(null)} configure={()=>showEquipment(detail.id)} headerToolsHost={headerToolsHost}/> + const content=detail&&view?.mode==='device'&&view.deviceID?showEquipment(detail.id)} headerToolsHost={headerToolsHost} titlePrefix={titleSuffix} headerTitleHost={headerTitleHost}/> + :detail&&view?.mode==='observation'?setView(null)} configure={()=>showEquipment(detail.id)} headerToolsHost={headerToolsHost}/> :detail&&view?.mode==='monitor'?showEquipment(detail.id)} headerToolsHost={headerToolsHost}/> :
    - {!fleet.items?:fleet.items.length===0?:{fleet.items.map(item=>setExpanded(current=>current.includes(item.id)?current.filter(id=>id!==item.id):[...current,item.id])} onObserve={()=>setView({vehicleID:item.id,mode:'observation'})} onAddComputer={()=>setAdding(item)} onBoardSettings={()=>setBoardSettings(item.id)} onMonitor={()=>setView({vehicleID:item.id,mode:'monitor'})} onUpdated={fleet.acceptVehicle}/>)}} + {!fleet.items?:fleet.items.length===0?:{fleet.items.map(item=>setExpanded(current=>current.includes(item.id)?current.filter(id=>id!==item.id):[...current,item.id])} onDeviceView={deviceID=>setView({vehicleID:item.id,mode:'device',deviceID})} onObserve={()=>setView({vehicleID:item.id,mode:'observation'})} onAddComputer={()=>setAdding(item)} onBoardSettings={()=>setBoardSettings(item.id)} onMonitor={()=>setView({vehicleID:item.id,mode:'monitor'})} onUpdated={fleet.acceptVehicle}/>)}}
    ; - return <>{headerTitleHost&&createPortal(titleSuffix,headerTitleHost)}{headerAdd}{content} + return <>{headerTitleHost&&view?.mode!=='device'&&createPortal(titleSuffix,headerTitleHost)}{headerAdd}{content} {operatorNetwork&&setOperatorNetwork(false)}/>} {adding!==undefined&&setAdding(undefined)} onComplete={complete} renderWindow={({content,actions,busy})=>{if(!busy)setAdding(undefined);}} footer={{actions}}>{content}}/>} {settingsVehicle&&setBoardSettings(null)} onRevoke={()=>{setBoardSettings(null);setRevoking(settingsVehicle);}}/>} diff --git a/apps/control-station/test/batteryScene.test.mjs b/apps/control-station/test/batteryScene.test.mjs new file mode 100644 index 00000000..2985ee25 --- /dev/null +++ b/apps/control-station/test/batteryScene.test.mjs @@ -0,0 +1,100 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {build} from 'esbuild'; +const load=async path=>{const result=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));}; +const {defaultBatteryScene}=await load('../src/core/batteryScene/profile.ts'); +const {defaultScene,parseScene,changeField,assignMaterial,createMaterial}=await load('../src/core/roverScene/sceneDocument.ts'); +test('battery JSON is isolated from rover JSON and preserves all editor settings',()=>{ + const rover=defaultScene();let battery=defaultBatteryScene(); + assert.deepEqual(battery.postFx,rover.postFx); + battery=changeField(battery,'postFx.lighting.exposure',1.7); + battery=createMaterial(battery,'custom/synthetic'); + battery=assignMaterial(battery,'bms/labels','custom/synthetic'); + battery.materials['bms/glass'].opacity=.25; + battery.objects[Object.keys(battery.objects)[0]]=false; + assert.deepEqual(parseScene(JSON.parse(JSON.stringify(battery)),defaultBatteryScene),battery); + assert.throws(()=>parseScene(battery));assert.throws(()=>parseScene(rover,defaultBatteryScene)); + assert.notEqual(defaultBatteryScene().materials['bms/glass'].opacity,.25); + assert.equal(rover.postFx.lighting.exposure,defaultScene().postFx.lighting.exposure); +}); +const {batteryState}=await load('../../../plugins/jk-bms/frontend/src/model.ts'); +test('stale and absent samples cannot turn into current or zero battery readings',()=>{ + const now=Date.parse('2026-11-03T10:00:00Z'),device={online:true,bms_status:{state:'streaming',fresh:true,compatible:true,sample_at:new Date(now).toISOString(),sample:{soc_percent:80}}}; + assert.equal(batteryState(device,true,now).fresh,true); + assert.equal(batteryState(device,false,now).fresh,false); + assert.equal(batteryState(device,true,now+13000).fresh,false); + assert.equal(batteryState(device,true,now+300001).sample.soc_percent,80); + assert.equal(batteryState(device,true,Date.parse('2026-11-04T00:00:00Z')).sample,null); + assert.equal(batteryState({online:false},true,now).sample,null); +}); +const {batteryViewHeight,batteryViewHeightKey}=await load('../src/core/batteryScene/viewHeight.ts'); +test('view height round trips independently per battery and rejects corrupt geometry',()=>{ + const store=new Map();store.set(batteryViewHeightKey('device/a'),JSON.stringify({height:721})); + assert.equal(batteryViewHeight(store.get(batteryViewHeightKey('device/a')),1024),721); + assert.equal(batteryViewHeight(store.get(batteryViewHeightKey('device/b'))??null,1024),724); + for(const raw of ['broken','null','{"height":"800"}','{"height":null}'])assert.equal(batteryViewHeight(raw,900),600); + assert.equal(batteryViewHeight('{"height":-100}',900),360); + assert.equal(batteryViewHeight('{"height":100000}',900),2160); +}); +const {updateChargeMaterial}=await load('../src/components/rover/playcanvas/chargeMaterial.ts'); +test('temporary disconnect holds the exact last colour and emission; expired telemetry is unknown',()=>{ + const gradient=defaultBatteryScene().materials['bms/cells'].chargeGradient; + const values=state=>{const result={};updateChargeMaterial({setParameter:(key,value)=>result[key]=value},gradient,state,3.5);return result;}; + const live=values({soc:82,fresh:true}); + assert.deepEqual(values({soc:82,fresh:false}),live); + const expired=values({soc:null,fresh:false}); + assert.equal(expired.chargeSaturation,0);assert.notDeepEqual(expired.chargeColorA,live.chargeColorA); + assert.notDeepEqual(values({soc:52,fresh:true}).chargeColorA,live.chargeColorA); +}); + +const {viewportFov,parseCameraState}=await load('../src/core/roverScene/cameraState.ts'); +test('saved camera JSON round trips and resizes preserve focal pixels without changing pose',()=>{ + const camera={pivot:{x:.1,y:.2,z:-.3},distance:1.2,azimuthDeg:-135,elevationDeg:42,referenceHeight:789}; + const doc={...defaultBatteryScene(),camera}; + assert.deepEqual(parseScene(JSON.parse(JSON.stringify(doc)),defaultBatteryScene).camera,camera); + const focal=h=>h/(2*Math.tan(viewportFov(h,camera.referenceHeight)*Math.PI/360)); + assert.ok(Math.abs(focal(360)-focal(789))<1e-9);assert.ok(Math.abs(focal(1700)-focal(789))<1e-9); + assert.equal(parseCameraState({...camera,distance:NaN}),undefined); + assert.equal(parseCameraState({...camera,pivot:{x:Infinity,y:0,z:0}}),undefined); + assert.equal(parseCameraState({...camera,distance:-1}),undefined); +}); +test('split dielectric side backers inherit existing assignment/visibility without replacing explicit child edits',()=>{ + const id=name=>'object/Model/'+encodeURIComponent('bms/CASE | dielectric liner'+name); + const doc=defaultBatteryScene(); + doc.objectAssignments={[id('')]:'bms/glass',[id('/right')]:'bms/cells'}; + doc.objectVisibility={[id('')]:false,[id('/right')]:true}; + const next=parseScene(doc,defaultBatteryScene); + assert.equal(next.objectAssignments[id('/left')],'bms/glass');assert.equal(next.objectAssignments[id('/right')],'bms/cells'); + assert.equal(next.objectVisibility[id('/left')],false);assert.equal(next.objectVisibility[id('/right')],true); + assert.equal(Object.keys(next.objects).length,63); +}); + +const {batteryAppearanceKey,defaultBatteryAppearance,parseBatteryAppearance}=await load('../src/core/batteryScene/appearance.ts'); +const {cellDisplayIndex,cellDisplayText}=await load('../src/core/batteryScene/cellDisplay.ts'); +test('battery appearance is isolated, round trips, rejects foreign JSON and bounds imported controls',()=>{ + const a=defaultBatteryAppearance(),b=defaultBatteryAppearance();a.panels.glass.tintHex='#cc3300';a.markings.size=150; + assert.deepEqual(parseBatteryAppearance(JSON.parse(JSON.stringify(a))),a); + assert.equal(b.panels.glass.tintHex,'#0b0b0e');assert.equal(b.panels.height,76); + assert.notEqual(batteryAppearanceKey('a'),batteryAppearanceKey('b')); + assert.throws(()=>parseBatteryAppearance(defaultBatteryScene())); + const bounded=parseBatteryAppearance({...a,markings:{size:500,color:'invalid'},panels:{height:-1,radius:Infinity,glass:{tintOpacity:1000,blur:-5}}}); + assert.equal(bounded.markings.size,160);assert.equal(bounded.markings.color,'#ffffff');assert.equal(bounded.panels.height,56);assert.equal(bounded.panels.radius,24);assert.equal(bounded.panels.glass.tintOpacity,100);assert.equal(bounded.panels.glass.blur,0); +}); +test('each label receives only its own measured voltage, with unknown never shown as zero',()=>{ + for(let i=0;i<13;i++)assert.equal(cellDisplayIndex(`bms/cell-display/C${String(i+1).padStart(2,'0')}`),i); + for(const bad of ['bms/cells/C01','bms/cell-display/C00','bms/cell-display/C14'])assert.equal(cellDisplayIndex(bad),null); + assert.deepEqual(cellDisplayText(12,3.456),{number:'13',voltage:'3,456 В'}); + for(const value of [undefined,NaN,Infinity])assert.equal(cellDisplayText(0,value).voltage,'— В'); +}); +import {readFileSync} from 'node:fs'; +test('R04 exports thirteen original front faces with independent materials and planar UVs',()=>{ + const glb=readFileSync(new URL('../public/battery-scene/catl-r04.glb',import.meta.url)); + const gltf=JSON.parse(glb.subarray(20,20+glb.readUInt32LE(12)).toString()); + const displays=gltf.meshes.filter(m=>cellDisplayIndex(m.name)!==null);assert.equal(displays.length,13); + const ids=new Set();for(const mesh of displays){const p=mesh.primitives[0],a=gltf.accessors[p.attributes.POSITION],uv=gltf.accessors[p.attributes.TEXCOORD_0]; + assert.equal(gltf.materials[p.material].name,mesh.name);ids.add(p.material);assert.equal(uv.count,4); + const x=(cellDisplayIndex(mesh.name)-6)*.036; + assert.ok(Math.abs((a.min[0]+a.max[0])/2-x)<1e-6);assert.ok(Math.abs((a.min[1]+a.max[1])/2-.063)<1e-6); + assert.ok(Math.abs(a.min[2]-.08664)<1e-6);assert.equal(a.min[2],a.max[2]); + }assert.equal(ids.size,13); +}); diff --git a/apps/node-agent/internal/node/sensor_bms.go b/apps/node-agent/internal/node/sensor_bms.go new file mode 100644 index 00000000..7ac53dc1 --- /dev/null +++ b/apps/node-agent/internal/node/sensor_bms.go @@ -0,0 +1,16 @@ +package node + +import "regexp" + +var bmsAddress = regexp.MustCompile(`^(?:[0-9A-F]{2}:){5}[0-9A-F]{2}$`) + +// A BLE projection belongs to the shipped service, not the USB placeholder path. +func bmsProjection(item map[string]any, model *sensorModel) bool { + if !currentCameraSnapshot(item, model) { + return false + } + status, _ := item["bms_status"].(map[string]any) + address, _ := status["address"].(string) + return status["schema"] == "missioncore.jk-bms/v1" && bmsAddress.MatchString(address) && + item["id"] == modelDeviceID(model, "public:"+address) && item["connection_mode"] == "bluetooth" +} diff --git a/apps/node-agent/internal/node/sensor_bms_test.go b/apps/node-agent/internal/node/sensor_bms_test.go new file mode 100644 index 00000000..274618ca --- /dev/null +++ b/apps/node-agent/internal/node/sensor_bms_test.go @@ -0,0 +1,27 @@ +package node + +import "testing" + +func TestBMSProjectionRequiresVersionAndStableIdentity(t *testing.T) { + model := modelForDevice("jkbms_00000000000000000000000000000000") + if model == nil { + t.Fatal("BMS model missing") + } + address := "AA:BB:CC:DD:EE:01" + item := map[string]any{ + "id": modelDeviceID(model, "public:"+address), "connection_mode": "bluetooth", + "bms_status": map[string]any{"schema": "missioncore.jk-bms/v1", "address": address}, + "snapshot": map[string]any{"revision": float64(1), "observed_at": "2026-11-03T12:00:00Z", + "context": map[string]any{"device": map[string]any{"model": map[string]any{"plugin_version": model.Version, "model_id": model.ID}}}}, + } + if !bmsProjection(item, model) { + t.Fatal("valid BLE projection rejected") + } + item["id"] = modelDeviceID(model, "public:AA:BB:CC:DD:EE:02") + if bmsProjection(item, model) { + t.Fatal("wrong physical identity accepted") + } + if len(model.Actions) != 0 || model.PrepareUnit != "" || model.Vendor != "" { + t.Fatal("BMS must remain automatic and read-only") + } +} diff --git a/apps/node-agent/internal/node/sensor_models.go b/apps/node-agent/internal/node/sensor_models.go index bb77cb73..5cd5aaa4 100644 --- a/apps/node-agent/internal/node/sensor_models.go +++ b/apps/node-agent/internal/node/sensor_models.go @@ -56,6 +56,8 @@ var sensorModels = []sensorModel{ Vendor: "04d8", Product: "0053", USBName: "USB CANFD DEBUG", Socket: "/run/mission-core-usb-can/driver.sock", PrepareUnit: "mission-core-node-usb-can-prepare.service", Report: "/var/lib/mission-core-node-profiles/usb-can/preparation.json", ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "can.status", "can.configure", "can.start", "can.stop", "can.clear", "can.transmit.preview", "can.transmit.apply", "can.transmit.stop")}, + {ID: "jk.bms", Name: "JK BMS", Prefix: "jkbms", Kind: "jk.bms", Plugin: "missioncore.jk-bms", Version: "0.1.0", + Socket: "/run/mission-core-jk-bms/driver.sock", Actions: actions()}, } func modelForDevice(id string) *sensorModel { diff --git a/apps/node-agent/internal/node/sensors.go b/apps/node-agent/internal/node/sensors.go index da5ec21d..900218ee 100644 --- a/apps/node-agent/internal/node/sensors.go +++ b/apps/node-agent/internal/node/sensors.go @@ -243,6 +243,9 @@ func (s *Sensors) Inventory() map[string]any { unsafePreparation[id] = item["preparation_safe"] == false || snapshot["acquisition"] != "idle" continue } + if model.ID == "jk.bms" && !bmsProjection(item, model) { + continue + } if model.ProtocolIdentity { if !currentCameraSnapshot(item, model) { continue diff --git a/apps/node-agent/ui/src/NodeSensors.tsx b/apps/node-agent/ui/src/NodeSensors.tsx index 7d0b2585..3f1a412e 100644 --- a/apps/node-agent/ui/src/NodeSensors.tsx +++ b/apps/node-agent/ui/src/NodeSensors.tsx @@ -1,5 +1,6 @@ import {usbCanSensorUi} from '../../../../plugins/usb-can/frontend/src/plugin'; import {vescSensorUi} from '../../../../plugins/vesc/frontend/src/plugin'; +import {jkBmsSensorUi} from '../../../../plugins/jk-bms/frontend/src/plugin'; import {xgridsK1SensorUi} from '../../../../plugins/xgrids-k1/frontend/src/sensors/plugin'; import {insta360X4SensorUi} from '../../../../plugins/insta360-x4/frontend/src/plugin'; import {createIsolatedRerunHost} from '../../../control-station/src/components/rerun/isolatedRerunHost'; @@ -12,4 +13,4 @@ import {createBoardLayoutStore} from '../../../../packages/sensor-ui/src/boardLa const layout=createBoardLayoutStore({read:()=>request('/api/presentation/board-layout'),patch:(section,open)=>request('/api/presentation/board-layout','PATCH',{section,open})}); const configurationArchive:NonNullable={list:(device,before)=>request(`/api/device-configurations/${encodeURIComponent(device)}${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>request(`/api/device-configurations/${encodeURIComponent(device)}/${encodeURIComponent(version)}`)}; const transport:SensorTransport={liveTelemetry:signal=>request('/api/devices/telemetry','GET',undefined,signal),configurationArchive,localPreview:{open:(command,signal)=>fetch("/api/devices/preview",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(command),signal}),read:(peer,after,signal)=>fetch("/api/devices/preview/read",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify({peer_id:peer,after}),signal})},enrollment:{state:()=>request("/api/devices/enrollment"),submit:value=>request("/api/devices/enrollment/operations","POST",value),operation:id=>request("/api/devices/enrollment/operations/"+encodeURIComponent(id))},subscribe:(receive,unavailable)=>{const events=new EventSource('/api/devices/events');events.onmessage=e=>{try{receive(JSON.parse(e.data));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},inventory:signal=>request('/api/devices','GET',undefined,signal),submit:value=>request('/api/devices/operations','POST',value),operation:id=>request('/api/devices/operations/'+encodeURIComponent(id))}; -export function NodeSensors({value,openSettings}:{value:Status;openSettings:()=>void}){return
    Бортовой компьютер
    {value.node_id}
    Операционная система
    {value.host.os}
    Архитектура
    {value.host.architecture}
    Процессоры
    {value.host.cpus}
    Память
    {value.host.memory_kib?`${(value.host.memory_kib/1048576).toFixed(1)} ГиБ`:"Нет сведений"}
    Mission Core Node
    {value.version}
    }} contributions={[xgridsK1SensorUi,insta360X4SensorUi,vescSensorUi,usbCanSensorUi]} createRerunHost={createIsolatedRerunHost} transport={transport}/>
    ;} +export function NodeSensors({value,openSettings}:{value:Status;openSettings:()=>void}){return
    Бортовой компьютер
    {value.node_id}
    Операционная система
    {value.host.os}
    Архитектура
    {value.host.architecture}
    Процессоры
    {value.host.cpus}
    Память
    {value.host.memory_kib?`${(value.host.memory_kib/1048576).toFixed(1)} ГиБ`:"Нет сведений"}
    Mission Core Node
    {value.version}
    }} contributions={[xgridsK1SensorUi,insta360X4SensorUi,vescSensorUi,usbCanSensorUi,jkBmsSensorUi]} createRerunHost={createIsolatedRerunHost} transport={transport}/>
    ;} diff --git a/docs/node/JK_BMS_BLUETOOTH.md b/docs/node/JK_BMS_BLUETOOTH.md new file mode 100644 index 00000000..bc58d090 --- /dev/null +++ b/docs/node/JK_BMS_BLUETOOTH.md @@ -0,0 +1,211 @@ +# JK BMS · Bluetooth equipment integration + +Owner scope: automatically show supported batteries below the onboard computer; +read-only telemetry on Node, and a battery viewport with React overlays in Core. +The battery settings, MOS switches, firmware and protection configuration are not +operator actions of this plugin. + +## Existing architecture and ownership + +Read against live Ops on 2026-11-03: [Node requirements, MISSIONCOR-76](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-76), +[USB-CAN, MISSIONCOR-90](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-90), +[K1 discovery, MISSIONCOR-95](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-95), +[X4, MISSIONCOR-77](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-77), +[governance, MISSIONCOR-50](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-50). +Battery findings and physical qualification belong to +[MISSIONCOR-96](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-96). + +The JK plugin owns BlueZ/protocol/compatibility. Node aggregates its versioned +Unix-socket inventory into the existing Plugin SDK session contract. Core uses +the paired Node channel and the existing sensor contribution registry. No new +public port, SSH product transport, fleet root or desktop BLE owner is introduced. + +## Discovery and supported profile + +`plugins/jk-bms/runtime` is one unprivileged service. It scans powered LE adapters +using its own BlueZ discovery leases; startup may enable an available adapter. +It does not alter rfkill, reset USB, pair devices or cancel another client's lease. +It never takes over an already connected peer. A 12-second discovery window is +followed by bounded connection/read deadlines; failed attempts back off to 64 s. +One connection is active at a time. After at most 120 s it returns to discovery +to admit other batteries. At most eight distinct instances are retained. + +Candidate evidence is the observed JK advertisement family: public address, +`JK_` name prefix, manufacturer `0x0B65` with `88 a0` followed by that address. +A name or FFE0 UUID by itself is insufficient. The stable ID hashes the public +hardware address, independently of name, host, USB port or `hci` number. The +strongest fresh adapter observation is selected for the next candidate. Distinct +addresses remain distinct devices; discovery does not assign a nearby battery +to a vehicle's power circuit or prove exclusive physical ownership. + +Verification requires service FFE0 and characteristic FFE1 with notify and +write-without-response, then a valid JK identity reply. The qualified telemetry +layout is **JK_BD6A17S6P / firmware 11.47**. Other JK identities remain visible +with unsupported compatibility, without requesting telemetry. This is not an +assertion that all JK models, BLE address randomization or arbitrary BMS brands +share one protocol. Additional profiles require evidence and regression fixtures. + +The only vendor requests are the observed 20-byte 0x97 identity query and 0x96 +telemetry query. StartNotify/StopNotify use the standard temporary CCCD +subscription. No parameter/settings command can be constructed. Replies require +the 300-byte frame header/checksum; fragmented notifications are reassembled in +a bounded buffer. Identity output uses a field allowlist because other offsets +contain credentials. Unknown settings frames are discarded. + +Protocol references inspected at fixed revisions: `patman15/aiobmsble` +705ea1609243bc4bcda3584e556a92077d58b5e6 and `syssi/esphome-jk-bms` +6b5a25aa43fb044c2a9592a5e87f06f8edc42554. Runtime does not install either project +or download a moving upstream branch. The existing board/mac qualification is +recorded separately in MISSIONCOR-96; synthetic tests are not radio acceptance. + +## Lifecycle and storage + +Only confirmed hardware identity is written under `/var/lib/mission-core-jk-bms`. +On Node, samples stay in bounded RAM, expire after 300 s and reset daily UTC. A connection +loss keeps the device and last sample, with `fresh=false`; a sample is current +only within 12 s while streaming. Core strips measurements from durable fleet +records and hydrates them from its bounded RAM cache. Core retains one latest snapshot per battery (at most 64 entries of 16 KiB) until the next UTC day, a Core restart, or 24 hours; null/disconnected updates do not erase it, and repeated or older observations cannot refresh its expiry. The browser retains the same UTC-day boundary and displays its original timestamp. Browser age checks cannot +turn a disconnected or expired sample green. Reconnection changes link generation +without remounting the viewer; restarting the service creates new SDK sessions. + +The standard Node package includes the runtime, service account, systemd unit, +BlueZ D-Bus policy and python3-dbus/BlueZ dependencies. Reboot needs no open UI or +manual scan. The service has no root privileges, network namespace access, +capabilities or raw device permissions. Rollback/removal stops and disables its +unit; identity is retained. The first increment is packaged over qualified +Node110 to preserve its other runtime payloads. A prepared Ubuntu24.04 amd64 +qualification is not a clean-image or multi-board physical acceptance. + +## Product surface and scene profile + +Placement approved by the owner: Fleet → vehicle → computer → battery row → eye. +Node uses the existing modal with compact telemetry and cell voltages. Core opens +a separate full equipment workspace with the same readout over the existing +PlayCanvas renderer. Back and close return to the selected vehicle equipment. +Expansion uses the same portal lifecycle as the Observatory, without a browser +fullscreen permission or a second canvas. + +The shared scene editor supplies materials, assignment, environment, light, +grid, blur, textures, camera controls and JSON import/export. The same hierarchical object tree is used for the rover and battery, with search, +selection of internal parts and per-object visibility. Select an object and a +material, then use the arrow beside the material inspector close button to +assign it. Whole palette tiles drag materials directly onto the picked mesh; +dropping outside a real model object does nothing. Stable named object paths +persist per-object assignments and visibility in the scene JSON. The pencil changes scene-edit mode; it is not a +BMS settings action. In edit mode telemetry overlays clear the model workspace. + +Battery profiles use IndexedDB `missioncore-battery-scenes`, keyed by stable +device ID; JSON schema `missioncore.battery-scene/v1`, model `catl-r04/v1`. +The first profile copies the selected vehicle's saved rover environment and +camera preferences once. Subsequent edits, reset and import are separate from +the rover. Each schema rejects the other model's JSON. Local save errors remain +visible and export remains available. Settings contain no telemetry. + +Geometry comes from the owner's `Cattle_Battery_Enclosure_R04.blend`, without +saving the source. Thirteen cell bodies are retained; enclosure glass and print +have separate materials. Engineering mesh parts are grouped into 50 render objects. Base, front, rear, +top and both slotted side panels are separate objects, so one panel can use an +independent transparent material. Old material-group assignments are retained; +legacy visibility settings migrate to the split panels. The two continuous dielectric side backers are separate left/right objects; other dielectric supports retain their existing group. Old per-object assignments and visibility migrate to both side backers unless the child already has an explicit override. +Dimensions and port geometry are a visual model, not newly verified hardware. +The flowing cell shader uses **pack SOC**, not invented individual-cell SOC. +During a temporary disconnect, the last valid SOC retains its exact gradient colours and emission; motion pauses at the last phase. Only absent/expired telemetry becomes neutral. Freshness remains explicit in the overlay; reduced-motion is respected. +Individual voltages remain numerical. Calculated power is marked as calculated; +configured capacity is not measured cell health. Unavailable temperature sensors +remain unknown; protection bytes are labelled as raw rather than guessed alarms. + +## Acceptance on 2026-11-03 + +Rover 006 was upgraded through the owner installer to Node `0.8.53-111`, release +`d05c2fc96975277d1b3a34c3`. The installer completed in 25.926 s; Node and the BMS, +K1, VESC, USB-CAN and RealSense services were active afterwards. The BMS service +is enabled and runs without root. Existing X4 `0.1.3-30` was preserved. The +installer's CAN observation was restored without motor commands. + +The battery appeared automatically in the existing Core inventory. A 90.714 s +read-only observation recorded 45 polls, four distinct fresh sample timestamps +and recovery across four link generations with the same device ID. It also +recorded disconnected/connect-failed periods: this is reconnection acceptance, +not a continuous 90-second radio stream. A subsequent visible sample at +15:40:26 UTC reported 82% SOC, 53.992 V, 13 cells, 9 mV spread and 170 cycles. + +Core UI acceptance covered the actual R04 model, fresh/stale display, shared +materials/environment/object inspectors, separate JSON import/export and local +profile save/reopen. A battery-only exposure change survived reopen while rover +exposure stayed unchanged; the test change was restored. Expand/restore and +Escape with nested inspectors were also checked. The Node login page and its +installed assets loaded through a temporary SSH forward, but the flat detail +modal was not visually accepted remotely: it requires the board's local system +login. No authentication guard was changed for that check. + +Evidence is in `outputs/bms-integration-20261103/` (installer report, prepared-host +qualification, live inventory summary and delivery report). The prepared +Ubuntu 24.04 amd64 smoke check is not clean-image or second-board acceptance. +Physical reboot acceptance, prolonged radio stability and exact cell SKU remain +open. BMS settings, MOS controls, firmware and pairing were not changed. + +## Shared object editor acceptance on 2026-11-03 + +The follow-up Core revision was checked in Chrome against the actual R04 and +rover Observatory. The BMS eye replaces the equipment workspace; back restores +the same selected vehicle. Edit mode opens the object hierarchy. An internal +C07 cell and an individual side panel were selected through the tree. The +material header arrow changed only the selected side; dragging a palette tile +onto the front panel changed only that panel. JSON exports confirmed both object +paths, persistence after reopen and no change after a drop onto empty sky. +Import of the initial profile followed by re-export matched the initial JSON +exactly, removing test assignments. Rover exposed the same tree and enabled +assignment action without applying a test edit. Expanded/restore and Escape +were checked. A final visual correction replaced long visibility labels with +canonical eye buttons so tree names remain readable. + +Validation: 1485 full unit tests, 48 focused tests after the navigation/portal +follow-up, Core production/type build, shared UI type/build checks and registry +validation. This Core-only follow-up did not install another Node release or +change BMS configuration. Evidence: `outputs/bms-scene-editor-20261103/`. + + +The follow-up editor refinement uses the canonical compact Tree in resizable +inspectors. Picking geometry reveals the selected tree row and material; empty +canvas clears selection. Cell, enclosure and electronics labels are separate +objects. The cell material exposes two colour pairs (0%/100%), interpolated by +pack SOC with configurable flowing emission. Scene document history supports +Ctrl/Cmd+Z, redo, both keyboard layouts and gesture grouping without a fixed +session step cap. Closing the scene releases history, preserving its saved +profile. Canvas wheel events exclusively control orbit zoom and prevent browser +default; other surfaces keep normal page scrolling. This same editor is used +by the rover. Final validation: 1490 unit tests, 24 focused checks and production +build; UI evidence and profile restore comparisons are consolidated in +`outputs/bms-scene-editor-20261103/`. + + +## Battery window composition + +The device name follows the vehicle/platform in the ApplicationPanel title. +One header owns back, full-window expand/restore, edit and close; the viewport +contains only edit-mode scene tools. `ApplicationPanel allowFullscreen` moves +the whole panel atomically and preserves modeless editor portals. + +Telemetry overlays use canonical `GlassMaterialSurface context="scene"` (V4 +translucent material) with interactive hit areas. Wheel over a telemetry card +scrolls the containing window; wheel over exposed canvas zooms the camera. +Seven equal compact pack metrics occupy one top row; battery-state facts occupy the bottom of the viewport. Thirteen transparent interactive labels project onto actual cell geometry and show index plus measured voltage. BMS/connection and cell count/spread remain below the viewport. + +Canonical `ResizableViewport` adjusts only height using either bottom corner +or keyboard Up/Down (Shift accelerates). Corner indicators and hover surfaces are invisible; only the cursor changes. Keyboard focus remains visible. Resize preserves orbit position and focal length in CSS pixels, changing crop instead of refitting. Height is a separate local view +preference under `missioncore.battery-view/v1:`; it survives reopening +and does not modify scene JSON, rover settings, telemetry or the BMS. The +360–2160 px range bounds corrupt storage and accidental gestures. Storage +failures are surfaced; longer views retain normal window scrolling. + + +Camera pose is part of the shared scene JSON metadata (`camera`: pivot, distance, +azimuth/elevation and referenceHeight). Completed gestures save locally; +unmount flushes even an unfinished wheel gesture. Reopen and JSON import restore +the pose. The projection reference height preserves apparent size across a +viewport height change. Battery and rover poses remain independent. + +Canonical ColorField now keeps incomplete HEX text locally. Deleting one or all +digits works; a complete six-digit value applies live. Enter/blur normalizes a +valid color or restores the last valid value; Escape cancels the draft. Scene +undo synchronizes the field alongside all other controls. diff --git a/packages/sensor-ui/src/contracts.ts b/packages/sensor-ui/src/contracts.ts index 04222b71..e02526c4 100644 --- a/packages/sensor-ui/src/contracts.ts +++ b/packages/sensor-ui/src/contracts.ts @@ -8,6 +8,7 @@ export interface Sensor { live_settings?: Record; camera_status?: Record; can_status?: Record; + bms_status?: Record; vesc_status?: Record; id: string; name: string; model: string; initializable?:boolean; preparation_safe?:boolean; prepared: boolean; configured?: boolean; verified: boolean; online: boolean; usb: string; firmware?: string; playback_id?: string | null; snapshot: {context: {session_id: string; device: {device_id: string}; execution: {node_id: string}}; acquisition: string; enrollment: string; message?: string}; diff --git a/plugins/jk-bms/frontend/src/BatteryTelemetry.tsx b/plugins/jk-bms/frontend/src/BatteryTelemetry.tsx new file mode 100644 index 00000000..455d1fe1 --- /dev/null +++ b/plugins/jk-bms/frontend/src/BatteryTelemetry.tsx @@ -0,0 +1,19 @@ +import type {CSSProperties,ComponentProps} from 'react'; +export type BatteryPanelAppearance={height:number;radius:number;labelSize:number;valueSize:number;textColor:string;glass:NonNullable['material']>}; +import {Description,GlassMaterialSurface,StatusBadge} from '@nodedc/ui-react'; +import {number,statusLabel,type BatteryState} from './model'; +export function batteryFacts(s:BatteryState['sample']){return [ + ['MOS заряда',s?(s.charge_mos_on?'Включён':'Выключен'):'—'],['MOS разряда',s?(s.discharge_mos_on?'Включён':'Выключен'):'—'], + ['Температура MOS',`${number(s?.temperature_mos_c)} °C`],['Датчик 1',`${number(s?.temperature_1_c)} °C`],['Датчик 2',`${number(s?.temperature_2_c)} °C`], + ['Ток балансировки',`${number(s?.balance_current_a,3)} А`],['Балансировка',s?(s.balance_action_raw===0?'Ожидание':s.balance_action_raw===1?'Заряд':s.balance_action_raw===2?'Разряд':'Неизвестный код'):'—'], + ['Флаги защиты · HEX',s?.protection_flags_raw??'—'],['Наработка',s?`${number(s.runtime_s/3600,1)} ч`:'—'],['Цикловая ёмкость',`${number(s?.cycle_capacity_ah,1)} А·ч`], + ];} +export function BatteryTelemetry({state,facts,appearance}:{state:BatteryState;facts:string[][];appearance?:BatteryPanelAppearance}){ + const all=[['Заряд аккумулятора',number(state.sample?.soc_percent,0),'%'],...facts]; + return
    +
    {all.map(([label,value,unit])=>{label}
    {value} {unit}
    )}
    +
    {statusLabel(state)}{state.sample_at?`Получено ${new Date(state.sample_at).toLocaleTimeString('ru-RU')}`:'Ожидаем чтение по Bluetooth'}
    +
    +
    {batteryFacts(state.sample).map(([label,value])=>{label}
    {value}
    )}
    +
    ; +} diff --git a/plugins/jk-bms/frontend/src/BmsDetail.tsx b/plugins/jk-bms/frontend/src/BmsDetail.tsx new file mode 100644 index 00000000..3fb229fc --- /dev/null +++ b/plugins/jk-bms/frontend/src/BmsDetail.tsx @@ -0,0 +1,49 @@ +import {BatteryTelemetry,batteryFacts,type BatteryPanelAppearance} from './BatteryTelemetry'; +import {useEffect,useRef,useState,type ReactNode} from 'react'; +import {Description,GlassSurface,Icon,IconButton,SettingsCard,StatusBadge,Window} from '@nodedc/ui-react'; +import type {SensorDetailProps} from '../../../../packages/sensor-ui/src/extensions'; +import {batteryState,number,statusLabel,type BatteryState} from './model'; +import './bms.css'; + +export type BatterySceneRenderer=(state:BatteryState)=>ReactNode; +export function BmsDetail({device,enabled,back,renderScene,renderViewport,panelAppearance,editing=false,presentation='window'}:SensorDetailProps&{renderScene?:BatterySceneRenderer;editing?:boolean;panelAppearance?:BatteryPanelAppearance;renderViewport?:(content:ReactNode)=>ReactNode;presentation?:'window'|'page'}){ + const [now,setNow]=useState(Date.now()),[expanded,setExpanded]=useState(false); + const expandButton=useRef(null); + useEffect(()=>{const timer=setInterval(()=>setNow(Date.now()),1000);return()=>clearInterval(timer);},[]); + const state=batteryState(device,enabled,now),s=state.sample; + const facts=[['Напряжение',number(s?.voltage_v,3),'В'],['Ток',number(s?.current_a,2),'А'],['Мощность · расчёт',number(s?.power_w,1),'Вт'], + ['Осталось',number(s?.remaining_ah,2),'А·ч'],['Ёмкость в BMS',number(s?.configured_capacity_ah,1),'А·ч'],['Циклы',number(s?.cycle_count,0),'']]; + const Panel=GlassSurface,surface={tone:'strong' as const}; + const panels=
    + Заряд аккумулятора
    {number(s?.soc_percent,0)}%
    + {statusLabel(state)} + {state.sample_at?`Получено ${new Date(state.sample_at).toLocaleTimeString('ru-RU')}`:'Ожидаем чтение по Bluetooth'} +
    {facts.map(([label,value,unit])=> + {label}
    {value} {unit}
    )}
    ; + const viewport=renderScene?<>{renderScene(state)}:null; + const content =
    + {viewport?(renderViewport?renderViewport(viewport):
    {viewport}
    ):panels} + {!editing&&<>{!state.fresh&&s&&Связь прервана или показания устарели. На экране последний полученный снимок{renderScene?'; он хранится до суточного сброса или перезапуска Core.':'.'}} + {state.state==='unsupported_firmware'&&BMS обнаружена, но эта модель или прошивка ещё не проверена. Чтение телеметрии для неё не запускается.} + {!renderScene&& +
    {s?.cell_voltages_v.map((value,i)=> + Ячейка {String(i+1).padStart(2,'0')}{number(value,3)} В)}
    +
    } +
    {!renderScene&&
    {batteryFacts(s).map(([label,value])=>
    {label}
    {value}
    )}
    } +
    {[ + ...(renderScene?[['Ячейки',s?String(s.cell_count):'—'],['Разброс ячеек',s?`${number(s.cell_delta_v*1000,0)} мВ`:'—']]:[]), + ['Модель',state.identity?.model??'Проверяется'],['Прошивка',state.identity?.firmware??'—'],['Аппаратная версия',state.identity?.hardware??'—'], + ['Bluetooth',state.address??'—'],['Адаптер борта',state.adapter??'—'],['Сигнал при обнаружении',state.rssi_dbm!=null?`${state.rssi_dbm} dBm`:'—'], + ].map(([label,value])=>
    {label}
    {value}
    )}
    + Показания доступны только для чтения. Ёмкость — настройка BMS, а не измерение состояния ячеек. + {renderScene&&Модель корпуса R04. Цвет всех ячеек отражает общий заряд батареи; индивидуальный заряд ячейки BMS не сообщает.} +
    } +
    ; + if(presentation==='page')return
    {content}
    ; + return {if(renderScene&&event.key==='Escape'&&event.currentTarget.contains(event.target as Node)){event.preventDefault();event.stopPropagation();if(expanded){setExpanded(false);expandButton.current?.focus();}else back();}}} + style={expanded?{width:'calc(100vw - 2 * var(--nodedc-space-4))',maxWidth:'none',height:'calc(100dvh - 2 * var(--nodedc-space-4))',maxHeight:'none'}:undefined} + headerActions={renderScene&&setExpanded(value=>!value)}>}> + {content} + ; +} diff --git a/plugins/jk-bms/frontend/src/bms.css b/plugins/jk-bms/frontend/src/bms.css new file mode 100644 index 00000000..d2982fdb --- /dev/null +++ b/plugins/jk-bms/frontend/src/bms.css @@ -0,0 +1,39 @@ +.bms-content{display:grid;gap:var(--nodedc-space-4)} +.bms-stage{position:relative;height:58vh;isolation:isolate;container-type:inline-size;overflow:hidden;border-radius:var(--nodedc-radius-panel)} +.bms-scene{position:absolute;inset:0} +.bms-panels{display:grid;gap:var(--nodedc-space-3)} +.bms-stage .bms-panels{position:absolute;inset:var(--nodedc-space-4) var(--nodedc-space-4) var(--nodedc-space-6,24px);pointer-events:none;grid-template-rows:auto auto;align-content:space-between} +.bms-stage .bms-charge,.bms-stage .bms-metrics{pointer-events:auto} +.bms-charge{padding:var(--nodedc-space-4);display:grid;justify-items:start;gap:var(--nodedc-space-2);width:max-content;max-width:100%} +.bms-soc{font-size:calc(var(--nodedc-font-size-lg) * 3);font-weight:var(--nodedc-font-weight-strong);font-variant-numeric:tabular-nums} +.bms-soc span{font-size:var(--nodedc-font-size-md);margin-left:var(--nodedc-space-2);color:var(--nodedc-text-secondary)} +.bms-metrics{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:var(--nodedc-space-2)} +.bms-metric{padding:var(--nodedc-space-3);display:grid;gap:var(--nodedc-space-2);font-variant-numeric:tabular-nums} +.bms-metric>div{font-size:var(--nodedc-font-size-lg);font-weight:var(--nodedc-font-weight-medium)} +.bms-metric span{font-size:var(--nodedc-font-size-sm);color:var(--nodedc-text-secondary)} +.bms-cells{display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr));gap:var(--nodedc-space-2)} +.bms-cell{padding:var(--nodedc-space-3);display:grid;gap:var(--nodedc-space-2);font-variant-numeric:tabular-nums} +.bms-details{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--nodedc-space-4)} +.bms-facts{display:grid;gap:var(--nodedc-space-3);margin:0} +.bms-facts>div{display:flex;justify-content:space-between;gap:var(--nodedc-space-4);font-size:var(--nodedc-font-size-sm)} +.bms-facts dt{color:var(--nodedc-text-secondary)} +.bms-facts dd{margin:0;text-align:right;overflow-wrap:anywhere;font-variant-numeric:tabular-nums} +.bms-scene-status{position:absolute;inset:45% var(--nodedc-space-4) auto;text-align:center} +@media(max-width:800px){.bms-details{grid-template-columns:1fr}} +@container(max-width:800px){.bms-metrics{grid-template-columns:repeat(3,minmax(0,1fr))}.bms-metric>div{font-size:var(--nodedc-font-size-md)}} +.bms-scene>.rover-view__scene{position:absolute;inset:0} +.bms-scene[data-editing=true]+.bms-panels{visibility:hidden} +.bms-scene .rover-scene-tools{right:var(--nodedc-space-3);top:var(--nodedc-space-3)} +.bms-window[data-expanded=true] .bms-stage{height:calc(100dvh - 180px)} +.bms-device-view{width:100%;min-width:0} + +.bms-panels--scene .bms-top{display:grid;gap:var(--nodedc-space-2);min-width:0} +.bms-top-metrics{display:grid;grid-template-columns:repeat(7,minmax(105px,1fr));gap:var(--nodedc-space-2);overflow-x:auto;pointer-events:auto} +.bms-panels--scene .bms-metric{padding:var(--nodedc-space-3);gap:var(--nodedc-space-1);min-width:0;min-height:var(--bms-tile-height,76px);box-sizing:border-box;align-content:center;color:var(--bms-text-color,var(--nodedc-text-primary))} +.bms-panels--scene .bms-metric>div{font-size:var(--bms-value-size,18px)} +.bms-panels--scene .bms-metric>.nodedc-description,.bms-panels--scene .bms-metric span{font-size:var(--bms-label-size,12px);color:inherit;opacity:.65} +.bms-reading-status{display:flex;align-items:center;gap:var(--nodedc-space-3);width:max-content;max-width:100%;pointer-events:auto} +.bms-status-metrics{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:var(--nodedc-space-2);pointer-events:auto} +.bms-details--scene{grid-template-columns:1fr} +@container(min-width:1400px){.bms-status-metrics{grid-template-columns:repeat(10,minmax(0,1fr))}} +@container(max-width:650px){.bms-status-metrics{display:flex;overflow-x:auto}.bms-state-metric{min-width:110px!important;flex:1 0 110px}} diff --git a/plugins/jk-bms/frontend/src/model.ts b/plugins/jk-bms/frontend/src/model.ts new file mode 100644 index 00000000..f71a762d --- /dev/null +++ b/plugins/jk-bms/frontend/src/model.ts @@ -0,0 +1,28 @@ +import type {Sensor} from '../../../../packages/sensor-ui/src/contracts'; + +export type BatterySample = { + soc_percent:number;voltage_v:number;current_a:number;power_w:number; + remaining_ah:number;configured_capacity_ah:number;cycle_count:number;cycle_capacity_ah:number; + cell_count:number;cell_voltages_v:number[];cell_delta_v:number; + charge_mos_on:boolean;discharge_mos_on:boolean;runtime_s:number;balance_current_a:number; + temperature_mos_c:number|null;temperature_1_c:number|null;temperature_2_c:number|null; + protection_flags_raw:string;balance_action_raw:number; +}; +export type BatteryState = {state:string;fresh:boolean;compatible:boolean;sample:BatterySample|null;sample_at:string|null; + address?:string;adapter?:string;rssi_dbm?:number;identity?:{model?:string;hardware?:string;firmware?:string;name?:string;manufactured_raw?:string}}; +export const number=(v:unknown,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits,minimumFractionDigits:digits}):'—'; +export function batteryState(device:Sensor,connected:boolean,now=Date.now()):BatteryState { + const raw=(device.bms_status??{}) as Partial; + const at=raw.sample_at?Date.parse(raw.sample_at):NaN; + const age=now-at; + const sample=raw.sample&&Number.isFinite(at)&&age>=-5000&&age<86400000&&new Date(at).toISOString().slice(0,10)===new Date(now).toISOString().slice(0,10)?raw.sample:null; + return {...raw,state:raw.state??'discovered',compatible:raw.compatible===true,sample,sample_at:sample?raw.sample_at??null:null, + fresh:!!(sample&&connected&&device.online&&raw.fresh&&age<12000)}; +} +export function statusLabel(state:BatteryState){ + if(state.fresh)return 'Данные поступают'; + if(state.sample)return 'Последние показания'; + if(state.state==='unsupported_firmware')return 'Версия не поддержана'; + if(state.state==='connecting'||state.state==='identifying')return 'Подключение'; + return state.identity?'Нет свежих данных':'Обнаружена · проверка BMS'; +} diff --git a/plugins/jk-bms/frontend/src/plugin.ts b/plugins/jk-bms/frontend/src/plugin.ts new file mode 100644 index 00000000..ee69a60d --- /dev/null +++ b/plugins/jk-bms/frontend/src/plugin.ts @@ -0,0 +1,8 @@ +import type {SensorUiContribution} from '../../../../packages/sensor-ui/src/extensions'; +import {BmsDetail} from './BmsDetail'; +import {batteryState,statusLabel} from './model'; + +export const jkBmsSensorUi:SensorUiContribution={ + kind:'jk.bms',Detail:BmsDetail,icon:'activity',retainOffline:true,supportsPreparation:false,supportsRenaming:false, + detailPresentation:'modal',status(device,fresh){const state=batteryState(device,fresh);return {label:statusLabel(state),tone:state.fresh?'success':state.sample?'warning':'neutral'};}, +}; diff --git a/plugins/jk-bms/packaging/mission-core-jk-bms.conf b/plugins/jk-bms/packaging/mission-core-jk-bms.conf new file mode 100644 index 00000000..1a4d3064 --- /dev/null +++ b/plugins/jk-bms/packaging/mission-core-jk-bms.conf @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/plugins/jk-bms/packaging/mission-core-jk-bms.service b/plugins/jk-bms/packaging/mission-core-jk-bms.service new file mode 100644 index 00000000..d43b8406 --- /dev/null +++ b/plugins/jk-bms/packaging/mission-core-jk-bms.service @@ -0,0 +1,40 @@ +[Unit] +Description=Mission Core JK BMS read-only Bluetooth observer +After=bluetooth.service +Wants=bluetooth.service +StartLimitIntervalSec=120 +StartLimitBurst=5 + +[Service] +Type=simple +User=mission-core-jk-bms +Group=mission-core-node +WorkingDirectory=/usr/lib/mission-core-jk-bms +ExecStart=/usr/bin/python3 -B -m runtime.server +RuntimeDirectory=mission-core-jk-bms +RuntimeDirectoryMode=0750 +StateDirectory=mission-core-jk-bms +StateDirectoryMode=0700 +UMask=0007 +Restart=on-failure +RestartSec=15 +TimeoutStopSec=20 +NoNewPrivileges=yes +CapabilityBoundingSet= +AmbientCapabilities= +PrivateNetwork=yes +PrivateDevices=yes +ProtectSystem=strict +ProtectHome=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictSUIDSGID=yes +RestrictAddressFamilies=AF_UNIX +MemoryMax=96M +TasksMax=16 +LogRateLimitIntervalSec=30s +LogRateLimitBurst=10 + +[Install] +WantedBy=multi-user.target diff --git a/plugins/jk-bms/packaging/payload.py b/plugins/jk-bms/packaging/payload.py new file mode 100644 index 00000000..176f73ad --- /dev/null +++ b/plugins/jk-bms/packaging/payload.py @@ -0,0 +1,17 @@ +"""Versioned BMS runtime and access policy shipped by the Node installer.""" + +from pathlib import Path + + +def payload(): + root = Path(__file__).resolve().parents[1] + result = [ + ("usr/lib/mission-core-jk-bms/runtime/" + p.name, p.read_bytes(), 0o644) + for p in sorted((root / "runtime").glob("*.py")) + ] + for name, target in [ + ("mission-core-jk-bms.service", "usr/lib/systemd/system/"), + ("mission-core-jk-bms.conf", "usr/share/dbus-1/system.d/"), + ]: + result.append((target + name, (root / "packaging" / name).read_bytes(), 0o644)) + return result diff --git a/plugins/jk-bms/packaging/qualify_package.py b/plugins/jk-bms/packaging/qualify_package.py new file mode 100644 index 00000000..33153d6a --- /dev/null +++ b/plugins/jk-bms/packaging/qualify_package.py @@ -0,0 +1,85 @@ +"""Bounded prepared-Ubuntu package smoke check; never installs or opens hardware.""" + +import argparse +import hashlib +import json +import os +import platform +import subprocess +import tempfile +import time +import uuid +from datetime import UTC, datetime +from pathlib import Path + + +def qualify(package, expected): + assert os.geteuid() != 0 + release = platform.freedesktop_os_release() + assert (release["ID"], release["VERSION_ID"], platform.machine()) == ( + "ubuntu", + "24.04", + "x86_64", + ) + raw = package.read_bytes() + assert hashlib.sha256(raw).hexdigest() == expected + report = dict( + schema="missioncore.bms.prepared-host-package-check/v1", + session_id=uuid.uuid4().hex, + started_at=datetime.now(UTC).isoformat(), + monotonic_started=time.monotonic(), + clean_image_qualified=False, + hardware_access=False, + checks=[], + ) + + def run(name, args, allowed=(0,), **kwargs): + result = subprocess.run(args, capture_output=True, timeout=60, **kwargs) + assert result.returncode in allowed, name + ": " + result.stderr.decode()[:300] + report["checks"].append(dict(id=name, exit_code=result.returncode)) + return result.stdout + + with tempfile.TemporaryDirectory(prefix="bms-package-", dir=package.parent) as scratch: + root = Path(scratch) + run("control", ["dpkg-deb", "-e", str(package), str(root / "control")]) + run("payload", ["dpkg-deb", "-x", str(package), str(root / "payload")]) + for name in ["postinst", "prerm"]: + run("shell-" + name, ["/bin/sh", "-n", str(root / "control" / name)]) + control = (root / "control/control").read_text() + assert "python3-dbus" in control and "bluez (>= 5.72)" in control + runtime = root / "payload/usr/lib/mission-core-jk-bms" + for path in runtime.rglob("*.py"): + compile(path.read_text(), str(path), "exec") + run( + "python-imports", + [ + "/usr/bin/python3", + "-B", + "-c", + "import runtime.protocol, runtime.service, runtime.bluez, runtime.server; " + "from gi.repository import GLib", + ], + cwd=runtime, + ) + help_text = run( + "node-executable-help", + [str(root / "payload/usr/lib/mission-core-node/node-agent"), "--help"], + allowed=(0, 1, 2), + ) + assert len(help_text) < 65536 + run("apt-simulation", ["apt-get", "--simulate", "--no-remove", "install", str(package)]) + report.update( + state="complete", + finished_at=datetime.now(UTC).isoformat(), + duration_seconds=time.monotonic() - report["monotonic_started"], + package_sha256=expected, + ) + print(json.dumps(report)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("package", type=Path) + parser.add_argument("sha256") + args = parser.parse_args() + qualify(args.package.resolve(), args.sha256) diff --git a/plugins/jk-bms/packaging/repack_node.py b/plugins/jk-bms/packaging/repack_node.py new file mode 100644 index 00000000..59aae19b --- /dev/null +++ b/plugins/jk-bms/packaging/repack_node.py @@ -0,0 +1,142 @@ +"""Add BMS to the pinned installed Node110 release, retaining other SDK payloads. + +The new Node binary embeds the rebuilt shared local UI. Full future builds use +build_deb.py; this incremental delivery preserves every unrelated installed +runtime and installer member instead of downgrading to the source baseline. +""" + +import argparse +import hashlib +import io +import json +import runpy +import sys +import tarfile +from pathlib import Path + +REPO = Path(__file__).resolve().parents[3] +NODE = REPO / "apps/node-agent" +BASE_SHA = "573280f338c833ff7cf00592d9bfb4ee292bf685fd788bae47ac5806524a497e" +VERSION = "0.8.53-111" +sys.path.insert(0, str(REPO / "scripts/packaging")) +from debian import package # noqa: E402 + + +def build(binary, output): + if output.exists(): + raise FileExistsError("Published releases are immutable") + base = NODE / "build/link-feedback-110/mission-core-node_0.8.53-110_amd64.deb" + raw = base.read_bytes() + if hashlib.sha256(raw).hexdigest() != BASE_SHA: + raise ValueError("Qualified baseline changed") + source = io.BytesIO(raw) + assert source.read(8) == b"!\n" + archives = {} + while header := source.read(60): + size = int(header[48:58]) + name = header[:16].decode().strip().rstrip("/") + archives[name] = source.read(size) + if size % 2: + source.read(1) + + def members(name): + with tarfile.open(fileobj=io.BytesIO(archives[name]), mode="r:gz") as archive: + return [(m.name, archive.extractfile(m).read(), m.mode) for m in archive if m.isfile()] + + controls, files = members("control.tar.gz"), members("data.tar.gz") + old = {name: data for name, data, _ in files} + control = dict((n, d) for n, d, _ in controls)["control"] + assert b"Version: 0.8.53-110\n" in control + control = control.replace(b"Version: 0.8.53-110\n", f"Version: {VERSION}\n".encode()) + control = control.replace(b"Depends: ", b"Depends: python3-dbus, bluez (>= 5.72), ", 1) + patched = {"control": control} + for name, data, _ in controls: + if name == "postinst": + needle = b" # Only bootstrap required" + assert needle in data + data = data.replace( + needle, + b' if ! getent passwd mission-core-jk-bms >/dev/null; then\n addu' + b'ser --system --group --home /var/lib/mission-core-jk-bms --no-create-h' + b'ome --disabled-login mission-core-jk-bms\n fi\n' + + needle, + 1, + ) + data = data.replace( + b" systemctl daemon-reload", + b' systemctl daemon-reload\n systemctl reload dbus.service\n ' + b' systemctl enable mission-core-jk-bms.service\n systemctl restart' + b' mission-core-jk-bms.service', + 1, + ) + patched[name] = data + if name == "prerm": + needle = b'case "$1" in\n upgrade|remove|deconfigure)' + assert needle in data + patched[name] = data.replace( + needle, + needle + + (b"\n if [ -d /run/systemd/system ] && " + b"[ -f /usr/lib/systemd/system/mission-core-jk-bms.service ]; then\n" + b" systemctl disable --now mission-core-jk-bms.service\n fi"), + 1, + ) + compiled = binary.read_bytes() + assert compiled[:6] == b"\x7fELF\x02\x01" and compiled[18:20] == b"\x3e\x00" + sources = [ + p + for root in [ + REPO / "plugins/jk-bms", + NODE / "internal", + NODE / "cmd", + NODE / "ui/src", + REPO / "packages/sensor-ui/src", + ] + for p in root.rglob("*") + if p.is_file() and "__pycache__" not in p.parts + ] + provenance = { + "schema": "missioncore.node.packaging-revision/v1", + "version": VERSION, + "qualified_base_sha256": BASE_SHA, + "qualified_base_provenance": json.loads( + old["usr/share/doc/mission-core-node/provenance.json"] + ), + "scope": "Read-only JK BLE discovery and bounded telemetry in the Node equipment view", + "binary_sha256": hashlib.sha256(compiled).hexdigest(), + "source_files": { + str(p.relative_to(REPO)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(sources) + }, + } + changes = { + "usr/lib/mission-core-node/node-agent": compiled, + "usr/share/doc/mission-core-node/provenance.json": ( + json.dumps(provenance, indent=2) + "\n" + ).encode(), + } + added = runpy.run_path(str(Path(__file__).with_name("payload.py")))["payload"]() + assert not any(name in old for name, _, _ in added) + controls = [(name, patched.get(name, data), mode) for name, data, mode in controls] + files = [(name, changes.get(name, data), mode) for name, data, mode in files] + added + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(package(controls, files)) + report = { + "version": VERSION, + "base_sha256": BASE_SHA, + "sha256": hashlib.sha256(output.read_bytes()).hexdigest(), + "bytes": output.stat().st_size, + "changed_controls": list(patched), + "changed_payloads": list(changes), + "added_payloads": [n for n, _, _ in added], + } + output.with_suffix(".json").write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--binary", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + build(args.binary, args.output) diff --git a/plugins/jk-bms/runtime/__init__.py b/plugins/jk-bms/runtime/__init__.py new file mode 100644 index 00000000..52784bda --- /dev/null +++ b/plugins/jk-bms/runtime/__init__.py @@ -0,0 +1,5 @@ +"""Read-only JK BLE equipment plugin. No settings or power-control operations.""" + +MODEL = "jk.bms" +VERSION = "0.1.0" +PLUGIN = "missioncore.jk-bms" diff --git a/plugins/jk-bms/runtime/bluez.py b/plugins/jk-bms/runtime/bluez.py new file mode 100644 index 00000000..4de741c2 --- /dev/null +++ b/plugins/jk-bms/runtime/bluez.py @@ -0,0 +1,252 @@ +"""One BLE owner, bounded scans and retries; no pairing, resets or settings. + +BlueZ discovery leases are per D-Bus client. Stop only this client's leases; +never disconnect an already connected peer or cancel another client's scan. +""" + +import contextlib +import time + +import dbus +from dbus.mainloop.glib import DBusGMainLoop + +from .protocol import ( + CHARACTERISTIC, + SERVICE, + Frames, + candidate, + identity, + query, + supported, + telemetry, +) + +DEVICE = "org.bluez.Device1" +ADAPTER = "org.bluez.Adapter1" +GATT = "org.bluez.GattCharacteristic1" + + +class Observer: + def __init__(self, service): + DBusGMainLoop(set_as_default=True) + self.service = service + self.bus = dbus.SystemBus() + self.scanning = set() + self.seen = {} + self.retry = {} + self.active = None + self.next_scan = 0 + self.scan_end = 0 + self.closed = False + self.bus.add_signal_receiver( + self.changed, + dbus_interface="org.freedesktop.DBus.Properties", + signal_name="PropertiesChanged", + path_keyword="path", + ) + self.bus.add_signal_receiver( + self.added, + dbus_interface="org.freedesktop.DBus.ObjectManager", + signal_name="InterfacesAdded", + ) + + def interface(self, path, interface): + return dbus.Interface(self.bus.get_object("org.bluez", path, introspect=False), interface) + + def objects(self): + return self.interface("/", "org.freedesktop.DBus.ObjectManager").GetManagedObjects( + timeout=3 + ) + + def added(self, path, interfaces): + if DEVICE in interfaces: + self.observe(str(path), interfaces[DEVICE]) + + def observe(self, path, properties): + if not candidate(properties): + return + address = str(properties["Address"]).upper() + adapter = str(properties.get("Adapter", "")) + rssi = int(properties.get("RSSI", -127)) + if self.service.observe(address, adapter.rsplit("/", 1)[-1], rssi): + self.seen[path] = (time.monotonic(), address, adapter, rssi) + + def changed(self, interface, changed, invalidated, path=None): + try: + if str(interface) == DEVICE and any(k in changed for k in ("RSSI", "ManufacturerData")): + properties = self.interface(path, "org.freedesktop.DBus.Properties").GetAll( + DEVICE, timeout=3 + ) + self.observe(str(path), properties) + a = self.active + if a and str(path) == a.get("characteristic") and "Value" in changed: + for frame in a["frames"].feed(bytes(changed["Value"])): + if frame[4] == 3: + info = identity(frame) + if not info["model"].startswith("JK_"): + self.finish("identity_mismatch") + return + self.service.identify(a["address"], info) + if not supported(info): + self.finish("unsupported_firmware", delay=300) + return + a["verified"] = True + elif frame[4] == 2 and a.get("verified"): + self.service.sample(a["address"], telemetry(frame)) + a["last_sample"] = time.monotonic() + except (dbus.DBusException, ValueError, OSError, KeyError): + self.finish("invalid_response") + + def stop_scan(self): + for path in list(self.scanning): + with contextlib.suppress(dbus.DBusException): + self.interface(path, ADAPTER).StopDiscovery(timeout=3) + self.scanning.discard(path) + + def finish(self, reason, delay=None): + a, self.active = self.active, None + if not a: + return + self.service.state(a["address"], reason) + failures = ( + 0 if a.get("last_sample") else min(self.retry.get(a["address"], (0, 0))[1] + 1, 6) + ) + self.retry[a["address"]] = ( + time.monotonic() + (delay if delay is not None else max(5, 2**failures)), + failures, + ) + try: + if a.get("notifying"): + self.interface(a["characteristic"], GATT).StopNotify(timeout=3) + except dbus.DBusException: + pass + with contextlib.suppress(dbus.DBusException): + self.interface(a["path"], DEVICE).Disconnect(timeout=3) + self.next_scan = 0 + + def write_read(self, command): + a = self.active + self.interface(a["characteristic"], GATT).WriteValue( + dbus.Array(query(command), signature="y"), + dbus.Dictionary({"type": dbus.String("command")}, signature="sv"), + timeout=3, + ) + a["last_query"] = time.monotonic() + + def tick(self): + if self.closed: + return False + self.service.expire() + try: + objects, now = self.objects(), time.monotonic() + a = self.active + if a: + properties = objects.get(a["path"], {}).get(DEVICE, {}) + if properties.get("Connected"): + a["connected"] = True + elif a.get("connected"): + self.finish("disconnected") + return True + if properties.get("ServicesResolved") and not a.get("characteristic"): + services = { + str(p) + for p, v in objects.items() + if str(p).startswith(a["path"] + "/") + and v.get("org.bluez.GattService1", {}).get("UUID") == SERVICE + } + chars = [ + str(p) + for p, v in objects.items() + if str(v.get(GATT, {}).get("Service")) in services + and v[GATT].get("UUID") == CHARACTERISTIC + and {"notify", "write-without-response"}.issubset( + set(v[GATT].get("Flags", [])) + ) + ] + if len(chars) != 1: + self.finish("unsupported_gatt", delay=300) + return True + a["characteristic"] = chars[0] + self.interface(chars[0], GATT).StartNotify(timeout=3) + a["notifying"] = True + self.service.state(a["address"], "identifying") + self.write_read(0x97) + if a.get("verified") and not a.get("requested"): + self.write_read(0x96) + a["requested"] = True + if a.get("last_query") and now - a.get("last_sample", a["last_query"]) > 12: + self.finish("read_timeout") + elif not a.get("last_sample") and now - a["started"] > 45: + self.finish("connect_timeout") + elif now - a["started"] > 120: + # Fairness: refresh discovery so a second BMS can be admitted. + self.finish("reconnecting", delay=5) + return True + if now >= self.next_scan and not self.scanning: + for path, interfaces in objects.items(): + properties = interfaces.get(ADAPTER) + if properties is None: + continue + try: + if not properties.get("Powered"): + self.interface(path, "org.freedesktop.DBus.Properties").Set( + ADAPTER, "Powered", dbus.Boolean(True), timeout=3 + ) + self.interface(path, ADAPTER).SetDiscoveryFilter( + dbus.Dictionary( + { + "Transport": dbus.String("le"), + "DuplicateData": dbus.Boolean(True), + }, + signature="sv", + ), + timeout=3, + ) + self.interface(path, ADAPTER).StartDiscovery(timeout=3) + self.scanning.add(str(path)) + except dbus.DBusException: + continue + self.scan_end, self.next_scan = now + 12, now + 20 + if self.scanning and now >= self.scan_end: + self.stop_scan() + choices = [ + (path, value) + for path, value in self.seen.items() + if now - value[0] < 20 and self.retry.get(value[1], (0, 0))[0] <= now + ] + # Never seize a peer already used by another Bluetooth client. + busy = { + str(v.get(DEVICE, {}).get("Address", "")).upper() + for v in objects.values() + if v.get(DEVICE, {}).get("Connected") + } + choices = [(p, v) for p, v in choices if v[1] not in busy] + if choices: + # Least recently attempted battery first, strongest adapter for it. + path, (_, address, adapter, rssi) = min( + choices, key=lambda row: (self.retry.get(row[1][1], (0, 0))[0], -row[1][3]) + ) + self.service.observe(address, adapter.rsplit("/", 1)[-1], rssi) + self.service.state(address, "connecting") + a = dict(path=path, address=address, started=now, frames=Frames()) + self.active = a + + def failed(error): + if self.active is a: + self.finish("connect_failed") + + self.interface(path, DEVICE).Connect( + reply_handler=lambda: None, error_handler=failed, timeout=40 + ) + self.seen = {p: v for p, v in self.seen.items() if now - v[0] < 30} + except (dbus.DBusException, ValueError, OSError, KeyError): + self.finish("bluetooth_unavailable") + self.stop_scan() + self.next_scan = time.monotonic() + 15 + return True + + def close(self): + self.closed = True + self.finish("stopped") + self.stop_scan() + self.bus.close() diff --git a/plugins/jk-bms/runtime/protocol.py b/plugins/jk-bms/runtime/protocol.py new file mode 100644 index 00000000..adbce518 --- /dev/null +++ b/plugins/jk-bms/runtime/protocol.py @@ -0,0 +1,139 @@ +"""JK02_32S profile qualified against BD6A17S6P / 11.47. + +Only 0x97 (identity) and 0x96 (telemetry subscription) can be constructed. +Never expose the raw identity frame: it contains unrelated credential fields. +""" + +import hashlib +import re + +SERVICE = "0000ffe0-0000-1000-8000-00805f9b34fb" +CHARACTERISTIC = "0000ffe1-0000-1000-8000-00805f9b34fb" +HEADER = bytes.fromhex("55aaeb90") + + +def query(command): + if type(command) is not int or command not in (0x97, 0x96): + raise ValueError("Only the two reviewed read requests are supported") + data = bytes.fromhex("aa5590eb") + bytes([command, 0]) + bytes(13) + return data + bytes([sum(data) & 255]) + + +def device_id(address): + if not re.fullmatch(r"(?:[0-9A-F]{2}:){5}[0-9A-F]{2}", address): + raise ValueError("Invalid public Bluetooth identity") + return "jkbms_" + hashlib.sha256(("public:" + address).encode()).hexdigest()[:32] + + +def candidate(properties): + """Advertisement is a candidate, never a verified model or ownership claim.""" + address = str(properties.get("Address", "")).upper() + if properties.get("AddressType") != "public" or not re.fullmatch( + r"(?:[0-9A-F]{2}:){5}[0-9A-F]{2}", address + ): + return False + manufacturer = properties.get("ManufacturerData", {}) + data = bytes(manufacturer.get(0x0B65, b"")) + return ( + str(properties.get("Name", "")).startswith("JK_") + and len(data) == 8 + and data[:2] == b"\x88\xa0" + and data[2:] == bytes.fromhex(address.replace(":", "")) + ) + + +class Frames: + def __init__(self): + self.buffer = bytearray() + self.rejected = 0 + + def feed(self, data): + if len(data) > 512: + self.buffer.clear() + self.rejected += 1 + return [] + self.buffer.extend(data) + result = [] + while len(self.buffer) >= 4: + offset = self.buffer.find(HEADER) + if offset < 0: + del self.buffer[:-3] + break + del self.buffer[:offset] + if len(self.buffer) < 300: + break + frame = bytes(self.buffer[:300]) + if sum(frame[:-1]) & 255 != frame[-1]: + del self.buffer[0] + self.rejected += 1 + continue + del self.buffer[:300] + result.append(frame) + return result + + +def identity(frame): + if len(frame) != 300 or frame[:5] != HEADER + b"\x03": + raise ValueError("Not a JK identity frame") + + def field(start, end): + return frame[start:end].split(b"\0", 1)[0].decode("ascii", "replace") + + return { + "model": field(6, 22), + "hardware": field(22, 30), + "firmware": field(30, 38), + "name": field(46, 62), + "manufactured_raw": field(78, 84), + } + + +def supported(info): + return info.get("model") == "JK_BD6A17S6P" and info.get("firmware") == "11.47" + + +def telemetry(frame): + if len(frame) != 300 or frame[:5] != HEADER + b"\x02": + raise ValueError("Not a JK telemetry frame") + + def u(offset, size=4, signed=False): + return int.from_bytes(frame[offset : offset + size], "little", signed=signed) + + mask = u(70) + count = mask.bit_count() + # Non-contiguous channel maps are not qualified by this profile. + if not 1 <= count <= 32 or mask != (1 << count) - 1: + raise ValueError("Unsupported cell map") + cells = [u(6 + i * 2, 2) / 1000 for i in range(count)] + voltage, soc = u(150) / 1000, u(173, 1) + if soc > 100 or any(not 0.5 < v < 5 for v in cells) or abs(sum(cells) - voltage) > 0.1: + raise ValueError("Inconsistent battery measurements") + + def temperature(offset, bit): + value = u(offset, 2, True) + return value / 10 if u(214, 1) & (1 << bit) and value != -2000 else None + + current = u(158, signed=True) / 1000 + return { + "voltage_v": voltage, + "current_a": current, + "soc_percent": soc, + "power_w": round(voltage * current, 3), + "power_source": "voltage_times_current", + "remaining_ah": u(174) / 1000, + "configured_capacity_ah": u(178) / 1000, + "cycle_count": u(182), + "cycle_capacity_ah": u(186) / 1000, + "cell_count": count, + "cell_voltages_v": cells, + "cell_delta_v": u(76, 2) / 1000, + "charge_mos_on": bool(u(198, 1)), + "discharge_mos_on": bool(u(199, 1)), + "runtime_s": u(194), + "balance_current_a": u(170, 2, True) / 1000, + "balance_action_raw": u(172, 1), + "protection_flags_raw": frame[166:170].hex(), + "temperature_mos_c": temperature(144, 0), + "temperature_1_c": temperature(162, 1), + "temperature_2_c": temperature(164, 2), + } diff --git a/plugins/jk-bms/runtime/server.py b/plugins/jk-bms/runtime/server.py new file mode 100644 index 00000000..5378be09 --- /dev/null +++ b/plugins/jk-bms/runtime/server.py @@ -0,0 +1,96 @@ +"""Local read-only inventory endpoint; no public port or arbitrary GATT API.""" + +import json +import os +import pwd +import re +import signal +import socket +import socketserver +import struct +import threading +from http.server import BaseHTTPRequestHandler +from pathlib import Path + +from .service import Service + + +class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): + daemon_threads = True + slots = threading.BoundedSemaphore(8) + + def process_request(self, request, address): + if not self.slots.acquire(blocking=False): + request.close() + return + super().process_request(request, address) + + def process_request_thread(self, request, address): + try: + request.settimeout(5) + super().process_request_thread(request, address) + finally: + self.slots.release() + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + _, uid, _ = struct.unpack( + "3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12) + ) + node = self.headers.get("X-Node-Id", "") + if uid != self.server.node_uid or not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node): + self.send_error(403) + return + if self.path != "/inventory": + self.send_error(404) + return + payload = json.dumps(self.server.service.inventory(node), allow_nan=False).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + +def main(): + if os.geteuid() == 0: + raise SystemExit("BMS runtime must use its service account") + from gi.repository import GLib + + from .bluez import Observer + + service = Service() + observer = Observer(service) + path = Path("/run/mission-core-jk-bms/driver.sock") + path.unlink(missing_ok=True) + server = Server(str(path), Handler) + server.node_uid = pwd.getpwnam("mission-core-node").pw_uid + server.service = service + os.chmod(path, 0o660) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + loop = GLib.MainLoop() + + def stop(): + loop.quit() + return False + + for signum in (signal.SIGTERM, signal.SIGINT): + GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signum, stop) + GLib.timeout_add(1000, observer.tick) + try: + loop.run() + finally: + observer.close() + server.shutdown() + server.server_close() + thread.join(timeout=6) + path.unlink(missing_ok=True) + + +if __name__ == "__main__": + main() diff --git a/plugins/jk-bms/runtime/service.py b/plugins/jk-bms/runtime/service.py new file mode 100644 index 00000000..077371cf --- /dev/null +++ b/plugins/jk-bms/runtime/service.py @@ -0,0 +1,171 @@ +"""Bounded latest telemetry in RAM; only confirmed identity survives restart.""" + +import copy +import json +import os +import threading +import time +import uuid +from datetime import UTC, datetime +from pathlib import Path + +from . import MODEL, PLUGIN, VERSION +from .protocol import device_id, supported + + +def utc(): + return datetime.now(UTC).isoformat() + + +class Service: + def __init__(self, root="/var/lib/mission-core-jk-bms", clock=time.monotonic): + self.root, self.clock = Path(root), clock + self.lock = threading.RLock() + self.instance = "jkbms_" + uuid.uuid4().hex + self.devices = {} + self.revision = 0 + self.day = datetime.now(UTC).date() + for path in sorted(self.root.glob("jkbms_*.json"))[:8]: + try: + data = json.loads(path.read_text()) + if path.name != device_id(data["address"]) + ".json": + continue + self.observe(data["address"], None, None) + self.devices[data["address"]]["identity"] = data["identity"] + except (ValueError, KeyError, OSError): + continue + + def observe(self, address, adapter, rssi): + with self.lock: + if address not in self.devices: + if len(self.devices) >= 8: + return False + self.devices[address] = dict( + id=device_id(address), + session="jkbms_" + uuid.uuid4().hex, + opened=utc(), + identity=None, + sample=None, + sample_at=None, + sampled=0, + state="discovered", + adapter=None, + rssi_dbm=None, + link_generation=0, + ) + d = self.devices[address] + d.update(adapter=adapter, rssi_dbm=rssi) + self.revision += 1 + return True + + def state(self, address, state): + with self.lock: + self.devices[address]["state"] = state + if state == "connecting": + self.devices[address]["link_generation"] += 1 + self.revision += 1 + + def identify(self, address, info): + with self.lock: + d = self.devices[address] + d["identity"] = copy.deepcopy(info) + self.root.mkdir(parents=True, exist_ok=True) + destination = self.root / (d["id"] + ".json") + temporary = destination.with_suffix(".tmp") + # Only allowlisted metadata, never frames, credentials or measurements. + temporary.write_text(json.dumps({"address": address, "identity": info})) + os.chmod(temporary, 0o600) + os.replace(temporary, destination) + self.revision += 1 + + def sample(self, address, sample): + with self.lock: + self.expire() + self.devices[address].update( + sample=copy.deepcopy(sample), + sample_at=utc(), + sampled=self.clock(), + state="streaming", + ) + self.revision += 1 + + def expire(self): + with self.lock: + self._expire() + + def _expire(self): + today = datetime.now(UTC).date() + for d in self.devices.values(): + if today != self.day or self.clock() - d["sampled"] >= 300: + d.update(sample=None, sample_at=None) + self.day = today + + def inventory(self, node): + with self.lock: + self.expire() + items = [] + for address, d in self.devices.items(): + info = d["identity"] or {} + fresh = d["sample"] is not None and self.clock() - d["sampled"] < 12 + online = d["state"] == "streaming" and fresh + status = { + k: copy.deepcopy(d[k]) + for k in ( + "state", + "identity", + "sample", + "sample_at", + "adapter", + "rssi_dbm", + "link_generation", + ) + } + status.update( + schema="missioncore.jk-bms/v1", + address=address, + fresh=online, + compatible=supported(info), + sample_ttl_s=300, + ) + items.append( + dict( + id=d["id"], + kind=MODEL, + name=info.get("name") or "JK BMS", + model=info.get("model") or "JK BMS · обнаружена", + firmware=info.get("firmware"), + initializable=False, + prepared=True, + configured=bool(info), + verified=supported(info), + online=online, + usb="", + connection_mode="bluetooth", + connection_label="Bluetooth LE", + layers=[], + bms_status=status, + snapshot=dict( + context=dict( + session_id=d["session"], + device=dict( + device_id=d["id"], + model=dict( + plugin_id=PLUGIN, plugin_version=VERSION, model_id=MODEL + ), + stability="stable", + basis="hardware-identifier", + ), + execution=dict( + node_id=node, agent_instance_id=self.instance, platform="linux" + ), + opened_at=d["opened"], + ), + revision=self.revision, + observed_at=utc(), + enrollment="enrolled" if info else "empty", + acquisition="idle", + connectivity="connected" if online else "degraded", + ), + ) + ) + return {"items": items} diff --git a/plugins/jk-bms/tests/test_bluez.py b/plugins/jk-bms/tests/test_bluez.py new file mode 100644 index 00000000..f8143e51 --- /dev/null +++ b/plugins/jk-bms/tests/test_bluez.py @@ -0,0 +1,143 @@ +"""Exercise the actual observer against synthetic D-Bus objects, without BLE.""" + +import importlib +import importlib.util +import sys +import types +import uuid +from pathlib import Path + +import pytest + + +@pytest.fixture +def observer(monkeypatch, tmp_path): + package = "jk_observer_test_" + uuid.uuid4().hex + root = Path(__file__).resolve().parents[1] / "runtime" + spec = importlib.util.spec_from_file_location( + package, root / "__init__.py", submodule_search_locations=[str(root)] + ) + module = importlib.util.module_from_spec(spec) + monkeypatch.setitem(sys.modules, spec.name, module) + spec.loader.exec_module(module) + calls, objects = [], {} + + class Proxy: + def __init__(self, path): + self.path = path + + def __getattr__(self, name): + def call(*args, **kwargs): + calls.append((self.path, name, args)) + if name == "GetManagedObjects": + return objects + if name == "GetAll": + return objects[self.path][args[0]] + + return call + + class Bus: + def get_object(self, destination, path, **kwargs): + assert destination == "org.bluez" and kwargs.get("introspect") is False + return Proxy(path) + + def add_signal_receiver(self, *args, **kwargs): + pass + + dbus = types.ModuleType("dbus") + dbus.DBusException = type("DBusException", (Exception,), {}) + dbus.SystemBus = Bus + dbus.Interface = lambda obj, interface: obj + dbus.Array = lambda value, **kwargs: value + dbus.Dictionary = lambda value, **kwargs: value + dbus.Boolean, dbus.String = bool, str + monkeypatch.setitem(sys.modules, "dbus", dbus) + monkeypatch.setitem(sys.modules, "dbus.mainloop", types.ModuleType("dbus.mainloop")) + glib = types.ModuleType("dbus.mainloop.glib") + glib.DBusGMainLoop = lambda **kwargs: None + monkeypatch.setitem(sys.modules, "dbus.mainloop.glib", glib) + runtime = importlib.import_module(package + ".bluez") + service = importlib.import_module(package + ".service").Service(tmp_path) + now = [100.0] + monkeypatch.setattr(runtime.time, "monotonic", lambda: now[0]) + obj = runtime.Observer(service) + adapter, peer = "/org/bluez/hci5", "/org/bluez/hci5/dev_AA_BB_CC_DD_EE_01" + props = { + "Name": "JK_synthetic", + "Address": "AA:BB:CC:DD:EE:01", + "AddressType": "public", + "ManufacturerData": {0x0B65: bytes.fromhex("88a0aabbccddee01")}, + "Adapter": adapter, + "RSSI": -65, + } + objects[adapter] = {runtime.ADAPTER: {"Powered": True}} + objects[peer] = {runtime.DEVICE: props} + objects[peer + "/service"] = {"org.bluez.GattService1": {"UUID": runtime.SERVICE}} + objects[peer + "/char"] = { + runtime.GATT: { + "Service": peer + "/service", + "UUID": runtime.CHARACTERISTIC, + "Flags": ["notify", "write-without-response"], + } + } + return obj, runtime, objects, props, calls, now, peer + + +def start(observer): + obj, runtime, objects, props, calls, now, peer = observer + obj.tick() + obj.added(peer, {runtime.DEVICE: props}) + now[0] = 113 + obj.tick() + props.update(Connected=True, ServicesResolved=True) + obj.tick() + + +def info(version): + data = bytearray(300) + data[:5] = bytes.fromhex("55aaeb9003") + data[6:18] = b"JK_BD6A17S6P" + data[30:35] = version + data[-1] = sum(data[:-1]) & 255 + return bytes(data) + + +def test_verification_precedes_telemetry_request(observer): + start(observer) + obj, runtime, objects, props, calls, now, peer = observer + def writes(): + return [args[0][4] for _, name, args in calls if name == "WriteValue"] + assert writes() == [0x97] + obj.changed(runtime.GATT, {"Value": info(b"11.47")}, [], path=peer + "/char") + obj.tick() + assert writes() == [0x97, 0x96] + props["Connected"] = False + obj.tick() + assert obj.active is None + assert any(name == "StopNotify" for _, name, _ in calls) + assert writes() == [0x97, 0x96] + + +def test_unsupported_firmware_never_requests_telemetry(observer): + start(observer) + obj, runtime, objects, props, calls, now, peer = observer + obj.changed(runtime.GATT, {"Value": info(b"14.00")}, [], path=peer + "/char") + assert obj.active is None + assert [args[0][4] for _, name, args in calls if name == "WriteValue"] == [0x97] + assert ( + obj.service.inventory("synthetic")["items"][0]["bms_status"]["state"] + == "unsupported_firmware" + ) + + +def test_foreign_connection_is_never_taken_over(observer): + obj, runtime, objects, props, calls, now, peer = observer + props["Connected"] = True + obj.tick() + obj.added(peer, {runtime.DEVICE: props}) + now[0] = 113 + obj.tick() + assert obj.active is None + assert not any( + name in {"Connect", "Disconnect", "WriteValue", "StartNotify"} for _, name, _ in calls + ) diff --git a/plugins/jk-bms/tests/test_bms.py b/plugins/jk-bms/tests/test_bms.py new file mode 100644 index 00000000..4c493928 --- /dev/null +++ b/plugins/jk-bms/tests/test_bms.py @@ -0,0 +1,143 @@ +"""Synthetic protocol and inventory checks; never opens a radio.""" + +# ruff: noqa: E402 +import importlib.util +import json +import sys +from pathlib import Path + +import pytest +from missioncore_plugin_sdk.v0alpha2 import DeviceSessionSnapshot + +root = Path(__file__).resolve().parents[1] / "runtime" +spec = importlib.util.spec_from_file_location( + "jkbms_test_runtime", root / "__init__.py", submodule_search_locations=[str(root)] +) +module = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = module +spec.loader.exec_module(module) +from jkbms_test_runtime.protocol import ( + HEADER, + Frames, + candidate, + device_id, + identity, + query, + supported, + telemetry, +) +from jkbms_test_runtime.service import Service + + +def frame(): + data = bytearray(300) + data[:5] = HEADER + b"\x02" + + def put(offset, value, size=4, signed=False): + data[offset : offset + size] = value.to_bytes(size, "little", signed=signed) + + for n in range(13): + put(6 + n * 2, 4100, 2) + put(70, (1 << 13) - 1) + put(150, 53300) + put(158, -2000, signed=True) + put(173, 80, 1) + put(174, 94400) + put(178, 118000) + put(182, 170) + put(214, 3, 1) + put(144, 251, 2) + put(162, 270, 2) + put(164, 1000, 2) + data[-1] = sum(data[:-1]) & 255 + return bytes(data) + + +def test_fragmentation_resync_checksum_and_bounded_buffer(): + raw = frame() + for split in range(1, 300): + parser = Frames() + assert parser.feed(b"noise" + raw[:split]) == [] + assert parser.feed(raw[split:]) == [raw] + parser = Frames() + damaged = raw[:90] + bytes([raw[90] ^ 1]) + raw[91:] + assert parser.feed(damaged) == [] + assert parser.feed(raw) == [raw] + assert parser.rejected == 1 + parser.feed(b"x" * 100000) + assert len(parser.buffer) < 300 + + +def test_only_reviewed_requests_and_temperature_presence(): + assert query(0x97).hex() == "aa5590eb97000000000000000000000000000011" + assert query(0x96).hex() == "aa5590eb96000000000000000000000000000010" + for value in (0, 1, 0x98, True, "0x97"): + with pytest.raises(ValueError): + query(value) + sample = telemetry(frame()) + assert sample["cell_count"] == 13 and sample["voltage_v"] == 53.3 + assert sample["current_a"] == -2 and sample["power_w"] == -106.6 + assert sample["temperature_mos_c"] == 25.1 and sample["temperature_2_c"] is None + bad = bytearray(frame()) + bad[173] = 101 + with pytest.raises(ValueError): + telemetry(bad) + bad = bytearray(frame()) + bad[70:74] = b"\x05\x00\x00\x00" + with pytest.raises(ValueError): + telemetry(bad) + + +def test_identity_allowlist_and_candidate_are_not_compatibility(): + data = bytearray(300) + data[:5] = HEADER + b"\x03" + data[6:18] = b"JK_BD6A17S6P" + data[30:35] = b"11.47" + data[90:96] = b"SECRET" + info = identity(data) + assert supported(info) and "SECRET" not in json.dumps(info) + assert not supported({**info, "firmware": "14.00"}) + props = { + "Name": "JK_synthetic", + "Address": "AA:BB:CC:DD:EE:01", + "AddressType": "public", + "ManufacturerData": {0x0B65: bytes.fromhex("88a0aabbccddee01")}, + } + assert candidate(props) + for change in ( + {"Name": "other"}, + {"ManufacturerData": {}}, + {"AddressType": "random"}, + {"Address": "AA:BB:CC:DD:EE:02"}, + ): + assert not candidate({**props, **change}) + + +def test_multiple_instances_restart_stale_and_no_disk_measurements(tmp_path): + now = [10] + service = Service(tmp_path, clock=lambda: now[0]) + address = "AA:BB:CC:DD:EE:01" + service.observe(address, "hci7", -70) + service.identify(address, {"model": "JK_BD6A17S6P", "firmware": "11.47"}) + service.sample(address, telemetry(frame())) + first = service.inventory("synthetic-node")["items"][0] + DeviceSessionSnapshot.model_validate(first["snapshot"]) + assert first["online"] + service.state(address, "disconnected") + service.observe(address, "hci9", -75) + second = service.inventory("synthetic-node")["items"][0] + assert ( + second["id"] == first["id"] + and second["snapshot"]["context"] == first["snapshot"]["context"] + ) + assert second["bms_status"]["sample"] and not second["online"] + for index in range(2, 11): + service.observe(f"AA:BB:CC:DD:EE:{index:02X}", "hci9", -65) + assert len(service.inventory("synthetic-node")["items"]) == 8 + assert device_id(address) != device_id("AA:BB:CC:DD:EE:02") + raw = next(tmp_path.glob("*.json")).read_text() + assert "sample" not in raw and "voltage" not in raw and "53300" not in raw + restored = Service(tmp_path).inventory("synthetic-node")["items"][0] + assert restored["id"] == first["id"] and restored["bms_status"]["sample"] is None + now[0] = 311 + assert service.inventory("synthetic-node")["items"][0]["bms_status"]["sample"] is None diff --git a/src/k1link/fleet/registry.py b/src/k1link/fleet/registry.py index 05d79e9f..af6b0252 100644 --- a/src/k1link/fleet/registry.py +++ b/src/k1link/fleet/registry.py @@ -454,6 +454,7 @@ class FleetRegistry: "Повторяем до истечения приглашения." ) self.save(row) + sensor_transient(self).prune() self.stop.wait(2) def receive(self, certificate: bytes, path: str, value: dict, *, address: str | None = None): diff --git a/src/k1link/fleet/sensor_transient.py b/src/k1link/fleet/sensor_transient.py index 4d702aaf..9f5f3cd1 100644 --- a/src/k1link/fleet/sensor_transient.py +++ b/src/k1link/fleet/sensor_transient.py @@ -9,6 +9,7 @@ import json import threading import time from collections import OrderedDict +from contextlib import suppress from datetime import UTC, datetime from functools import wraps @@ -31,14 +32,19 @@ class SensorTransient: self.clock, self.day = clock, day self.date = day() self.entries = OrderedDict() + self.bms = OrderedDict() self.lock = threading.RLock() @synchronized def prune(self): if self.day() != self.date: self.entries.clear() + self.bms.clear() self.date = self.day() now = self.clock() + for key, (at, _) in list(self.bms.items()): + if now - at >= 86400: + del self.bms[key] for key, (at, _, _) in list(self.entries.items()): if now - at >= 300: del self.entries[key] @@ -47,6 +53,42 @@ class SensorTransient: def persist(self, row): self.prune() result = dict(row) + if "sensor_state" in row: + items = [] + for source in row["sensor_state"].get("items", []): + item = dict(source) + if item.get("kind") == "jk.bms": + status = dict(item.get("bms_status") or {}) + key = (row["id"], item["id"]) + previous = self.bms.get(key) + retained = json.loads(previous[1])["bms_status"] if previous else {} + # One latest observation per device, RAM only. A disconnect is + # not a new observation and cannot erase or rejuvenate it. + old_at = retained.get("sample_at") + new_at = status.get("sample_at") + older = False + with suppress(ValueError, TypeError): + older = bool( + old_at and new_at + and datetime.fromisoformat(new_at) < datetime.fromisoformat(old_at) + ) + same = previous and old_at == new_at + if previous and (status.get("sample") is None or older): + status.update(sample=retained.get("sample"), sample_at=old_at, fresh=False) + same = True + if status.get("sample") is not None: + raw = json.dumps( + {"bms_status": status, "online": item.get("online", False)}, + allow_nan=False, + ).encode() + if len(raw) <= 16384: + self.bms[key] = (previous[0] if same else self.clock(), raw) + status.update(sample=None, sample_at=None, fresh=False, rssi_dbm=None) + item.update(bms_status=status, online=False) + items.append(item) + result["sensor_state"] = {**row["sensor_state"], "items": items} + while len(self.bms) > 64: + self.bms.popitem(last=False) operations = dict(row.get("sensor_commands", {})) for key, value in operations.items(): command = value.get("command", {}) @@ -76,6 +118,10 @@ class SensorTransient: @synchronized def hydrate(self, row): self.prune() + for item in row.get("sensor_state", {}).get("items", []): + cached = self.bms.get((row["id"], item.get("id"))) + if item.get("kind") == "jk.bms" and cached: + item.update(json.loads(cached[1])) for key, value in list(row.get("sensor_commands", {}).items()): if not value.get("ephemeral_expired"): continue diff --git a/tests/fleet/test_bms_transient.py b/tests/fleet/test_bms_transient.py new file mode 100644 index 00000000..ae777811 --- /dev/null +++ b/tests/fleet/test_bms_transient.py @@ -0,0 +1,68 @@ +import copy +import json + +from k1link.fleet.sensor_transient import SensorTransient + + +def test_bms_inventory_never_persists_measurements_and_repeated_saves_do_not_extend_expiry(): + now = [0] + cache = SensorTransient(clock=lambda: now[0]) + row = { + "id": "vehicle", + "sensor_state": { + "items": [ + { + "id": "battery", + "kind": "jk.bms", + "online": True, + "bms_status": { + "identity": {"model": "JK"}, + "sample": {"voltage_v": 53.3}, + "sample_at": "synthetic-time", + "fresh": True, + "rssi_dbm": -65, + }, + } + ] + }, + } + saved = cache.persist(row) + assert "voltage_v" not in json.dumps(saved) + assert not saved["sensor_state"]["items"][0]["online"] + assert cache.hydrate(copy.deepcopy(saved)) == row + assert SensorTransient().hydrate(copy.deepcopy(saved)) == saved + now[0] = 86399 + cache.persist(row) + now[0] = 86401 + assert cache.hydrate(copy.deepcopy(saved)) == saved + + +def test_bms_disconnect_retains_latest_until_daily_reset_without_disk_measurements(): + now, day = [0], [1] + cache = SensorTransient(clock=lambda: now[0], day=lambda: day[0]) + + def row(sample, at, vehicle="v"): + return {"id": vehicle, "sensor_state": {"items": [{ + "id": "b", "kind": "jk.bms", "online": sample is not None, + "bms_status": {"sample": sample, "sample_at": at, "fresh": True}, + }]}} + + def status_of(value): + return cache.hydrate(copy.deepcopy(value))["sensor_state"]["items"][0]["bms_status"] + + latest = row({"soc_percent": 82}, "2026-11-03T10:00:00+00:00") + cache.persist(latest) + now[0] = 600 + saved = cache.persist(row(None, None)) + assert "soc_percent" not in json.dumps(saved) + status = status_of(saved) + assert status["sample"]["soc_percent"] == 82 + assert status["sample_at"] == "2026-11-03T10:00:00+00:00" + assert status["fresh"] is False + cache.persist(row({"soc_percent": 81}, "2026-11-03T09:00:00+00:00")) + assert status_of(saved)["sample"]["soc_percent"] == 82 + cache.persist(row({"soc_percent": 83}, "2026-11-03T11:00:00+00:00")) + assert status_of(saved)["sample"]["soc_percent"] == 83 + assert status_of(row(None, None, "other"))["sample"] is None + day[0] = 2 + assert cache.hydrate(copy.deepcopy(saved)) == saved diff --git a/tools/battery-scene/export_battery.py b/tools/battery-scene/export_battery.py new file mode 100644 index 00000000..b00d4674 --- /dev/null +++ b/tools/battery-scene/export_battery.py @@ -0,0 +1,156 @@ +"""Export R04 geometry without saving or modifying its authoritative .blend. + +Run with Blender --background --python this.py -- . +Collapse tiny engineering parts by material for the operator viewport; retain +thirteen cell bodies, thirteen original cell label faces with distinct dynamic +material IDs, and separate static printed labels. +""" + +import hashlib +import json +import sys +from pathlib import Path + +import bpy + +output = Path(sys.argv[sys.argv.index("--") + 1]) +scene = bpy.context.scene +scene.frame_set(1) +depsgraph = bpy.context.evaluated_depsgraph_get() +roots = [c for c in bpy.data.collections if c.name == "IN" or c.name.startswith("OUT |")] +if len(roots) != 2: + raise ValueError("Expected R04 IN / OUT collection structure") +objects = set(o for c in roots for o in c.all_objects) +outer_objects = set(o for c in roots if c.name.startswith("OUT |") for o in c.all_objects) +groups = {} +for obj in sorted(objects, key=lambda o: o.name): + if obj.type not in {"MESH", "CURVE", "FONT"} or obj.hide_render: + continue + # Replace only the two static glyph objects on each original side label. + cell = next( + (c.name[:3] for c in obj.users_collection if c.name.startswith("C") and "| cell" in c.name), + None, + ) + if cell and obj.name in {cell + " Side index", cell + " Side note"}: + continue + display = cell is not None and obj.name == cell + " Side index label" + evaluated = obj.evaluated_get(depsgraph) + mesh = evaluated.to_mesh() + if mesh is None: + continue + matrix = obj.matrix_world + for polygon in mesh.polygons: + # Keep the existing outward face, in its original world position. + if display and (matrix.to_3x3() @ polygon.normal).y > -0.99: + continue + material = mesh.materials[polygon.material_index] if mesh.materials else None + name = material.name if material else "default" + label = obj.type == "FONT" or name.startswith(("PRINT", "Print")) + glass = name == "CASE | bead-blasted graphite" and any( + c.name.startswith(("02 |", "03 |")) for c in obj.users_collection + ) + role = ( + "bms/labels" + if label + else "bms/cells" + if name == "Cell / blue polymer sleeve" + else "bms/glass" + if glass + else "bms/" + name + ) + part = ( + ("cells" if cell else "enclosure" if obj in outer_objects else "electronics") + if label + else cell + if role == "bms/cells" + else obj.name + if name == "CASE | bead-blasted graphite" + else None + ) + if name == "CASE | dielectric liner" and obj.name.startswith("SLOT BACKER |"): + part = "left" if obj.name.endswith(" -1") else "right" + if display: + role, part = "bms/cell-display/" + cell, None + key = (role, part) + group = groups.setdefault( + key, {"vertices": [], "faces": [], "smooth": [], "material": material, "indices": {}} + ) + face = [] + for index in polygon.vertices: + vertex_key = (obj.name, index) + if vertex_key not in group["indices"]: + group["indices"][vertex_key] = len(group["vertices"]) + group["vertices"].append(tuple(matrix @ mesh.vertices[index].co)) + face.append(group["indices"][vertex_key]) + group["faces"].append(face) + group["smooth"].append(polygon.use_smooth) + evaluated.to_mesh_clear() + +bpy.ops.object.select_all(action="DESELECT") +collection = bpy.data.collections.new("Mission Core battery export") +scene.collection.children.link(collection) +materials = {} +for (role, cell), data in groups.items(): + if role not in materials: + material = data["material"].copy() if data["material"] else bpy.data.materials.new(role) + material.name = role + materials[role] = material + mesh = bpy.data.meshes.new(role + ("/" + cell if cell else "")) + mesh.from_pydata(data["vertices"], [], data["faces"]) + mesh.materials.append(materials[role]) + for polygon, smooth in zip(mesh.polygons, data["smooth"], strict=True): + polygon.use_smooth = smooth + obj = bpy.data.objects.new(mesh.name, mesh) + collection.objects.link(obj) + obj.select_set(True) +# A deterministic cube UV layout makes the shared texture controls useful. +export_objects = list(collection.objects) +bpy.ops.object.select_all(action="DESELECT") +for obj in export_objects: + if obj.name.startswith("bms/cell-display/"): + uv = obj.data.uv_layers.new(name="Cell display UV") + xs = [v.co.x for v in obj.data.vertices] + zs = [v.co.z for v in obj.data.vertices] + for polygon in obj.data.polygons: + for loop in polygon.loop_indices: + co = obj.data.vertices[obj.data.loops[loop].vertex_index].co + uv.data[loop].uv = ( + (co.x - min(xs)) / (max(xs) - min(xs)), + (co.z - min(zs)) / (max(zs) - min(zs)), + ) + continue + obj.select_set(True) + bpy.context.view_layer.objects.active = obj + bpy.ops.object.mode_set(mode="EDIT") + bpy.ops.mesh.select_all(action="SELECT") + bpy.ops.uv.cube_project(cube_size=0.1) + bpy.ops.object.mode_set(mode="OBJECT") + obj.select_set(False) +for obj in export_objects: + obj.select_set(True) +output.parent.mkdir(parents=True, exist_ok=True) +bpy.ops.export_scene.gltf( + filepath=str(output), + export_format="GLB", + use_selection=True, + export_animations=False, + export_extras=False, + export_cameras=False, + export_lights=False, +) +report = { + "source": Path(bpy.data.filepath).name, + "source_sha256": hashlib.sha256(Path(bpy.data.filepath).read_bytes()).hexdigest(), + "model": output.name, + "sha256": hashlib.sha256(output.read_bytes()).hexdigest(), + "bytes": output.stat().st_size, + "groups": len(groups), + "cell_bodies": sum(role == "bms/cells" for role, _ in groups), + "objects": [obj.name for obj in export_objects], + "materials": list(materials), + "cell_displays": sum(role.startswith("bms/cell-display/") for role, _ in groups), + "uv": "cube_projection; original cell display faces use planar X/Z UV", + "source_modified": False, +} +output.with_suffix(".json").write_text(json.dumps(report, indent=2) + "\n") +print(json.dumps(report))