feat(bms): add read-only diagnostics and guarded operating switch commands

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 17:14:54 +03:00
parent ab8e977f11
commit 42213001ba
19 changed files with 919 additions and 40 deletions
+18 -14
View File
@@ -1,8 +1,11 @@
# JK BMS: доступные данные и потенциал управления
Срез источников: 2026-11-04. Это исследование возможностей, не приёмка новых
команд на аккумуляторе. Настройки BMS не менялись. После просьбы владельца
проверки оборудования и пробное выключение не запускались.
Обновлено 2026-11-04 после поставки Node 0.8.53-113. Дополнительные поля
и чтение настроек внедрены. Команды заряда, разряда и балансировки доступны
с подтверждением; на реальной BMS проверена запись прежних значений и полное
обратное чтение без изменения настроек. Фактическое отключение MOS и выключение
борта не выполнялись. Точный протокол, аудит исходников и ограничения:
[контракт управления](47_JK_BMS_OPERATING_CONTROL.md).
## Наш профиль и уже реализованное чтение
@@ -19,15 +22,15 @@
[контракт интеграции](JK_BMS_BLUETOOTH.md). Это поля нашего декодера, а не
обещание всех возможностей семейства JK.
## Что можно добавить для наблюдения
## Дополнительные данные, внедрённые в Node113
| Возможность | Практическая ценность и граница подтверждения |
|---|---|
| Минимальная, максимальная и средняя ячейка, номер наиболее отклоняющейся | Можно вычислять из уже получаемых напряжений, без новых команд BMS. |
| Сопротивления измерительных/балансировочных цепей и маска проблем проводов | В описании JK02_32S есть соответствующие поля. Их ещё нужно проверить на нашей 11.47; нельзя называть их лабораторным внутренним сопротивлением ячеек. |
| Понятные причины защиты | Расшифровка битов вместо HEX; нужны подтверждённая раскладка этой версии и сохранение неизвестных битов. |
| Текущие пороги напряжения, тока, температуры, настройки балансировки и сна | Отдельный кадр настроек. Наши запросы уже включают 0x96, но текущий декодер использует телеметрию, а кадр настроек пока не публикует. |
| Серийный номер BMS, показатель здоровья от BMS | В upstream-парсере предусмотрены поля. Это номер контроллера и оценка его прошивки, не артикул CATL и не измеренная остаточная ёмкость. |
| Минимальная, максимальная и средняя ячейка, номер наиболее отклоняющейся | Вычисляются из полученных напряжений, без новых команд BMS. |
| Сопротивления измерительных/балансировочных цепей и маска проблем проводов | Прочитаны на 11.47; это измерительная цепь, не лабораторное внутреннее сопротивление ячеек. |
| Понятные причины защиты | Расшифровка JK02, исходный HEX и неизвестные биты сохранены. |
| Текущие пороги напряжения, тока, температуры, настройки балансировки и сна | Кадр настроек 0x01 публикуется после запроса 0x96. Числовые параметры доступны только для чтения. |
| Серийный номер BMS, показатель здоровья от BMS | Поля добавлены в allowlist декодера. Это номер контроллера и оценка его прошивки, не артикул CATL и не измеренная остаточная ёмкость. |
Основания: [описание 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),
@@ -39,7 +42,7 @@
фактическую ёмкость из нынешнего потока получить нельзя. Время до разряда
можно только оценивать по нагрузке; при нулевом токе полезной оценки нет.
## Управление: существует в проектах, ещё не принято для нашей прошивки
## Управление и границы проверки
ESPHome предоставляет переключение зарядного и разрядного MOS, балансировки,
сна, ряд порогов и калибровок. В примере также есть команды перезапуска,
@@ -55,10 +58,11 @@ ESPHome предоставляет переключение зарядного
изменения до выяснения состояния.
[Границы поддержки batmon](https://github.com/fl4p/batmon-ha/blob/master/doc/JK-Settings.md).
Для Mission Core следующий полезный шаг — расширение чтения в существующем
плагине. Если позже вводить управление, необходимы свежий сеанс, отдельное
подтверждение, чтение результата и запрет повторного исполнения старой команды
после переподключения. Порог токовой защиты не является регулятором мощности
Mission Core реализует только три рабочих переключателя: заряд, разряд и
балансировка. Свежий сеанс, отдельное подтверждение, fingerprint настроек,
обратное чтение и запрет повторного исполнения старой команды обязательны.
Проверка на нашей плате ограничена записью уже установленных значений; фактическое
изменение MOS не проверялось. Порог токовой защиты не является регулятором мощности
зарядника или двигателя. Отключение разрядного MOS может обесточить сам борт;
последующее дистанционное включение тогда требует независимого питания.
Выключение ОС через кнопку борта — другая операция, оно не отключает MOS BMS.
+90
View File
@@ -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.