Auto-detect BMS packs and hide empty ones

- app.py: scan all 15 pack slots (600-809) on first request and every 5
  minutes; packs with zero voltage and SOC are dropped, and later reads
  only cover the active packs
- Per-pack byte-swap detection (SOC out of range raw but valid swapped)
  instead of assuming pack 2 is swapped
- API now returns bms_packs[] in place of the bms2_* fields
- index.html renders one section per connected pack, none if empty

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Vlad Doloman
2026-11-06 23:23:53 +02:00
co-authored by Claude Sonnet 5.5
parent 48a57cc58c
commit 76b22ea10b
3 changed files with 121 additions and 66 deletions
+1 -1
View File
@@ -5,7 +5,7 @@ A Flask-based application for monitoring Deye Inverters (and compatible models)
## Features
- **Real-time Monitoring**: Reads critical data such as Input/Output Voltage, Grid/Load Currents, Battery SOC, Temperature, and Power.
- **BMS Integration**: Retrieves detailed Battery Management System (BMS) data for up to two battery packs.
- **BMS Integration**: Retrieves Battery Management System (BMS) data for any of up to 15 battery packs. All pack slots are scanned at start-up and every 5 minutes; packs that report only zeros are hidden, and byte-swapped packs are detected automatically.
- **Web Interface**: Provides a user-friendly dashboard to view inverter status (served at `/`).
- **JSON API**: Exposes raw data via a RESTful endpoint (`/api/data`) for integration with other systems.
- **PDF Utility**: Includes a tool to extract register information from Deye Modbus PDF manuals.
+74 -17
View File
@@ -18,11 +18,68 @@ CACHE_TTL = 2.0 # seconds; the logger only tolerates one session at a time
_lock = threading.Lock()
_cache = {"time": 0.0, "data": None}
# BMS packs: 14 registers each starting at 600 (pack 1 = 600-613 ... pack 15 = 796-809)
BMS_BASE = 600
BMS_PACK_SIZE = 14
BMS_MAX_PACKS = 15
BMS_RESCAN_INTERVAL = 300.0 # seconds between full scans for connected packs
MAX_READ_CHUNK = 100 # registers per Modbus read
# Pack numbers (1-based) that reported data at the last scan; None = not scanned yet.
_bms_state = {"packs": None, "scanned": 0.0}
def to_signed(val):
return val if val < 32768 else val - 65536
def swap_bytes(raw):
return ((raw & 0xFF) << 8) | (raw >> 8)
def read_registers(inverter, start, count):
"""Read `count` holding registers in chunks the logger handles reliably."""
values = []
while len(values) < count:
chunk = min(MAX_READ_CHUNK, count - len(values))
values.extend(inverter.read_holding_registers(register_addr=start + len(values), quantity=chunk))
return values
def pack_registers(bms, pack):
i = (pack - 1) * BMS_PACK_SIZE
return bms[i:i + BMS_PACK_SIZE]
def detect_active_packs(bms):
"""Packs whose module voltage or SOC register is non-zero.
Empty packs read as zeros apart from a constant placeholder in the temperature
register, so only voltage (offset 0) and SOC (offset 3) are checked. Zero is the
same with or without byte swapping.
"""
return [n for n in range(1, len(bms) // BMS_PACK_SIZE + 1)
if pack_registers(bms, n)[0] != 0 or pack_registers(bms, n)[3] != 0]
def parse_bms_pack(pack, regs):
"""Decode one pack. SOC is in 0.1% (<= 1000). Some packs (seen on pack 2) are
reported byte-swapped by the firmware, so if the raw SOC is out of range but
becomes valid after swapping, swap every register of the pack back."""
soc_raw = regs[3]
if soc_raw > 1000 and swap_bytes(soc_raw) <= 1000:
regs = [swap_bytes(r) for r in regs]
return {
"pack": pack,
"voltage": round(regs[0] * 0.01, 2), # 0.01V
"current": round(to_signed(regs[1]) * 0.1, 1), # 0.1A, negative = discharge
"temp": round((regs[2] - 1000) * 0.1, 1), # offset +1000, 0.1C
"soc": round(regs[3] * 0.1, 1), # 0.1%
"charge_voltage": round(regs[6] * 0.01, 2), # 0.01V
"charge_current_limit": round(regs[7] * 0.1, 1), # 0.1A, BMS-requested limit
}
def get_inverter_data():
"""
Connects to the inverter and reads voltage registers.
@@ -41,13 +98,22 @@ def get_inverter_data():
# Reading blocks:
# Block 1: 150 - 216 (67 registers) - Voltages, Currents, Battery, PV, Control
# Block 2: 600 - 627 (28 registers) - BMS Data
# Block 2: 600 - 809 (up to 15 packs x 14 registers) - BMS Data
# Block 3: 245 (1 register) - Max Grid Output
# Block 4: 292 - 293 (2 registers) - Peak Shaving
# Block 5: 312 - 325 (14 registers) - Lithium battery / BMS limits
block1 = inverter.read_holding_registers(register_addr=150, quantity=67)
block2 = inverter.read_holding_registers(register_addr=600, quantity=28)
# BMS: scan all possible packs on first use and every BMS_RESCAN_INTERVAL;
# otherwise only read up to the last pack that was found.
now = time.monotonic()
scan = (_bms_state["packs"] is None
or now - _bms_state["scanned"] >= BMS_RESCAN_INTERVAL)
if scan:
bms_count = BMS_MAX_PACKS
else:
bms_count = max(_bms_state["packs"], default=0)
bms = read_registers(inverter, BMS_BASE, bms_count * BMS_PACK_SIZE) if bms_count else []
block3 = inverter.read_holding_registers(register_addr=245, quantity=1)
block4 = inverter.read_holding_registers(register_addr=292, quantity=2)
block5 = inverter.read_holding_registers(register_addr=312, quantity=14)
@@ -82,21 +148,12 @@ def get_inverter_data():
data["max_discharge_current"] = block1[61] # 211
data["batt_charge_efficiency"] = round(block1[66] * 0.1, 1) # 216 (0.1%)
# Block 2 Parsing (BMS 600-627, index = register - 600)
# Pack 1 (600-613) is not connected on this system and reads as zeros, so it
# is not exposed. Pack 2 (614-627) carries the real battery data, but this
# firmware reports every register byte-swapped (e.g. SOC 80.0% reads 0x2003
# instead of 0x0320), so swap the bytes back before scaling.
def bms2(i):
raw = block2[i]
return ((raw & 0xFF) << 8) | (raw >> 8)
data["bms2_voltage"] = round(bms2(14) * 0.01, 2) # 614 (0.01V)
data["bms2_current"] = round(to_signed(bms2(15)) * 0.1, 1) # 615 (0.1A, negative = discharge)
data["bms2_temp"] = round((bms2(16) - 1000) * 0.1, 1) # 616 (offset +1000, 0.1C)
data["bms2_soc"] = round(bms2(17) * 0.1, 1) # 617 (0.1%)
data["bms2_charge_voltage"] = round(bms2(20) * 0.01, 2) # 620 (0.01V)
data["bms2_charge_current_limit"] = round(bms2(21) * 0.1, 1) # 621 (0.1A, BMS-requested limit)
# Block 2 Parsing (BMS packs)
if scan:
_bms_state["packs"] = detect_active_packs(bms)
_bms_state["scanned"] = now
data["bms_packs"] = [parse_bms_pack(n, pack_registers(bms, n))
for n in _bms_state["packs"] if n * BMS_PACK_SIZE <= len(bms)]
# Block 3 Parsing (245)
data["max_grid_output_power"] = block3[0] # 245
+46 -48
View File
@@ -35,7 +35,13 @@
margin: 10px 0 20px;
}
body>h2 {
#bms-container {
width: 100%;
max-width: 1000px;
}
body>h2,
#bms-container>h2 {
width: 100%;
max-width: 1000px;
margin: 30px 0 10px;
@@ -260,45 +266,7 @@
</div>
</div>
<h2>BMS Data</h2>
<div class="dashboard">
<div class="card">
<h2>BMS SOC</h2>
<div class="value-container loading">
<span class="value" id="bms2-soc">--</span><span class="unit">%</span>
</div>
</div>
<div class="card">
<h2>BMS Voltage</h2>
<div class="value-container loading">
<span class="value" id="bms2-voltage">--</span><span class="unit">V</span>
</div>
</div>
<div class="card">
<h2>BMS Current</h2>
<div class="value-container loading">
<span class="value" id="bms2-current">--</span><span class="unit">A</span>
</div>
</div>
<div class="card">
<h2>BMS Temp</h2>
<div class="value-container loading">
<span class="value" id="bms2-temp">--</span><span class="unit">°C</span>
</div>
</div>
<div class="card">
<h2>BMS Charge Voltage</h2>
<div class="value-container loading">
<span class="value" id="bms2-charge-voltage">--</span><span class="unit">V</span>
</div>
</div>
<div class="card">
<h2>BMS Charge I Limit</h2>
<div class="value-container loading">
<span class="value" id="bms2-charge-current-limit">--</span><span class="unit">A</span>
</div>
</div>
</div>
<div id="bms-container"></div>
<h2>Advanced Control & Limits</h2>
<div class="dashboard">
@@ -394,6 +362,42 @@
9: 'Tianbangda 485', 10: 'Shenggao CAN'
};
const BMS_FIELDS = [
['soc', 'SOC', '%'], ['voltage', 'Voltage', 'V'], ['current', 'Current', 'A'],
['temp', 'Temp', '°C'], ['charge_voltage', 'Charge Voltage', 'V'],
['charge_current_limit', 'Charge I Limit', 'A']
];
// One section per connected BMS pack; nothing is shown if no pack reports data.
function renderBms(packs) {
const container = document.getElementById('bms-container');
container.replaceChildren();
for (const pack of packs) {
const title = document.createElement('h2');
title.textContent = 'BMS Pack ' + pack.pack;
const grid = document.createElement('div');
grid.className = 'dashboard';
for (const [key, label, unit] of BMS_FIELDS) {
const card = document.createElement('div');
card.className = 'card';
const h = document.createElement('h2');
h.textContent = label;
const box = document.createElement('div');
box.className = 'value-container';
const val = document.createElement('span');
val.className = 'value';
val.textContent = pack[key];
const u = document.createElement('span');
u.className = 'unit';
u.textContent = unit;
box.append(val, u);
card.append(h, box);
grid.append(card);
}
container.append(title, grid);
}
}
async function fetchData() {
try {
const response = await fetch('/api/data', { signal: AbortSignal.timeout(15000) });
@@ -428,13 +432,7 @@
document.getElementById('max-charge').textContent = data.max_charge_current;
document.getElementById('max-discharge').textContent = data.max_discharge_current;
// BMS Data (pack 2)
document.getElementById('bms2-soc').textContent = data.bms2_soc;
document.getElementById('bms2-voltage').textContent = data.bms2_voltage;
document.getElementById('bms2-current').textContent = data.bms2_current;
document.getElementById('bms2-temp').textContent = data.bms2_temp;
document.getElementById('bms2-charge-voltage').textContent = data.bms2_charge_voltage;
document.getElementById('bms2-charge-current-limit').textContent = data.bms2_charge_current_limit;
renderBms(data.bms_packs || []);
// Advanced Control
document.getElementById('max-grid-output').textContent = data.max_grid_output_power;
@@ -465,7 +463,7 @@
console.error('Error fetching data:', error);
statusDot.className = 'status-indicator error';
statusText.textContent = 'Error: ' + error.message;
valueContainers.forEach(el => el.classList.add('loading'));
document.querySelectorAll('.value-container').forEach(el => el.classList.add('loading'));
}
}