feat(bms): add read-only diagnostics and guarded operating switch commands
This commit is contained in:
@@ -21,7 +21,12 @@ func TestBMSProjectionRequiresVersionAndStableIdentity(t *testing.T) {
|
|||||||
if bmsProjection(item, model) {
|
if bmsProjection(item, model) {
|
||||||
t.Fatal("wrong physical identity accepted")
|
t.Fatal("wrong physical identity accepted")
|
||||||
}
|
}
|
||||||
if len(model.Actions) != 0 || model.PrepareUnit != "" || model.Vendor != "" {
|
if len(model.Actions) != 3 || model.PrepareUnit != "" || model.Vendor != "" {
|
||||||
t.Fatal("BMS must remain automatic and read-only")
|
t.Fatal("BMS must remain automatic with only three admitted operations")
|
||||||
|
}
|
||||||
|
for _, action := range []string{"bms.read", "bms.control.verify", "bms.control.set"} {
|
||||||
|
if !model.Actions[action] {
|
||||||
|
t.Fatalf("missing admitted action %s", action)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,8 +56,8 @@ var sensorModels = []sensorModel{
|
|||||||
Vendor: "04d8", Product: "0053", USBName: "USB CANFD DEBUG", Socket: "/run/mission-core-usb-can/driver.sock",
|
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",
|
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")},
|
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",
|
{ID: "jk.bms", Name: "JK BMS", Prefix: "jkbms", Kind: "jk.bms", Plugin: "missioncore.jk-bms", Version: "0.2.0",
|
||||||
Socket: "/run/mission-core-jk-bms/driver.sock", Actions: actions()},
|
Socket: "/run/mission-core-jk-bms/driver.sock", Actions: actions("bms.read", "bms.control.verify", "bms.control.set")},
|
||||||
}
|
}
|
||||||
|
|
||||||
func modelForDevice(id string) *sensorModel {
|
func modelForDevice(id string) *sensorModel {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
|
|
||||||
// Configuration browsing is a bounded snapshot, not a durable backup or write receipt.
|
// Configuration browsing is a bounded snapshot, not a durable backup or write receipt.
|
||||||
func sensorSnapshot(action string) bool {
|
func sensorSnapshot(action string) bool {
|
||||||
return strings.HasPrefix(action, "can.") || action == "vesc.qml.open" || action == "vesc.qml.frame" || action == "vesc.qml.close" || action == "vesc.samples.start" || action == "vesc.samples.status" || action == "vesc.samples.fetch" || action == "vesc.samples.stop" || action == "vesc.samples.read" || action == "vesc.qml.begin" || action == "vesc.qml.chunk" || action == "vesc.qml.render" || action == "vesc.packages.catalog" || action == "vesc.packages.inspect" || action == "vesc.packages.download" || action == "vesc.packages.begin" || action == "vesc.packages.chunk" || action == "vesc.packages.load" || action == "vesc.packages.forget" || action == "vesc.packages.status" || action == "vesc.packages.prepare" || action == "vesc.packages.remove_prepare" || action == "vesc.packages.restore" || action == "vesc.packages.reconcile" || action == "vesc.packages.refresh" || action == "vesc.bms.configuration.read" || action == "vesc.bms.configuration.preview" || action == "vesc.bms.configuration.reconcile" || action == "vesc.bms.configuration.restore" || action == "vesc.code.read" || action == "vesc.code.begin" || action == "vesc.code.chunk" || action == "vesc.code.prepare" || action == "vesc.code.erase_prepare" || action == "vesc.code.reconcile" || action == "vesc.code.control_prepare" || action == "vesc.code.stats" || action == "vesc.code.restore" || action == "vesc.firmware.backup" || action == "vesc.firmware.target" || action == "vesc.bms.read" || action == "vesc.bms.prepare" || action == "vesc.firmware.catalog" || action == "vesc.tools.read" || action == "vesc.terminal.read" || action == "vesc.firmware.status" || action == "vesc.configuration.read" || action == "vesc.configuration.preview" || action == "vesc.diagnostics.read"
|
return strings.HasPrefix(action, "bms.") || strings.HasPrefix(action, "can.") || action == "vesc.qml.open" || action == "vesc.qml.frame" || action == "vesc.qml.close" || action == "vesc.samples.start" || action == "vesc.samples.status" || action == "vesc.samples.fetch" || action == "vesc.samples.stop" || action == "vesc.samples.read" || action == "vesc.qml.begin" || action == "vesc.qml.chunk" || action == "vesc.qml.render" || action == "vesc.packages.catalog" || action == "vesc.packages.inspect" || action == "vesc.packages.download" || action == "vesc.packages.begin" || action == "vesc.packages.chunk" || action == "vesc.packages.load" || action == "vesc.packages.forget" || action == "vesc.packages.status" || action == "vesc.packages.prepare" || action == "vesc.packages.remove_prepare" || action == "vesc.packages.restore" || action == "vesc.packages.reconcile" || action == "vesc.packages.refresh" || action == "vesc.bms.configuration.read" || action == "vesc.bms.configuration.preview" || action == "vesc.bms.configuration.reconcile" || action == "vesc.bms.configuration.restore" || action == "vesc.code.read" || action == "vesc.code.begin" || action == "vesc.code.chunk" || action == "vesc.code.prepare" || action == "vesc.code.erase_prepare" || action == "vesc.code.reconcile" || action == "vesc.code.control_prepare" || action == "vesc.code.stats" || action == "vesc.code.restore" || action == "vesc.firmware.backup" || action == "vesc.firmware.target" || action == "vesc.bms.read" || action == "vesc.bms.prepare" || action == "vesc.firmware.catalog" || action == "vesc.tools.read" || action == "vesc.terminal.read" || action == "vesc.firmware.status" || action == "vesc.configuration.read" || action == "vesc.configuration.preview" || action == "vesc.diagnostics.read"
|
||||||
}
|
}
|
||||||
|
|
||||||
func expiredSensorSnapshot(value SensorOperation) SensorOperation {
|
func expiredSensorSnapshot(value SensorOperation) SensorOperation {
|
||||||
@@ -24,7 +24,9 @@ func expiredSensorSnapshot(value SensorOperation) SensorOperation {
|
|||||||
func (s *Sensors) writeOperation(value *SensorOperation) error {
|
func (s *Sensors) writeOperation(value *SensorOperation) error {
|
||||||
// CAN requests/results are bounded RAM. On restart every USB generation is
|
// CAN requests/results are bounded RAM. On restart every USB generation is
|
||||||
// replaced; queued old-session commands cannot execute or replay TX.
|
// replaced; queued old-session commands cannot execute or replay TX.
|
||||||
if strings.HasPrefix(value.Command.Action, "can.") && value.Result == nil { return nil }
|
if (strings.HasPrefix(value.Command.Action, "can.") || strings.HasPrefix(value.Command.Action, "bms.")) && value.Result == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
if !sensorSnapshot(value.Command.Action) || value.Result == nil {
|
if !sensorSnapshot(value.Command.Action) || value.Result == nil {
|
||||||
return s.write(value.Command.ID+".json", value)
|
return s.write(value.Command.ID+".json", value)
|
||||||
@@ -61,7 +63,9 @@ func (s *Sensors) writeOperation(value *SensorOperation) error {
|
|||||||
*entry = expiredSensorSnapshot(*entry)
|
*entry = expiredSensorSnapshot(*entry)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(value.Command.Action, "can.") { return nil }
|
if strings.HasPrefix(value.Command.Action, "can.") || strings.HasPrefix(value.Command.Action, "bms.") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
persisted := expiredSensorSnapshot(*value)
|
persisted := expiredSensorSnapshot(*value)
|
||||||
return s.write(value.Command.ID+".json", &persisted)
|
return s.write(value.Command.ID+".json", &persisted)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -59,3 +59,23 @@ func TestConfigurationBackupsRemainDurable(t *testing.T) {
|
|||||||
t.Fatal("backup receipt was discarded")
|
t.Fatal("backup receipt was discarded")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBMSCommandsAndReadbacksNeverPersistOrReplayFromDisk(t *testing.T) {
|
||||||
|
s := &Sensors{root: t.TempDir(), operations: map[string]*SensorOperation{}}
|
||||||
|
for _, action := range []string{"bms.read", "bms.control.verify", "bms.control.set"} {
|
||||||
|
op := &SensorOperation{Command: SensorCommand{ID: action, Action: action}, State: "running", Updated: time.Now().Unix()}
|
||||||
|
s.operations[action] = op
|
||||||
|
if err := s.writeOperation(op); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
op.State = "complete"
|
||||||
|
op.Result = map[string]any{"settings": map[string]any{"value": 42}}
|
||||||
|
if err := s.writeOperation(op); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files, err := os.ReadDir(s.root)
|
||||||
|
if err != nil || len(files) != 0 {
|
||||||
|
t.Fatal("BMS commands or measurements escaped RAM", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import sys
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
BINARY_VERSION = "0.8.53"
|
BINARY_VERSION = "0.8.53"
|
||||||
VERSION = "0.8.53-112"
|
VERSION = "0.8.53-113"
|
||||||
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
|
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
|
||||||
from debian import package
|
from debian import package
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
# JK BMS: доступные данные и потенциал управления
|
# JK BMS: доступные данные и потенциал управления
|
||||||
|
|
||||||
Срез источников: 2026-11-04. Это исследование возможностей, не приёмка новых
|
Обновлено 2026-11-04 после поставки Node 0.8.53-113. Дополнительные поля
|
||||||
команд на аккумуляторе. Настройки BMS не менялись. После просьбы владельца
|
и чтение настроек внедрены. Команды заряда, разряда и балансировки доступны
|
||||||
проверки оборудования и пробное выключение не запускались.
|
с подтверждением; на реальной BMS проверена запись прежних значений и полное
|
||||||
|
обратное чтение без изменения настроек. Фактическое отключение MOS и выключение
|
||||||
|
борта не выполнялись. Точный протокол, аудит исходников и ограничения:
|
||||||
|
[контракт управления](47_JK_BMS_OPERATING_CONTROL.md).
|
||||||
|
|
||||||
## Наш профиль и уже реализованное чтение
|
## Наш профиль и уже реализованное чтение
|
||||||
|
|
||||||
@@ -19,15 +22,15 @@
|
|||||||
[контракт интеграции](JK_BMS_BLUETOOTH.md). Это поля нашего декодера, а не
|
[контракт интеграции](JK_BMS_BLUETOOTH.md). Это поля нашего декодера, а не
|
||||||
обещание всех возможностей семейства JK.
|
обещание всех возможностей семейства JK.
|
||||||
|
|
||||||
## Что можно добавить для наблюдения
|
## Дополнительные данные, внедрённые в Node113
|
||||||
|
|
||||||
| Возможность | Практическая ценность и граница подтверждения |
|
| Возможность | Практическая ценность и граница подтверждения |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Минимальная, максимальная и средняя ячейка, номер наиболее отклоняющейся | Можно вычислять из уже получаемых напряжений, без новых команд BMS. |
|
| Минимальная, максимальная и средняя ячейка, номер наиболее отклоняющейся | Вычисляются из полученных напряжений, без новых команд BMS. |
|
||||||
| Сопротивления измерительных/балансировочных цепей и маска проблем проводов | В описании JK02_32S есть соответствующие поля. Их ещё нужно проверить на нашей 11.47; нельзя называть их лабораторным внутренним сопротивлением ячеек. |
|
| Сопротивления измерительных/балансировочных цепей и маска проблем проводов | Прочитаны на 11.47; это измерительная цепь, не лабораторное внутреннее сопротивление ячеек. |
|
||||||
| Понятные причины защиты | Расшифровка битов вместо HEX; нужны подтверждённая раскладка этой версии и сохранение неизвестных битов. |
|
| Понятные причины защиты | Расшифровка JK02, исходный HEX и неизвестные биты сохранены. |
|
||||||
| Текущие пороги напряжения, тока, температуры, настройки балансировки и сна | Отдельный кадр настроек. Наши запросы уже включают 0x96, но текущий декодер использует телеметрию, а кадр настроек пока не публикует. |
|
| Текущие пороги напряжения, тока, температуры, настройки балансировки и сна | Кадр настроек 0x01 публикуется после запроса 0x96. Числовые параметры доступны только для чтения. |
|
||||||
| Серийный номер BMS, показатель здоровья от BMS | В upstream-парсере предусмотрены поля. Это номер контроллера и оценка его прошивки, не артикул CATL и не измеренная остаточная ёмкость. |
|
| Серийный номер BMS, показатель здоровья от BMS | Поля добавлены в allowlist декодера. Это номер контроллера и оценка его прошивки, не артикул CATL и не измеренная остаточная ёмкость. |
|
||||||
|
|
||||||
Основания: [описание BLE-протокола](https://github.com/syssi/esphome-jk-bms/blob/main/docs/protocol-design-ble.md),
|
Основания: [описание BLE-протокола](https://github.com/syssi/esphome-jk-bms/blob/main/docs/protocol-design-ble.md),
|
||||||
[парсер aiobmsble](https://github.com/patman15/aiobmsble/blob/main/aiobmsble/bms/jikong_bms.py),
|
[парсер aiobmsble](https://github.com/patman15/aiobmsble/blob/main/aiobmsble/bms/jikong_bms.py),
|
||||||
@@ -39,7 +42,7 @@
|
|||||||
фактическую ёмкость из нынешнего потока получить нельзя. Время до разряда
|
фактическую ёмкость из нынешнего потока получить нельзя. Время до разряда
|
||||||
можно только оценивать по нагрузке; при нулевом токе полезной оценки нет.
|
можно только оценивать по нагрузке; при нулевом токе полезной оценки нет.
|
||||||
|
|
||||||
## Управление: существует в проектах, ещё не принято для нашей прошивки
|
## Управление и границы проверки
|
||||||
|
|
||||||
ESPHome предоставляет переключение зарядного и разрядного MOS, балансировки,
|
ESPHome предоставляет переключение зарядного и разрядного MOS, балансировки,
|
||||||
сна, ряд порогов и калибровок. В примере также есть команды перезапуска,
|
сна, ряд порогов и калибровок. В примере также есть команды перезапуска,
|
||||||
@@ -55,10 +58,11 @@ ESPHome предоставляет переключение зарядного
|
|||||||
изменения до выяснения состояния.
|
изменения до выяснения состояния.
|
||||||
[Границы поддержки batmon](https://github.com/fl4p/batmon-ha/blob/master/doc/JK-Settings.md).
|
[Границы поддержки batmon](https://github.com/fl4p/batmon-ha/blob/master/doc/JK-Settings.md).
|
||||||
|
|
||||||
Для Mission Core следующий полезный шаг — расширение чтения в существующем
|
Mission Core реализует только три рабочих переключателя: заряд, разряд и
|
||||||
плагине. Если позже вводить управление, необходимы свежий сеанс, отдельное
|
балансировка. Свежий сеанс, отдельное подтверждение, fingerprint настроек,
|
||||||
подтверждение, чтение результата и запрет повторного исполнения старой команды
|
обратное чтение и запрет повторного исполнения старой команды обязательны.
|
||||||
после переподключения. Порог токовой защиты не является регулятором мощности
|
Проверка на нашей плате ограничена записью уже установленных значений; фактическое
|
||||||
|
изменение MOS не проверялось. Порог токовой защиты не является регулятором мощности
|
||||||
зарядника или двигателя. Отключение разрядного MOS может обесточить сам борт;
|
зарядника или двигателя. Отключение разрядного MOS может обесточить сам борт;
|
||||||
последующее дистанционное включение тогда требует независимого питания.
|
последующее дистанционное включение тогда требует независимого питания.
|
||||||
Выключение ОС через кнопку борта — другая операция, оно не отключает MOS BMS.
|
Выключение ОС через кнопку борта — другая операция, оно не отключает MOS BMS.
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# JK BMS operating controls
|
||||||
|
|
||||||
|
Scope: JK_BD6A17S6P, hardware 11.XA, firmware 11.47, JK02_32S layout.
|
||||||
|
Other models keep discovery/read qualification independent from write authority.
|
||||||
|
|
||||||
|
## Protocol and limits
|
||||||
|
|
||||||
|
The existing owner uses BlueZ service FFE0, characteristic FFE1,
|
||||||
|
`write-without-response` and notifications. The notification subscription makes
|
||||||
|
only the normal temporary CCCD change. Reads use registers 0x97 (identity) and
|
||||||
|
0x96 (settings/status). The driver never pairs, resets an adapter, runs a second
|
||||||
|
BLE client, or disconnects a peer owned by another client.
|
||||||
|
|
||||||
|
Only three fixed 20-byte operating frames can be encoded: header AA5590EB,
|
||||||
|
register 0x1D charge / 0x1E discharge / 0x1F balance, length 4, a little-endian
|
||||||
|
uint32 equal to zero or one, zero padding, sum-of-first-19 checksum. No arbitrary
|
||||||
|
address/value, protection-setting, SOC calibration, reset, password, emergency
|
||||||
|
or firmware API is exposed. In settings response 0x01, the corresponding uint32
|
||||||
|
values are at offsets 118, 122 and 126. Enabled means permission to operate;
|
||||||
|
BMS protections can still keep a MOS or balancer inactive.
|
||||||
|
|
||||||
|
An explicit operator confirmation sends a session-bound, expiring request.
|
||||||
|
Before sending, the driver rereads settings and checks the confirmation's
|
||||||
|
fingerprint, BLE generation, qualified identity, cell count, fresh telemetry
|
||||||
|
and protection/wiring flags. Password reminder bit 19 is informational; unknown
|
||||||
|
bits and every other active flag block changes. The query settles for at least
|
||||||
|
one second before a write. After the write, a fresh 0x96 query checks the complete
|
||||||
|
settings payload: exactly the selected bool may change; all other bytes must
|
||||||
|
remain equal. There is no blind write retry or automatic opposite command.
|
||||||
|
|
||||||
|
A lost link, timeout or unexpected readback after sending is **unknown**, not
|
||||||
|
success. Subsequent writes are blocked for that runtime instance; reads remain
|
||||||
|
available. Resolve the actual state before restarting/requalifying. Restarts
|
||||||
|
change session identity and cannot revive queued old requests. Reusing an
|
||||||
|
operation ID cannot repeat the physical write. Node and Core receipts and
|
||||||
|
telemetry stay bounded in RAM; persisted tombstones cannot replay commands.
|
||||||
|
|
||||||
|
Restoring an operating state is another explicitly confirmed command after a
|
||||||
|
fresh read, not an automatic rollback. Turning discharge off can remove board
|
||||||
|
power and require local recovery. No automated test is allowed to cut board
|
||||||
|
power. Numeric protection settings and calibration are never modified by this
|
||||||
|
feature, including the verification operation.
|
||||||
|
|
||||||
|
`bms.control.verify` is an engineering-only, low-current (<=0.2 A) check which
|
||||||
|
writes each switch's **existing** value and compares the whole readback. It
|
||||||
|
checks command framing and unchanged settings, but cannot prove that changing
|
||||||
|
a MOS/balancer state actuates hardware. Synthetic tests cover actual requested
|
||||||
|
transitions and failure paths without a radio.
|
||||||
|
|
||||||
|
## Sources reviewed
|
||||||
|
|
||||||
|
The adapter is implemented locally, not by executing/vendor-installing a whole
|
||||||
|
upstream application. Reviewed immutable source snapshots:
|
||||||
|
|
||||||
|
- [batmon-ha c58a670](https://github.com/fl4p/batmon-ha/tree/c58a670abc722483b503ab6a89f835b60e971230), MIT: common settings, switch frames, one-second query settling.
|
||||||
|
- [ESPHome JK BMS 0bd4063](https://github.com/syssi/esphome-jk-bms/tree/0bd4063e459ae6ed95e767288b32daefc6049dbf), Apache-2.0: offsets, switch registers, JK02 status-bit meanings.
|
||||||
|
- [aiobmsble 705ea16](https://github.com/patman15/aiobmsble/tree/705ea1609243bc4bcda3584e556a92077d58b5e6), Apache-2.0: read-only transport/parser comparison.
|
||||||
|
|
||||||
|
This is a bounded source review, not an audit of every upstream dependency.
|
||||||
|
The batmon identity path logs a Bluetooth password field at INFO; its standalone
|
||||||
|
example also toggles a switch. Neither behaviour is copied or executed. Identity
|
||||||
|
is an explicit allowlist; raw frames, password fields and arbitrary write APIs
|
||||||
|
are not returned or logged. Source hashes, qualification results and live-test
|
||||||
|
limitations are retained in local `outputs/bms-integration-20261104`.
|
||||||
|
|
||||||
|
## Readout semantics
|
||||||
|
|
||||||
|
Telemetry offset 178 is the BMS's full/effective capacity estimate; settings
|
||||||
|
frame offset 130 is configured nominal capacity. Neither measures actual cell
|
||||||
|
health independently. SOH is the reported BMS estimate. Wiring resistance is
|
||||||
|
measurement-lead resistance, not cell internal resistance. Unknown warning bits
|
||||||
|
remain visible. A disconnected battery can retain its last valid SOC for the
|
||||||
|
current UTC day (maximum 24 hours, bounded RAM) while freshness is shown stale.
|
||||||
|
At expiry or before the first reading, an independently editable, non-emissive
|
||||||
|
fallback surface is used. No measurement is written into the scene profile.
|
||||||
|
|
||||||
|
## Prepared-board acceptance, 2026-11-04
|
||||||
|
|
||||||
|
Node 0.8.53-113 installed through owner release e59c35fe4f83b5c98cea3b0a.
|
||||||
|
Package validation and installer completed; Node, BMS, VESC, USB-CAN, K1 and
|
||||||
|
RealSense remained active, X4 0.1.3-30 unchanged. This is prepared Ubuntu 24.04
|
||||||
|
amd64 acceptance, not a clean-host qualification.
|
||||||
|
|
||||||
|
At 14:01:26–14:01:43 UTC, the real paired Core→Node→BLE path completed bms.read
|
||||||
|
and bms.control.verify. Charge/discharge/balance were already true and each
|
||||||
|
was written as true. Whole settings fingerprint was identical before/after.
|
||||||
|
No MOS-off, calibration, threshold, password, firmware or board shutdown was
|
||||||
|
requested. Actual hardware switching remains untested. Readout confirmed 13
|
||||||
|
channels, 118 Ah configured capacity, reported SOH, cell extrema and wiring
|
||||||
|
resistances. Local evidence: outputs/bms-integration-20261104/live-check.json.
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""Node113 over qualified Node112; replace reviewed BMS/UI only."""
|
||||||
|
|
||||||
|
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"
|
||||||
|
VERSION = "0.8.53-113"
|
||||||
|
BASE_SHA = "a67521b9647c3f8e02849cde5adb3bcb8d5f50370e61559da8c6aef3692b6e29"
|
||||||
|
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")
|
||||||
|
raw = (NODE / "build/power-112/mission-core-node_0.8.53-112_amd64.deb").read_bytes()
|
||||||
|
if hashlib.sha256(raw).hexdigest() != BASE_SHA:
|
||||||
|
raise ValueError("Qualified baseline changed")
|
||||||
|
stream = io.BytesIO(raw)
|
||||||
|
assert stream.read(8) == b"!<arch>\n"
|
||||||
|
archives = {}
|
||||||
|
while header := stream.read(60):
|
||||||
|
size = int(header[48:58])
|
||||||
|
archives[header[:16].decode().strip().rstrip("/")] = stream.read(size)
|
||||||
|
if size % 2:
|
||||||
|
stream.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 = {n: d for n, d, _ in files}
|
||||||
|
compiled = binary.read_bytes()
|
||||||
|
assert compiled[:6] == b"\x7fELF\x02\x01" and compiled[18:20] == b"\x3e\x00"
|
||||||
|
sources = {
|
||||||
|
str(p.relative_to(REPO)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||||
|
for root in (
|
||||||
|
REPO / "plugins/jk-bms",
|
||||||
|
NODE / "internal",
|
||||||
|
NODE / "cmd",
|
||||||
|
NODE / "web/dist",
|
||||||
|
REPO / "packages/sensor-ui/src",
|
||||||
|
)
|
||||||
|
for p in sorted(root.rglob("*"))
|
||||||
|
if p.is_file() and "__pycache__" not in p.parts
|
||||||
|
}
|
||||||
|
provenance = dict(
|
||||||
|
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="Reviewed JK diagnostics and expiring three-switch controls; no numeric writes",
|
||||||
|
binary_sha256=hashlib.sha256(compiled).hexdigest(),
|
||||||
|
source_files=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 = []
|
||||||
|
for name, data, mode in runpy.run_path(str(Path(__file__).with_name("payload.py")))[
|
||||||
|
"payload"
|
||||||
|
]():
|
||||||
|
if name in old:
|
||||||
|
changes[name] = data
|
||||||
|
else:
|
||||||
|
added.append((name, data, mode))
|
||||||
|
replaced = []
|
||||||
|
for name, data, mode in controls:
|
||||||
|
if name == "control":
|
||||||
|
assert b"Version: 0.8.53-112\n" in data
|
||||||
|
data = data.replace(b"Version: 0.8.53-112\n", f"Version: {VERSION}\n".encode())
|
||||||
|
replaced.append((name, data, mode))
|
||||||
|
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(replaced, files))
|
||||||
|
report = dict(
|
||||||
|
version=VERSION,
|
||||||
|
base_sha256=BASE_SHA,
|
||||||
|
sha256=hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||||
|
bytes=output.stat().st_size,
|
||||||
|
changed_controls=["control"],
|
||||||
|
changed_payloads=[name for name, data in changes.items() if old.get(name) != data],
|
||||||
|
added_payloads=[n for n, _, _ in added],
|
||||||
|
retained_payload_count=sum(data == old.get(name) for name, data, _ in files),
|
||||||
|
)
|
||||||
|
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", type=Path, required=True)
|
||||||
|
parser.add_argument("--output", type=Path, required=True)
|
||||||
|
args = parser.parse_args()
|
||||||
|
build(args.binary, args.output)
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
"""Read-only JK BLE equipment plugin. No settings or power-control operations."""
|
"""JK BLE equipment plugin. Read diagnostics and three reviewed operating switches."""
|
||||||
|
|
||||||
MODEL = "jk.bms"
|
MODEL = "jk.bms"
|
||||||
VERSION = "0.1.0"
|
VERSION = "0.2.0"
|
||||||
PLUGIN = "missioncore.jk-bms"
|
PLUGIN = "missioncore.jk-bms"
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import time
|
|||||||
import dbus
|
import dbus
|
||||||
from dbus.mainloop.glib import DBusGMainLoop
|
from dbus.mainloop.glib import DBusGMainLoop
|
||||||
|
|
||||||
|
from .operations import Operations
|
||||||
from .protocol import (
|
from .protocol import (
|
||||||
CHARACTERISTIC,
|
CHARACTERISTIC,
|
||||||
SERVICE,
|
SERVICE,
|
||||||
@@ -20,6 +21,7 @@ from .protocol import (
|
|||||||
supported,
|
supported,
|
||||||
telemetry,
|
telemetry,
|
||||||
)
|
)
|
||||||
|
from .settings import decode_settings, switch_command
|
||||||
|
|
||||||
DEVICE = "org.bluez.Device1"
|
DEVICE = "org.bluez.Device1"
|
||||||
ADAPTER = "org.bluez.Adapter1"
|
ADAPTER = "org.bluez.Adapter1"
|
||||||
@@ -30,6 +32,8 @@ class Observer:
|
|||||||
def __init__(self, service):
|
def __init__(self, service):
|
||||||
DBusGMainLoop(set_as_default=True)
|
DBusGMainLoop(set_as_default=True)
|
||||||
self.service = service
|
self.service = service
|
||||||
|
self.operations = Operations(service, self)
|
||||||
|
service.operations = self.operations
|
||||||
self.bus = dbus.SystemBus()
|
self.bus = dbus.SystemBus()
|
||||||
self.scanning = set()
|
self.scanning = set()
|
||||||
self.seen = {}
|
self.seen = {}
|
||||||
@@ -91,6 +95,10 @@ class Observer:
|
|||||||
self.finish("unsupported_firmware", delay=300)
|
self.finish("unsupported_firmware", delay=300)
|
||||||
return
|
return
|
||||||
a["verified"] = True
|
a["verified"] = True
|
||||||
|
elif frame[4] == 1 and a.get("verified"):
|
||||||
|
settings = decode_settings(frame)
|
||||||
|
self.service.settings(a["address"], settings)
|
||||||
|
self.operations.received(a["address"], frame, settings)
|
||||||
elif frame[4] == 2 and a.get("verified"):
|
elif frame[4] == 2 and a.get("verified"):
|
||||||
self.service.sample(a["address"], telemetry(frame))
|
self.service.sample(a["address"], telemetry(frame))
|
||||||
a["last_sample"] = time.monotonic()
|
a["last_sample"] = time.monotonic()
|
||||||
@@ -104,6 +112,7 @@ class Observer:
|
|||||||
self.scanning.discard(path)
|
self.scanning.discard(path)
|
||||||
|
|
||||||
def finish(self, reason, delay=None):
|
def finish(self, reason, delay=None):
|
||||||
|
self.operations.finish("Bluetooth-сеанс завершён; команда не повторяется.")
|
||||||
a, self.active = self.active, None
|
a, self.active = self.active, None
|
||||||
if not a:
|
if not a:
|
||||||
return
|
return
|
||||||
@@ -133,6 +142,13 @@ class Observer:
|
|||||||
)
|
)
|
||||||
a["last_query"] = time.monotonic()
|
a["last_query"] = time.monotonic()
|
||||||
|
|
||||||
|
def write_switch(self, name, enabled):
|
||||||
|
self.interface(self.active["characteristic"], GATT).WriteValue(
|
||||||
|
dbus.Array(switch_command(name, enabled), signature="y"),
|
||||||
|
dbus.Dictionary({"type": dbus.String("command")}, signature="sv"),
|
||||||
|
timeout=3,
|
||||||
|
)
|
||||||
|
|
||||||
def tick(self):
|
def tick(self):
|
||||||
if self.closed:
|
if self.closed:
|
||||||
return False
|
return False
|
||||||
@@ -174,11 +190,20 @@ class Observer:
|
|||||||
if a.get("verified") and not a.get("requested"):
|
if a.get("verified") and not a.get("requested"):
|
||||||
self.write_read(0x96)
|
self.write_read(0x96)
|
||||||
a["requested"] = True
|
a["requested"] = True
|
||||||
|
self.operations.tick()
|
||||||
|
if (
|
||||||
|
a.get("verified")
|
||||||
|
and a.get("last_sample")
|
||||||
|
and now - a.get("settings_query", a["started"]) > 60
|
||||||
|
and not self.operations.job
|
||||||
|
):
|
||||||
|
self.write_read(0x96)
|
||||||
|
a["settings_query"] = now
|
||||||
if a.get("last_query") and now - a.get("last_sample", a["last_query"]) > 12:
|
if a.get("last_query") and now - a.get("last_sample", a["last_query"]) > 12:
|
||||||
self.finish("read_timeout")
|
self.finish("read_timeout")
|
||||||
elif not a.get("last_sample") and now - a["started"] > 45:
|
elif not a.get("last_sample") and now - a["started"] > 45:
|
||||||
self.finish("connect_timeout")
|
self.finish("connect_timeout")
|
||||||
elif now - a["started"] > 120:
|
elif now - a["started"] > 120 and not self.operations.job:
|
||||||
# Fairness: refresh discovery so a second BMS can be admitted.
|
# Fairness: refresh discovery so a second BMS can be admitted.
|
||||||
self.finish("reconnecting", delay=5)
|
self.finish("reconnecting", delay=5)
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
"""Single-flight, expiring BMS operations on the observer's existing BLE link."""
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from .protocol import supported
|
||||||
|
from .settings import SWITCHES, unchanged_except
|
||||||
|
|
||||||
|
|
||||||
|
class Operations:
|
||||||
|
def __init__(self, service, observer):
|
||||||
|
self.service, self.observer = service, observer
|
||||||
|
self.lock = threading.RLock()
|
||||||
|
self.job = None
|
||||||
|
self.receipts = {}
|
||||||
|
self.blocked = set()
|
||||||
|
|
||||||
|
def execute(self, request):
|
||||||
|
with self.lock, self.service.lock:
|
||||||
|
identifier = request.get("operation_id", "")
|
||||||
|
if (
|
||||||
|
not re.fullmatch(r"op_[0-9a-f]{32}", identifier)
|
||||||
|
or request.get("idempotency_key") != identifier
|
||||||
|
):
|
||||||
|
raise ValueError("Неверный идентификатор операции.")
|
||||||
|
if identifier in self.receipts:
|
||||||
|
previous, result = self.receipts[identifier]
|
||||||
|
if previous != request:
|
||||||
|
raise ValueError("Идентификатор уже использован.")
|
||||||
|
return copy.deepcopy(result)
|
||||||
|
self.receipts = {
|
||||||
|
key: value
|
||||||
|
for key, value in self.receipts.items()
|
||||||
|
if datetime.fromisoformat(
|
||||||
|
value[0]["deadline_at"].replace("Z", "+00:00")
|
||||||
|
).timestamp()
|
||||||
|
> time.time()
|
||||||
|
}
|
||||||
|
if self.job or len(self.receipts) >= 128:
|
||||||
|
raise ValueError("Дождитесь завершения операции BMS.")
|
||||||
|
action = request.get("action_id")
|
||||||
|
if action not in ("bms.read", "bms.control.verify", "bms.control.set"):
|
||||||
|
raise ValueError("Команда BMS не поддерживается.")
|
||||||
|
deadline = datetime.fromisoformat(
|
||||||
|
request["deadline_at"].replace("Z", "+00:00")
|
||||||
|
).timestamp()
|
||||||
|
if not 0 < deadline - time.time() <= 25:
|
||||||
|
raise ValueError("Срок команды истёк. Обновите показания.")
|
||||||
|
session = request["session"]
|
||||||
|
if not isinstance(session, dict):
|
||||||
|
raise ValueError("Неверный сеанс BMS.")
|
||||||
|
address, d = next(
|
||||||
|
(
|
||||||
|
(a, d)
|
||||||
|
for a, d in self.service.devices.items()
|
||||||
|
if d["id"] == session["device_id"]
|
||||||
|
),
|
||||||
|
(None, None),
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
d is None
|
||||||
|
or d["session"] != session["session_id"]
|
||||||
|
or not supported(d["identity"] or {})
|
||||||
|
):
|
||||||
|
raise ValueError("Сеанс или профиль BMS изменился.")
|
||||||
|
parameters = request.get("parameters", {})
|
||||||
|
if not isinstance(parameters, dict):
|
||||||
|
raise ValueError("Неверные параметры команды.")
|
||||||
|
if action == "bms.control.set":
|
||||||
|
if (
|
||||||
|
set(parameters) != {"switch", "enabled", "fingerprint", "link_generation"}
|
||||||
|
or parameters["switch"] not in SWITCHES
|
||||||
|
or type(parameters["enabled"]) is not bool
|
||||||
|
):
|
||||||
|
raise ValueError("Допустимы только заряд, разряд и балансировка.")
|
||||||
|
if parameters["link_generation"] != d["link_generation"]:
|
||||||
|
raise ValueError("Bluetooth переподключился. Обновите показания.")
|
||||||
|
elif parameters:
|
||||||
|
raise ValueError("У команды нет дополнительных параметров.")
|
||||||
|
if action != "bms.read" and d["identity"].get("hardware") != "11.XA":
|
||||||
|
raise ValueError("Управление этой аппаратной версией не проверено.")
|
||||||
|
if action != "bms.read" and address in self.blocked:
|
||||||
|
raise ValueError(
|
||||||
|
"Результат предыдущей записи не подтверждён. Управление заблокировано."
|
||||||
|
)
|
||||||
|
job = dict(
|
||||||
|
request=copy.deepcopy(request),
|
||||||
|
address=address,
|
||||||
|
session=d["session"],
|
||||||
|
generation=d["link_generation"],
|
||||||
|
expires=time.monotonic() + min(20, deadline - time.time()),
|
||||||
|
phase="queued",
|
||||||
|
sent=False,
|
||||||
|
event=threading.Event(),
|
||||||
|
)
|
||||||
|
self.job = job
|
||||||
|
job["event"].wait(22)
|
||||||
|
with self.lock:
|
||||||
|
if not job["event"].is_set():
|
||||||
|
self.finish("Связь не подтвердила результат операции.")
|
||||||
|
return copy.deepcopy(job["result"])
|
||||||
|
|
||||||
|
def finish(self, error=None, result=None):
|
||||||
|
with self.lock:
|
||||||
|
job, self.job = self.job, None
|
||||||
|
if not job:
|
||||||
|
return
|
||||||
|
if error and job["sent"]:
|
||||||
|
self.blocked.add(job["address"])
|
||||||
|
value = {"state": ("unknown" if job["sent"] else "error") if error else "complete"}
|
||||||
|
if error:
|
||||||
|
value["error"] = error
|
||||||
|
else:
|
||||||
|
value["result"] = result
|
||||||
|
job["result"] = value
|
||||||
|
self.receipts[job["request"]["operation_id"]] = (job["request"], value)
|
||||||
|
job["event"].set()
|
||||||
|
|
||||||
|
def tick(self):
|
||||||
|
with self.lock, self.service.lock:
|
||||||
|
job = self.job
|
||||||
|
if not job:
|
||||||
|
return
|
||||||
|
a = self.observer.active
|
||||||
|
d = self.service.devices[job["address"]]
|
||||||
|
if (
|
||||||
|
time.monotonic() >= job["expires"]
|
||||||
|
or not a
|
||||||
|
or a["address"] != job["address"]
|
||||||
|
or not a.get("verified")
|
||||||
|
or d["session"] != job["session"]
|
||||||
|
or d["link_generation"] != job["generation"]
|
||||||
|
or not d["sample"]
|
||||||
|
or d["state"] != "streaming"
|
||||||
|
or self.service.clock() - d["sampled"] >= 5
|
||||||
|
):
|
||||||
|
self.finish("Нет свежего подтверждённого соединения с BMS.")
|
||||||
|
return
|
||||||
|
if job["phase"] == "queued":
|
||||||
|
job["phase"] = "before"
|
||||||
|
job["query_at"] = time.monotonic()
|
||||||
|
self.observer.write_read(0x96)
|
||||||
|
elif job["phase"] == "write_ready" and time.monotonic() - job["query_at"] >= 1:
|
||||||
|
if (
|
||||||
|
d["sample"].get("protection_mask", 1) & ~(1 << 19)
|
||||||
|
or d["sample"].get("wire_warning_cells")
|
||||||
|
or not d["settings"]
|
||||||
|
or d["settings"]["fingerprint"] != job["fingerprint"]
|
||||||
|
or (
|
||||||
|
job["request"]["action_id"] == "bms.control.verify"
|
||||||
|
and abs(d["sample"]["current_a"]) > 0.2
|
||||||
|
)
|
||||||
|
):
|
||||||
|
self.finish("Состояние BMS изменилось до записи. Подтвердите заново.")
|
||||||
|
return
|
||||||
|
job.update(sent=True, phase="settle", read_after=time.monotonic() + 0.3)
|
||||||
|
# No retry: a GATT exception can happen after the device accepted the frame.
|
||||||
|
self.observer.write_switch(job["switch"], job["enabled"])
|
||||||
|
elif job["phase"] == "settle" and time.monotonic() >= job["read_after"]:
|
||||||
|
job["phase"] = "after"
|
||||||
|
job["query_at"] = time.monotonic()
|
||||||
|
self.observer.write_read(0x96)
|
||||||
|
|
||||||
|
def received(self, address, frame, settings):
|
||||||
|
with self.lock, self.service.lock:
|
||||||
|
job = self.job
|
||||||
|
if not job or job["address"] != address or job["phase"] not in ("before", "after"):
|
||||||
|
return
|
||||||
|
if time.monotonic() >= job["expires"]:
|
||||||
|
self.finish("Срок подтверждения BMS истёк.")
|
||||||
|
return
|
||||||
|
d = self.service.devices[address]
|
||||||
|
action, parameters = job["request"]["action_id"], job["request"].get("parameters", {})
|
||||||
|
if (
|
||||||
|
not d["sample"]
|
||||||
|
or self.service.clock() - d["sampled"] >= 5
|
||||||
|
or d["session"] != job["session"]
|
||||||
|
or d["link_generation"] != job["generation"]
|
||||||
|
):
|
||||||
|
self.finish("Сеанс или свежие показания BMS потеряны.")
|
||||||
|
return
|
||||||
|
if settings["values"]["cell_count"] != d["sample"]["cell_count"]:
|
||||||
|
self.finish("Настройки не совпадают с числом измеряемых ячеек.")
|
||||||
|
return
|
||||||
|
if job["phase"] == "before":
|
||||||
|
if action == "bms.read":
|
||||||
|
self.finish(result={"settings": settings, "link_generation": job["generation"]})
|
||||||
|
return
|
||||||
|
if parameters and parameters["fingerprint"] != settings["fingerprint"]:
|
||||||
|
self.finish("Настройки изменились. Обновите сведения и подтвердите снова.")
|
||||||
|
return
|
||||||
|
if d["sample"].get("protection_mask", 1) & ~(1 << 19) or d["sample"].get(
|
||||||
|
"wire_warning_cells"
|
||||||
|
):
|
||||||
|
self.finish("BMS сообщает о защите или проводах. Управление недоступно.")
|
||||||
|
return
|
||||||
|
job["before"] = frame
|
||||||
|
if action == "bms.control.verify":
|
||||||
|
if abs(d["sample"]["current_a"]) > 0.2:
|
||||||
|
self.finish("Для проверки требуется ток не более 0,2 А.")
|
||||||
|
return
|
||||||
|
job["remaining"] = list(SWITCHES)
|
||||||
|
else:
|
||||||
|
name, enabled = parameters["switch"], parameters["enabled"]
|
||||||
|
if settings["switches"][name] == enabled:
|
||||||
|
self.finish(
|
||||||
|
result={
|
||||||
|
"unchanged": True,
|
||||||
|
"switch": name,
|
||||||
|
"enabled": enabled,
|
||||||
|
"settings": settings,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
job["remaining"] = [name]
|
||||||
|
else:
|
||||||
|
name, enabled = job["switch"], job["enabled"]
|
||||||
|
if not unchanged_except(job["before"], frame, name, enabled):
|
||||||
|
self.finish(
|
||||||
|
"Ответ BMS не совпал с ожидаемым; дальнейшее управление заблокировано."
|
||||||
|
)
|
||||||
|
return
|
||||||
|
job["before"] = frame
|
||||||
|
if not job["remaining"]:
|
||||||
|
self.finish(
|
||||||
|
result={
|
||||||
|
"verified_readback": True,
|
||||||
|
"verification": "same-value-only"
|
||||||
|
if action == "bms.control.verify"
|
||||||
|
else "requested-state",
|
||||||
|
"settings": settings,
|
||||||
|
"link_generation": job["generation"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
name = job["remaining"].pop(0)
|
||||||
|
enabled = (
|
||||||
|
settings["switches"][name]
|
||||||
|
if action == "bms.control.verify"
|
||||||
|
else parameters["enabled"]
|
||||||
|
)
|
||||||
|
job.update(
|
||||||
|
switch=name,
|
||||||
|
enabled=enabled,
|
||||||
|
phase="write_ready",
|
||||||
|
fingerprint=settings["fingerprint"],
|
||||||
|
)
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
"""JK02_32S profile qualified against BD6A17S6P / 11.47.
|
"""JK02_32S profile qualified against BD6A17S6P / 11.47.
|
||||||
|
|
||||||
Only 0x97 (identity) and 0x96 (telemetry subscription) can be constructed.
|
Only read requests are constructed here. Operating switches have a separate
|
||||||
|
strict encoder in settings.py; protection/calibration writes are absent.
|
||||||
Never expose the raw identity frame: it contains unrelated credential fields.
|
Never expose the raw identity frame: it contains unrelated credential fields.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -63,7 +64,7 @@ class Frames:
|
|||||||
if len(self.buffer) < 300:
|
if len(self.buffer) < 300:
|
||||||
break
|
break
|
||||||
frame = bytes(self.buffer[:300])
|
frame = bytes(self.buffer[:300])
|
||||||
if sum(frame[:-1]) & 255 != frame[-1]:
|
if frame[4] not in (1, 2, 3) or sum(frame[:-1]) & 255 != frame[-1]:
|
||||||
del self.buffer[0]
|
del self.buffer[0]
|
||||||
self.rejected += 1
|
self.rejected += 1
|
||||||
continue
|
continue
|
||||||
@@ -85,6 +86,7 @@ def identity(frame):
|
|||||||
"firmware": field(30, 38),
|
"firmware": field(30, 38),
|
||||||
"name": field(46, 62),
|
"name": field(46, 62),
|
||||||
"manufactured_raw": field(78, 84),
|
"manufactured_raw": field(78, 84),
|
||||||
|
"serial_number": field(86, 97),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -121,12 +123,22 @@ def telemetry(frame):
|
|||||||
"power_w": round(voltage * current, 3),
|
"power_w": round(voltage * current, 3),
|
||||||
"power_source": "voltage_times_current",
|
"power_source": "voltage_times_current",
|
||||||
"remaining_ah": u(174) / 1000,
|
"remaining_ah": u(174) / 1000,
|
||||||
"configured_capacity_ah": u(178) / 1000,
|
"configured_capacity_ah": None,
|
||||||
|
"effective_capacity_ah": u(178) / 1000,
|
||||||
|
"reported_health_percent": u(190, 1) if u(190, 1) <= 100 else None,
|
||||||
"cycle_count": u(182),
|
"cycle_count": u(182),
|
||||||
"cycle_capacity_ah": u(186) / 1000,
|
"cycle_capacity_ah": u(186) / 1000,
|
||||||
"cell_count": count,
|
"cell_count": count,
|
||||||
"cell_voltages_v": cells,
|
"cell_voltages_v": cells,
|
||||||
"cell_delta_v": u(76, 2) / 1000,
|
"cell_delta_v": u(76, 2) / 1000,
|
||||||
|
"cell_min_v": min(cells),
|
||||||
|
"cell_max_v": max(cells),
|
||||||
|
"cell_average_v": round(sum(cells) / count, 4),
|
||||||
|
"cell_min_index": cells.index(min(cells)) + 1,
|
||||||
|
"cell_max_index": cells.index(max(cells)) + 1,
|
||||||
|
"wire_resistances_ohm": [u(80 + i * 2, 2) / 1000 for i in range(count)],
|
||||||
|
"wire_warning_cells": [i + 1 for i in range(count) if u(146) & (1 << i)],
|
||||||
|
"protection_mask": u(166),
|
||||||
"charge_mos_on": bool(u(198, 1)),
|
"charge_mos_on": bool(u(198, 1)),
|
||||||
"discharge_mos_on": bool(u(199, 1)),
|
"discharge_mos_on": bool(u(199, 1)),
|
||||||
"runtime_s": u(194),
|
"runtime_s": u(194),
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Local read-only inventory endpoint; no public port or arbitrary GATT API."""
|
"""Private inventory and allowlisted operations; no public port or raw GATT API."""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
@@ -37,6 +37,9 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
def log_message(self, *args):
|
def log_message(self, *args):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
self.do_GET()
|
||||||
|
|
||||||
def do_GET(self):
|
def do_GET(self):
|
||||||
_, uid, _ = struct.unpack(
|
_, uid, _ = struct.unpack(
|
||||||
"3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)
|
"3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)
|
||||||
@@ -45,12 +48,32 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if uid != self.server.node_uid or not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node):
|
if uid != self.server.node_uid or not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node):
|
||||||
self.send_error(403)
|
self.send_error(403)
|
||||||
return
|
return
|
||||||
if self.path != "/inventory":
|
try:
|
||||||
|
if self.headers.get("Transfer-Encoding"):
|
||||||
|
raise ValueError("Недопустимый формат запроса.")
|
||||||
|
if self.command == "GET" and self.path == "/inventory":
|
||||||
|
result = self.server.service.inventory(node)
|
||||||
|
elif self.command == "POST" and self.path == "/operation":
|
||||||
|
size = int(self.headers.get("Content-Length", "0"))
|
||||||
|
if not 0 < size <= 8192 or self.headers.get("Content-Type") != "application/json":
|
||||||
|
raise ValueError("Недопустимый размер запроса.")
|
||||||
|
raw = self.rfile.read(size)
|
||||||
|
if len(raw) != size:
|
||||||
|
raise ValueError("Неполный запрос.")
|
||||||
|
request = json.loads(raw)
|
||||||
|
if not isinstance(request, dict):
|
||||||
|
raise ValueError("Недопустимый запрос.")
|
||||||
|
result = self.server.service.operations.execute(request)
|
||||||
|
else:
|
||||||
self.send_error(404)
|
self.send_error(404)
|
||||||
return
|
return
|
||||||
payload = json.dumps(self.server.service.inventory(node), allow_nan=False).encode()
|
except (ValueError, KeyError, TypeError, OSError):
|
||||||
|
self.send_error(400, "Invalid or unavailable BMS operation")
|
||||||
|
return
|
||||||
|
payload = json.dumps(result, allow_nan=False).encode()
|
||||||
self.send_response(200)
|
self.send_response(200)
|
||||||
self.send_header("Content-Type", "application/json")
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Cache-Control", "no-store")
|
||||||
self.send_header("Content-Length", str(len(payload)))
|
self.send_header("Content-Length", str(len(payload)))
|
||||||
self.end_headers()
|
self.end_headers()
|
||||||
self.wfile.write(payload)
|
self.wfile.write(payload)
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ class Service:
|
|||||||
self.instance = "jkbms_" + uuid.uuid4().hex
|
self.instance = "jkbms_" + uuid.uuid4().hex
|
||||||
self.devices = {}
|
self.devices = {}
|
||||||
self.revision = 0
|
self.revision = 0
|
||||||
|
self.operations = None
|
||||||
self.day = datetime.now(UTC).date()
|
self.day = datetime.now(UTC).date()
|
||||||
for path in sorted(self.root.glob("jkbms_*.json"))[:8]:
|
for path in sorted(self.root.glob("jkbms_*.json"))[:8]:
|
||||||
try:
|
try:
|
||||||
@@ -52,6 +53,9 @@ class Service:
|
|||||||
adapter=None,
|
adapter=None,
|
||||||
rssi_dbm=None,
|
rssi_dbm=None,
|
||||||
link_generation=0,
|
link_generation=0,
|
||||||
|
settings=None,
|
||||||
|
settings_at=None,
|
||||||
|
settings_received=0,
|
||||||
)
|
)
|
||||||
d = self.devices[address]
|
d = self.devices[address]
|
||||||
d.update(adapter=adapter, rssi_dbm=rssi)
|
d.update(adapter=adapter, rssi_dbm=rssi)
|
||||||
@@ -78,9 +82,22 @@ class Service:
|
|||||||
os.replace(temporary, destination)
|
os.replace(temporary, destination)
|
||||||
self.revision += 1
|
self.revision += 1
|
||||||
|
|
||||||
|
def settings(self, address, settings):
|
||||||
|
with self.lock:
|
||||||
|
self.devices[address].update(
|
||||||
|
settings=copy.deepcopy(settings), settings_at=utc(), settings_received=self.clock()
|
||||||
|
)
|
||||||
|
self.revision += 1
|
||||||
|
|
||||||
def sample(self, address, sample):
|
def sample(self, address, sample):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
self.expire()
|
self.expire()
|
||||||
|
settings = self.devices[address].get("settings")
|
||||||
|
if settings:
|
||||||
|
sample = {
|
||||||
|
**sample,
|
||||||
|
"configured_capacity_ah": settings["values"]["nominal_capacity_ah"],
|
||||||
|
}
|
||||||
self.devices[address].update(
|
self.devices[address].update(
|
||||||
sample=copy.deepcopy(sample),
|
sample=copy.deepcopy(sample),
|
||||||
sample_at=utc(),
|
sample_at=utc(),
|
||||||
@@ -98,6 +115,8 @@ class Service:
|
|||||||
for d in self.devices.values():
|
for d in self.devices.values():
|
||||||
if today != self.day or self.clock() - d["sampled"] >= 300:
|
if today != self.day or self.clock() - d["sampled"] >= 300:
|
||||||
d.update(sample=None, sample_at=None)
|
d.update(sample=None, sample_at=None)
|
||||||
|
if today != self.day or self.clock() - d["settings_received"] >= 300:
|
||||||
|
d.update(settings=None, settings_at=None)
|
||||||
self.day = today
|
self.day = today
|
||||||
|
|
||||||
def inventory(self, node):
|
def inventory(self, node):
|
||||||
@@ -118,6 +137,8 @@ class Service:
|
|||||||
"adapter",
|
"adapter",
|
||||||
"rssi_dbm",
|
"rssi_dbm",
|
||||||
"link_generation",
|
"link_generation",
|
||||||
|
"settings",
|
||||||
|
"settings_at",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
status.update(
|
status.update(
|
||||||
@@ -125,6 +146,12 @@ class Service:
|
|||||||
address=address,
|
address=address,
|
||||||
fresh=online,
|
fresh=online,
|
||||||
compatible=supported(info),
|
compatible=supported(info),
|
||||||
|
control_available=online
|
||||||
|
and supported(info)
|
||||||
|
and info.get("hardware") == "11.XA"
|
||||||
|
and bool(d["settings"])
|
||||||
|
and address not in (self.operations.blocked if self.operations else set()),
|
||||||
|
control_locked=bool(self.operations and address in self.operations.blocked),
|
||||||
sample_ttl_s=300,
|
sample_ttl_s=300,
|
||||||
)
|
)
|
||||||
items.append(
|
items.append(
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"""Read-only JK02_32S settings; no numeric setting encoder exists here.
|
||||||
|
|
||||||
|
Offsets cross-checked with pinned ESPHome/batmon sources in the capability doc.
|
||||||
|
The entire frame remains private RAM for command readback comparison.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
from .protocol import HEADER
|
||||||
|
|
||||||
|
# name, offset, divisor, signed. Only the common 11.x fields are admitted.
|
||||||
|
FIELDS = (
|
||||||
|
("sleep_voltage_v", 6, 1000, False),
|
||||||
|
("cell_uvp_v", 10, 1000, False),
|
||||||
|
("cell_uvpr_v", 14, 1000, False),
|
||||||
|
("cell_ovp_v", 18, 1000, False),
|
||||||
|
("cell_ovpr_v", 22, 1000, False),
|
||||||
|
("balance_trigger_v", 26, 1000, False),
|
||||||
|
("soc100_voltage_v", 30, 1000, False),
|
||||||
|
("soc0_voltage_v", 34, 1000, False),
|
||||||
|
("requested_charge_voltage_v", 38, 1000, False),
|
||||||
|
("requested_float_voltage_v", 42, 1000, False),
|
||||||
|
("poweroff_voltage_v", 46, 1000, False),
|
||||||
|
("max_charge_current_a", 50, 1000, False),
|
||||||
|
("charge_ocp_delay_s", 54, 1, False),
|
||||||
|
("charge_ocp_recovery_s", 58, 1, False),
|
||||||
|
("max_discharge_current_a", 62, 1000, False),
|
||||||
|
("discharge_ocp_delay_s", 66, 1, False),
|
||||||
|
("discharge_ocp_recovery_s", 70, 1, False),
|
||||||
|
("short_circuit_recovery_s", 74, 1, False),
|
||||||
|
("max_balance_current_a", 78, 1000, False),
|
||||||
|
("charge_overtemp_c", 82, 10, True),
|
||||||
|
("charge_overtemp_recovery_c", 86, 10, True),
|
||||||
|
("discharge_overtemp_c", 90, 10, True),
|
||||||
|
("discharge_overtemp_recovery_c", 94, 10, True),
|
||||||
|
("charge_undertemp_c", 98, 10, True),
|
||||||
|
("charge_undertemp_recovery_c", 102, 10, True),
|
||||||
|
("mos_overtemp_c", 106, 10, True),
|
||||||
|
("mos_overtemp_recovery_c", 110, 10, True),
|
||||||
|
("nominal_capacity_ah", 130, 1000, False),
|
||||||
|
("short_circuit_delay_us", 134, 1, False),
|
||||||
|
("balance_start_voltage_v", 138, 1000, False),
|
||||||
|
)
|
||||||
|
SWITCHES = {"charging": (0x1D, 118), "discharging": (0x1E, 122), "balancing": (0x1F, 126)}
|
||||||
|
|
||||||
|
|
||||||
|
def decode_settings(frame):
|
||||||
|
if len(frame) != 300 or frame[:5] != HEADER + b"\x01" or sum(frame[:-1]) & 255 != frame[-1]:
|
||||||
|
raise ValueError("Invalid settings frame")
|
||||||
|
values = {
|
||||||
|
name: int.from_bytes(frame[offset : offset + 4], "little", signed=signed) / scale
|
||||||
|
for name, offset, scale, signed in FIELDS
|
||||||
|
}
|
||||||
|
values["cell_count"] = int.from_bytes(frame[114:118], "little")
|
||||||
|
switches = {
|
||||||
|
key: int.from_bytes(frame[offset : offset + 4], "little")
|
||||||
|
for key, (_, offset) in SWITCHES.items()
|
||||||
|
}
|
||||||
|
if not 1 <= values["cell_count"] <= 32 or any(v not in (0, 1) for v in switches.values()):
|
||||||
|
raise ValueError("Unsupported settings layout")
|
||||||
|
if not (
|
||||||
|
0 < values["cell_uvp_v"] < values["cell_ovp_v"] < 5
|
||||||
|
and 0 < values["nominal_capacity_ah"] < 100000
|
||||||
|
):
|
||||||
|
raise ValueError("Inconsistent settings layout")
|
||||||
|
return {
|
||||||
|
"values": values,
|
||||||
|
"switches": {key: bool(v) for key, v in switches.items()},
|
||||||
|
"fingerprint": hashlib.sha256(frame[6:299]).hexdigest(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def switch_command(name, enabled):
|
||||||
|
if name not in SWITCHES or type(enabled) is not bool:
|
||||||
|
raise ValueError("Only three boolean operating switches are supported")
|
||||||
|
data = bytes.fromhex("aa5590eb") + bytes([SWITCHES[name][0], 4, int(enabled)]) + bytes(12)
|
||||||
|
return data + bytes([sum(data) & 255])
|
||||||
|
|
||||||
|
|
||||||
|
def unchanged_except(before, after, name, enabled):
|
||||||
|
"""Compare every settings byte, excluding counter/CRC and the requested bit."""
|
||||||
|
expected = bytearray(before[6:299])
|
||||||
|
offset = SWITCHES[name][1] - 6
|
||||||
|
expected[offset : offset + 4] = int(enabled).to_bytes(4, "little")
|
||||||
|
return bytes(expected) == after[6:299]
|
||||||
@@ -93,7 +93,7 @@ def test_identity_allowlist_and_candidate_are_not_compatibility():
|
|||||||
data[:5] = HEADER + b"\x03"
|
data[:5] = HEADER + b"\x03"
|
||||||
data[6:18] = b"JK_BD6A17S6P"
|
data[6:18] = b"JK_BD6A17S6P"
|
||||||
data[30:35] = b"11.47"
|
data[30:35] = b"11.47"
|
||||||
data[90:96] = b"SECRET"
|
data[97:103] = b"SECRET"
|
||||||
info = identity(data)
|
info = identity(data)
|
||||||
assert supported(info) and "SECRET" not in json.dumps(info)
|
assert supported(info) and "SECRET" not in json.dumps(info)
|
||||||
assert not supported({**info, "firmware": "14.00"})
|
assert not supported({**info, "firmware": "14.00"})
|
||||||
|
|||||||
@@ -0,0 +1,222 @@
|
|||||||
|
"""Synthetic transport: no radio, real battery, or OS services are accessed."""
|
||||||
|
|
||||||
|
# ruff: noqa: E402
|
||||||
|
import concurrent.futures
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from jkbms_test_runtime.operations import Operations
|
||||||
|
from jkbms_test_runtime.settings import SWITCHES, decode_settings, switch_command, unchanged_except
|
||||||
|
from test_bms import HEADER, Service, frame, telemetry
|
||||||
|
|
||||||
|
|
||||||
|
def settings_frame(**switches):
|
||||||
|
data = bytearray(300)
|
||||||
|
data[:5] = HEADER + b"\x01"
|
||||||
|
for offset, value in [(10, 2800), (18, 4250), (98, -50), (114, 13), (130, 120000)]:
|
||||||
|
data[offset : offset + 4] = value.to_bytes(4, "little", signed=value < 0)
|
||||||
|
for key, (_, offset) in SWITCHES.items():
|
||||||
|
data[offset : offset + 4] = int(switches.get(key, True)).to_bytes(4, "little")
|
||||||
|
data[-1] = sum(data[:-1]) & 255
|
||||||
|
return bytes(data)
|
||||||
|
|
||||||
|
|
||||||
|
def test_encoder_cannot_address_numeric_settings_and_decoder_rejects_corruption():
|
||||||
|
raw = settings_frame()
|
||||||
|
value = decode_settings(raw)
|
||||||
|
assert value["values"]["nominal_capacity_ah"] == 120
|
||||||
|
assert value["values"]["charge_undertemp_c"] == -5
|
||||||
|
for name, (register, _) in SWITCHES.items():
|
||||||
|
for enabled in (True, False):
|
||||||
|
encoded = switch_command(name, enabled)
|
||||||
|
assert len(encoded) == 20 and encoded[:6] == bytes.fromhex("aa5590eb") + bytes(
|
||||||
|
[register, 4]
|
||||||
|
)
|
||||||
|
assert int.from_bytes(encoded[6:10], "little") == int(enabled)
|
||||||
|
assert encoded[-1] == sum(encoded[:-1]) & 255
|
||||||
|
for bad in (1, 0, None, "true", [], {}):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
switch_command(name, bad)
|
||||||
|
for name in ("soc", "voltage", "capacity", "password", "firmware", "reset", 0x6E):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
switch_command(name, True)
|
||||||
|
for bad in (raw[:-1], raw[:70] + bytes([raw[70] ^ 1]) + raw[71:], frame()):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
decode_settings(bad)
|
||||||
|
assert unchanged_except(raw, settings_frame(charging=False), "charging", False)
|
||||||
|
assert not unchanged_except(
|
||||||
|
raw, settings_frame(charging=False, balancing=False), "charging", False
|
||||||
|
)
|
||||||
|
assert telemetry(frame())["effective_capacity_ah"] == 118
|
||||||
|
assert telemetry(frame())["configured_capacity_ah"] is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def rig(tmp_path):
|
||||||
|
service = Service(tmp_path)
|
||||||
|
address = "AA:BB:CC:DD:EE:01"
|
||||||
|
service.observe(address, "hci7", -50)
|
||||||
|
service.identify(address, {"model": "JK_BD6A17S6P", "firmware": "11.47", "hardware": "11.XA"})
|
||||||
|
sample = {**telemetry(frame()), "current_a": 0, "protection_mask": 1 << 19}
|
||||||
|
service.sample(address, sample)
|
||||||
|
service.settings(address, decode_settings(settings_frame()))
|
||||||
|
reads, writes = [], []
|
||||||
|
observer = SimpleNamespace(
|
||||||
|
active={"address": address, "verified": True},
|
||||||
|
write_read=reads.append,
|
||||||
|
write_switch=lambda *args: writes.append(args),
|
||||||
|
)
|
||||||
|
operations = Operations(service, observer)
|
||||||
|
service.operations = operations
|
||||||
|
pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
||||||
|
|
||||||
|
def request(action, parameters=None):
|
||||||
|
identifier = "op_" + uuid.uuid4().hex
|
||||||
|
return dict(
|
||||||
|
operation_id=identifier,
|
||||||
|
idempotency_key=identifier,
|
||||||
|
action_id=action,
|
||||||
|
deadline_at=(datetime.now(UTC) + timedelta(seconds=20)).isoformat(),
|
||||||
|
session={
|
||||||
|
"device_id": service.devices[address]["id"],
|
||||||
|
"session_id": service.devices[address]["session"],
|
||||||
|
},
|
||||||
|
parameters=parameters or {},
|
||||||
|
)
|
||||||
|
|
||||||
|
def start(req):
|
||||||
|
future = pool.submit(operations.execute, req)
|
||||||
|
until = time.monotonic() + 1
|
||||||
|
while not operations.job and not future.done() and time.monotonic() < until:
|
||||||
|
time.sleep(0.001)
|
||||||
|
operations.tick()
|
||||||
|
return future
|
||||||
|
|
||||||
|
def receive(raw):
|
||||||
|
value = decode_settings(raw)
|
||||||
|
service.settings(address, value)
|
||||||
|
operations.received(address, raw, value)
|
||||||
|
|
||||||
|
def write_ready():
|
||||||
|
operations.job["query_at"] -= 2
|
||||||
|
operations.tick()
|
||||||
|
operations.job["read_after"] -= 1
|
||||||
|
operations.tick()
|
||||||
|
|
||||||
|
yield SimpleNamespace(
|
||||||
|
service=service,
|
||||||
|
address=address,
|
||||||
|
op=operations,
|
||||||
|
reads=reads,
|
||||||
|
writes=writes,
|
||||||
|
request=request,
|
||||||
|
start=start,
|
||||||
|
receive=receive,
|
||||||
|
write_ready=write_ready,
|
||||||
|
)
|
||||||
|
operations.finish("test teardown")
|
||||||
|
pool.shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
def test_read_and_noop_set_never_mutate(rig):
|
||||||
|
for action, params in [
|
||||||
|
("bms.read", {}),
|
||||||
|
(
|
||||||
|
"bms.control.set",
|
||||||
|
dict(
|
||||||
|
switch="charging",
|
||||||
|
enabled=True,
|
||||||
|
fingerprint=decode_settings(settings_frame())["fingerprint"],
|
||||||
|
link_generation=0,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]:
|
||||||
|
req = rig.request(action, params)
|
||||||
|
f = rig.start(req)
|
||||||
|
rig.receive(settings_frame())
|
||||||
|
assert f.result(1)["state"] == "complete"
|
||||||
|
assert rig.op.execute(req) == f.result() and not rig.writes
|
||||||
|
|
||||||
|
|
||||||
|
def test_verify_writes_only_current_values_once_and_checks_entire_readback(rig):
|
||||||
|
req = rig.request("bms.control.verify")
|
||||||
|
f = rig.start(req)
|
||||||
|
rig.receive(settings_frame())
|
||||||
|
rig.op.tick()
|
||||||
|
assert not rig.writes # query must settle first
|
||||||
|
for name in SWITCHES:
|
||||||
|
rig.write_ready()
|
||||||
|
assert rig.writes[-1] == (name, True)
|
||||||
|
rig.receive(settings_frame())
|
||||||
|
assert f.result(1)["result"]["verification"] == "same-value-only"
|
||||||
|
rig.op.execute(req)
|
||||||
|
assert len(rig.writes) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_mutation_readback_and_idempotency(rig):
|
||||||
|
params = dict(
|
||||||
|
switch="balancing",
|
||||||
|
enabled=False,
|
||||||
|
fingerprint=decode_settings(settings_frame())["fingerprint"],
|
||||||
|
link_generation=0,
|
||||||
|
)
|
||||||
|
req = rig.request("bms.control.set", params)
|
||||||
|
f = rig.start(req)
|
||||||
|
rig.receive(settings_frame())
|
||||||
|
rig.write_ready()
|
||||||
|
rig.receive(settings_frame(balancing=False))
|
||||||
|
assert f.result(1)["state"] == "complete" and rig.writes == [("balancing", False)]
|
||||||
|
assert rig.op.execute(req) == f.result()
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
rig.op.execute({**req, "parameters": {**params, "enabled": True}})
|
||||||
|
|
||||||
|
|
||||||
|
def test_uncertain_disconnect_and_side_effect_block_future_writes(rig):
|
||||||
|
f = rig.start(rig.request("bms.control.verify"))
|
||||||
|
rig.receive(settings_frame())
|
||||||
|
rig.write_ready()
|
||||||
|
rig.receive(settings_frame(balancing=False))
|
||||||
|
assert f.result(1)["state"] == "unknown"
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
rig.op.execute(rig.request("bms.control.verify"))
|
||||||
|
f = rig.start(rig.request("bms.read"))
|
||||||
|
rig.receive(settings_frame())
|
||||||
|
assert f.result(1)["state"] == "complete" # reading remains possible
|
||||||
|
|
||||||
|
|
||||||
|
def test_old_session_deadline_generation_fingerprint_and_fault_rejected(rig):
|
||||||
|
base = rig.request("bms.read")
|
||||||
|
for req in (
|
||||||
|
{**base, "deadline_at": "2000-01-01T00:00:00Z"},
|
||||||
|
{**base, "session": {**base["session"], "session_id": "old"}},
|
||||||
|
{**base, "action_id": "bms.reset"},
|
||||||
|
):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
rig.op.execute(req)
|
||||||
|
req = rig.request(
|
||||||
|
"bms.control.set",
|
||||||
|
dict(switch="charging", enabled=False, fingerprint="old", link_generation=0),
|
||||||
|
)
|
||||||
|
f = rig.start(req)
|
||||||
|
rig.receive(settings_frame())
|
||||||
|
assert f.result(1)["state"] == "error" and not rig.writes
|
||||||
|
f = rig.start(rig.request("bms.control.verify"))
|
||||||
|
rig.receive(settings_frame())
|
||||||
|
rig.service.devices[rig.address]["sample"]["protection_mask"] = 2
|
||||||
|
rig.op.job["query_at"] -= 2
|
||||||
|
rig.op.tick()
|
||||||
|
assert f.result(1)["state"] == "error" and not rig.writes
|
||||||
|
|
||||||
|
|
||||||
|
def test_transport_loss_after_write_is_unknown_without_retry(rig):
|
||||||
|
f = rig.start(rig.request("bms.control.verify"))
|
||||||
|
rig.receive(settings_frame())
|
||||||
|
rig.write_ready()
|
||||||
|
rig.op.finish("connection lost")
|
||||||
|
assert f.result(1)["state"] == "unknown" and len(rig.writes) == 1
|
||||||
|
for _ in range(3):
|
||||||
|
rig.op.tick()
|
||||||
|
assert len(rig.writes) == 1
|
||||||
@@ -15,7 +15,7 @@ from functools import wraps
|
|||||||
|
|
||||||
|
|
||||||
def ephemeral(action):
|
def ephemeral(action):
|
||||||
return action.startswith(("vesc.samples.", "vesc.qml.", "can."))
|
return action.startswith(("vesc.samples.", "vesc.qml.", "can.", "bms."))
|
||||||
|
|
||||||
|
|
||||||
def synchronized(method):
|
def synchronized(method):
|
||||||
@@ -83,7 +83,10 @@ class SensorTransient:
|
|||||||
).encode()
|
).encode()
|
||||||
if len(raw) <= 16384:
|
if len(raw) <= 16384:
|
||||||
self.bms[key] = (previous[0] if same else self.clock(), raw)
|
self.bms[key] = (previous[0] if same else self.clock(), raw)
|
||||||
status.update(sample=None, sample_at=None, fresh=False, rssi_dbm=None)
|
status.update(
|
||||||
|
sample=None, sample_at=None, fresh=False, rssi_dbm=None,
|
||||||
|
settings=None, settings_at=None, control_available=False,
|
||||||
|
)
|
||||||
item.update(bms_status=status, online=False)
|
item.update(bms_status=status, online=False)
|
||||||
items.append(item)
|
items.append(item)
|
||||||
result["sensor_state"] = {**row["sensor_state"], "items": items}
|
result["sensor_state"] = {**row["sensor_state"], "items": items}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from missioncore_plugin_sdk.v0alpha2.session import DeviceSessionSnapshot
|
|||||||
from .trust import PairingError
|
from .trust import PairingError
|
||||||
|
|
||||||
ACTIONS = {
|
ACTIONS = {
|
||||||
|
"bms.read", "bms.control.verify", "bms.control.set",
|
||||||
"can.status", "can.configure", "can.start", "can.stop", "can.clear", "can.transmit.preview", "can.transmit.apply", "can.transmit.stop",
|
"can.status", "can.configure", "can.start", "can.stop", "can.clear", "can.transmit.preview", "can.transmit.apply", "can.transmit.stop",
|
||||||
"prepare",
|
"prepare",
|
||||||
"details",
|
"details",
|
||||||
|
|||||||
Reference in New Issue
Block a user