feat(bms): discover JK batteries and integrate read-only telemetry scenes
This commit is contained in:
@@ -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<ComponentProps<typeof GlassMaterialSurface>['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 <div className="bms-panels bms-panels--scene" style={appearance?{'--bms-tile-height':`${appearance.height}px`,'--bms-label-size':`${appearance.labelSize}px`,'--bms-value-size':`${appearance.valueSize}px`,'--bms-text-color':appearance.textColor} as CSSProperties:undefined}>
|
||||
<div className="bms-top"><div className="bms-top-metrics">{all.map(([label,value,unit])=><GlassMaterialSurface context="scene" radius="panel" material={appearance?.glass} radiusPx={appearance?.radius} className="bms-metric" key={label}><Description>{label}</Description><div>{value} <span>{unit}</span></div></GlassMaterialSurface>)}</div>
|
||||
<div className="bms-reading-status"><StatusBadge tone={state.fresh?'success':state.sample?'warning':'neutral'}>{statusLabel(state)}</StatusBadge><Description>{state.sample_at?`Получено ${new Date(state.sample_at).toLocaleTimeString('ru-RU')}`:'Ожидаем чтение по Bluetooth'}</Description></div>
|
||||
</div>
|
||||
<div className="bms-status-metrics">{batteryFacts(state.sample).map(([label,value])=><GlassMaterialSurface context="scene" radius="panel" material={appearance?.glass} radiusPx={appearance?.radius} className="bms-metric bms-state-metric" key={label}><Description>{label}</Description><div>{value}</div></GlassMaterialSurface>)}</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -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<HTMLButtonElement>(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=<div className="bms-panels"><Panel {...surface} radius="panel" className="bms-charge">
|
||||
<Description>Заряд аккумулятора</Description><div className="bms-soc">{number(s?.soc_percent,0)}<span>%</span></div>
|
||||
<StatusBadge tone={state.fresh?'success':s?'warning':'neutral'}>{statusLabel(state)}</StatusBadge>
|
||||
<Description>{state.sample_at?`Получено ${new Date(state.sample_at).toLocaleTimeString('ru-RU')}`:'Ожидаем чтение по Bluetooth'}</Description>
|
||||
</Panel><div className="bms-metrics">{facts.map(([label,value,unit])=><Panel {...surface} key={label} radius="panel" className="bms-metric">
|
||||
<Description>{label}</Description><div>{value} <span>{unit}</span></div></Panel>)}</div></div>;
|
||||
const viewport=renderScene?<>{renderScene(state)}<BatteryTelemetry state={state} facts={facts} appearance={panelAppearance}/></>:null;
|
||||
const content = <div className="bms-content">
|
||||
{viewport?(renderViewport?renderViewport(viewport):<div className="bms-stage">{viewport}</div>):panels}
|
||||
{!editing&&<>{!state.fresh&&s&&<Description role="status">Связь прервана или показания устарели. На экране последний полученный снимок{renderScene?'; он хранится до суточного сброса или перезапуска Core.':'.'}</Description>}
|
||||
{state.state==='unsupported_firmware'&&<Description role="status">BMS обнаружена, но эта модель или прошивка ещё не проверена. Чтение телеметрии для неё не запускается.</Description>}
|
||||
{!renderScene&&<SettingsCard title={s?`Ячейки · ${s.cell_count}`:'Ячейки'} description={s?`Разброс ${number(s.cell_delta_v*1000,0)} мВ`:'Количество и напряжения появятся после чтения BMS'}>
|
||||
<div className="bms-cells">{s?.cell_voltages_v.map((value,i)=><GlassSurface tone="soft" radius="panel" className="bms-cell" key={i}>
|
||||
<Description>Ячейка {String(i+1).padStart(2,'0')}</Description><span>{number(value,3)} В</span></GlassSurface>)}</div>
|
||||
</SettingsCard>}
|
||||
<div className={renderScene?"bms-details bms-details--scene":"bms-details"}>{!renderScene&&<SettingsCard title="Состояние батареи"><dl className="bms-facts">{batteryFacts(s).map(([label,value])=><div key={label}><dt>{label}</dt><dd>{value}</dd></div>)}</dl></SettingsCard>}
|
||||
<SettingsCard title="BMS и подключение"><dl className="bms-facts">{[
|
||||
...(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])=><div key={label}><dt>{label}</dt><dd>{value}</dd></div>)}</dl>
|
||||
<Description>Показания доступны только для чтения. Ёмкость — настройка BMS, а не измерение состояния ячеек.</Description>
|
||||
{renderScene&&<Description>Модель корпуса R04. Цвет всех ячеек отражает общий заряд батареи; индивидуальный заряд ячейки BMS не сообщает.</Description>}
|
||||
</SettingsCard></div></>}
|
||||
</div>;
|
||||
if(presentation==='page')return <section className="bms-device-view" aria-label={`Аккумулятор · ${device.name}`}>{content}</section>;
|
||||
return <Window open size="lg" title={device.name} subtitle="Аккумулятор · Bluetooth LE" onClose={back} className="bms-window" data-expanded={expanded||undefined} allowFloating={!expanded}
|
||||
closeOnEscape={!renderScene} onKeyDown={event=>{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&&<IconButton ref={expandButton} label={expanded?"Восстановить окно батареи":"Развернуть окно батареи"} onClick={()=>setExpanded(value=>!value)}><Icon name={expanded?"minimize":"expand"}/></IconButton>}>
|
||||
{content}
|
||||
</Window>;
|
||||
}
|
||||
@@ -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}}
|
||||
@@ -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<BatteryState>;
|
||||
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';
|
||||
}
|
||||
@@ -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'};},
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<policy user="mission-core-jk-bms">
|
||||
<allow send_destination="org.bluez" send_interface="org.freedesktop.DBus.ObjectManager" send_member="GetManagedObjects"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.freedesktop.DBus.Properties" send_member="GetAll"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.freedesktop.DBus.Properties" send_member="Set"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Adapter1" send_member="SetDiscoveryFilter"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Adapter1" send_member="StartDiscovery"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Adapter1" send_member="StopDiscovery"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Device1" send_member="Connect"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Device1" send_member="Disconnect"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.GattCharacteristic1" send_member="StartNotify"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.GattCharacteristic1" send_member="StopNotify"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.GattCharacteristic1" send_member="WriteValue"/>
|
||||
<allow receive_sender="org.bluez"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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"!<arch>\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)
|
||||
@@ -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"
|
||||
@@ -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()
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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}
|
||||
@@ -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
|
||||
)
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user