Add dashboard editor for registers 230 and 293
- writable_registers.py: shared whitelist, ranges and defaults (230: 0-115 A, 293: 0-6500 W; defaults 43 and 4500) with strict validate_write() - app.py: POST /api/registers validates everything before writing, writes under the inverter lock, reads each register back to verify; also reads register 230 for display - index.html: Settings section with per-register Set, Default button, client-side digit/range checks and a confirm dialog - read_registers.py: use the shared limits; README documents the feature Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
5f1849af4d
commit
a6f8295d0e
@@ -7,6 +7,7 @@ A Flask-based application for monitoring Deye Inverters (and compatible models)
|
||||
- **Real-time Monitoring**: Reads critical data such as Input/Output Voltage, Grid/Load Currents, Battery SOC, Temperature, and Power.
|
||||
- **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 `/`).
|
||||
- **Settings Editor**: The dashboard can change registers 230 (grid charge current, 0–115 A) and 293 (grid peak shaving power, 0–6500 W), with strict validation on both the page and the server, read-back verification, and a **Default** button (43 A / 4500 W). Limits live in `writable_registers.py`. There is no authentication, so only expose the app on a trusted network.
|
||||
- **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.
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import threading
|
||||
import time
|
||||
|
||||
from flask import Flask, jsonify, render_template
|
||||
from flask import Flask, jsonify, render_template, request
|
||||
from pysolarmanv5 import PySolarmanV5
|
||||
from writable_registers import WRITABLE, validate_write
|
||||
try:
|
||||
import config
|
||||
except ImportError:
|
||||
@@ -80,6 +81,17 @@ def parse_bms_pack(pack, regs):
|
||||
}
|
||||
|
||||
|
||||
def connect():
|
||||
return PySolarmanV5(
|
||||
config.INVERTER_IP,
|
||||
config.INVERTER_SERIAL,
|
||||
port=config.INVERTER_PORT,
|
||||
mb_slave_id=config.INVERTER_SLAVE_ID,
|
||||
socket_timeout=SOCKET_TIMEOUT,
|
||||
verbose=False
|
||||
)
|
||||
|
||||
|
||||
def get_inverter_data():
|
||||
"""
|
||||
Connects to the inverter and reads voltage registers.
|
||||
@@ -87,14 +99,7 @@ def get_inverter_data():
|
||||
"""
|
||||
inverter = None
|
||||
try:
|
||||
inverter = PySolarmanV5(
|
||||
config.INVERTER_IP,
|
||||
config.INVERTER_SERIAL,
|
||||
port=config.INVERTER_PORT,
|
||||
mb_slave_id=config.INVERTER_SLAVE_ID,
|
||||
socket_timeout=SOCKET_TIMEOUT,
|
||||
verbose=False
|
||||
)
|
||||
inverter = connect()
|
||||
|
||||
# Reading blocks:
|
||||
# Block 1: 150 - 216 (67 registers) - Voltages, Currents, Battery, PV, Control
|
||||
@@ -116,6 +121,7 @@ def get_inverter_data():
|
||||
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)
|
||||
block6 = inverter.read_holding_registers(register_addr=230, quantity=1)
|
||||
block5 = inverter.read_holding_registers(register_addr=312, quantity=14)
|
||||
|
||||
data = {}
|
||||
@@ -158,6 +164,9 @@ def get_inverter_data():
|
||||
# Block 3 Parsing (245)
|
||||
data["max_grid_output_power"] = block3[0] # 245
|
||||
|
||||
# Register 230 (writable)
|
||||
data["grid_charge_current"] = block6[0] # 230 (1A)
|
||||
|
||||
# Block 4 Parsing (292-293)
|
||||
data["gen_peak_shaving_power"] = block4[0] # 292
|
||||
data["grid_peak_shaving_power"] = block4[1] # 293
|
||||
@@ -204,9 +213,37 @@ def get_cached_data():
|
||||
_cache["time"] = time.monotonic()
|
||||
return data
|
||||
|
||||
def write_inverter_registers(writes):
|
||||
"""Write already-validated {register: value} pairs, reading each back to verify.
|
||||
|
||||
Returns (applied, error): `applied` maps register -> value confirmed by read-back,
|
||||
`error` is a message for the first failure (None on success).
|
||||
"""
|
||||
applied = {}
|
||||
inverter = None
|
||||
try:
|
||||
inverter = connect()
|
||||
for reg, value in writes.items():
|
||||
inverter.write_multiple_holding_registers(reg, [value])
|
||||
readback = inverter.read_holding_registers(register_addr=reg, quantity=1)
|
||||
if not readback or readback[0] != value:
|
||||
got = readback[0] if readback else None
|
||||
return applied, f"Register {reg}: wrote {value} but read back {got}"
|
||||
applied[reg] = readback[0]
|
||||
return applied, None
|
||||
except Exception as e:
|
||||
return applied, f"{type(e).__name__}: {e}"
|
||||
finally:
|
||||
if inverter is not None:
|
||||
try:
|
||||
inverter.disconnect()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
return render_template('index.html')
|
||||
return render_template('index.html', writable=WRITABLE)
|
||||
|
||||
@app.route('/api/data')
|
||||
def api_data():
|
||||
@@ -214,5 +251,37 @@ def api_data():
|
||||
status = 200 if data.get("status") == "success" else 502
|
||||
return jsonify(data), status
|
||||
|
||||
@app.route('/api/registers', methods=['POST'])
|
||||
def api_registers():
|
||||
"""Write whitelisted registers. Body: {"writes": {"230": 43, "293": 4500}}.
|
||||
|
||||
All values are validated before anything is written. Requiring a JSON body means
|
||||
a cross-site form post cannot trigger this (a cross-origin fetch needs a CORS
|
||||
preflight, which this app does not grant).
|
||||
"""
|
||||
body = request.get_json(silent=True)
|
||||
raw = body.get("writes") if isinstance(body, dict) else None
|
||||
if not isinstance(raw, dict) or not raw:
|
||||
return jsonify({"status": "error", "message": 'Body must be {"writes": {"<register>": <int>}}'}), 400
|
||||
|
||||
writes = {}
|
||||
for key, value in raw.items():
|
||||
if not (isinstance(key, str) and key.isascii() and key.isdecimal()):
|
||||
return jsonify({"status": "error", "message": f"Invalid register {key!r}"}), 400
|
||||
reg = int(key)
|
||||
error = validate_write(reg, value)
|
||||
if error:
|
||||
return jsonify({"status": "error", "message": error}), 400
|
||||
writes[reg] = value
|
||||
|
||||
with _lock:
|
||||
applied, error = write_inverter_registers(writes)
|
||||
_cache["data"] = None # force a fresh read after any write attempt
|
||||
|
||||
if error:
|
||||
return jsonify({"status": "error", "message": error, "applied": applied}), 502
|
||||
return jsonify({"status": "success", "applied": applied})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=False, host='0.0.0.0')
|
||||
|
||||
@@ -88,6 +88,73 @@
|
||||
margin-left: 5px;
|
||||
}
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.setting-row input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 8px 10px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #555;
|
||||
background: #1a1a1a;
|
||||
color: #fff;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.setting-row input.invalid {
|
||||
border-color: #ff4444;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 8px 14px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
background: var(--secondary-accent);
|
||||
color: #fff;
|
||||
font-size: 0.95rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
button.secondary {
|
||||
background: #555;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin-top: 8px;
|
||||
font-size: 0.8rem;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.settings-actions {
|
||||
width: 100%;
|
||||
max-width: 1000px;
|
||||
margin-top: 15px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
#write-msg {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
#write-msg.ok {
|
||||
color: #00ff88;
|
||||
}
|
||||
|
||||
#write-msg.err {
|
||||
color: #ff4444;
|
||||
}
|
||||
|
||||
.status-bar {
|
||||
margin-top: 40px;
|
||||
padding: 10px 20px;
|
||||
@@ -268,6 +335,28 @@
|
||||
|
||||
<div id="bms-container"></div>
|
||||
|
||||
<h2>Settings</h2>
|
||||
<div class="dashboard" id="settings">
|
||||
{% for reg, spec in writable.items() %}
|
||||
<div class="card" data-reg="{{ reg }}">
|
||||
<h2>{{ spec.label }} (reg {{ reg }})</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="current-{{ reg }}">--</span><span class="unit">{{ spec.unit }}</span>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<input type="text" inputmode="numeric" id="input-{{ reg }}" autocomplete="off"
|
||||
aria-label="New value for register {{ reg }}">
|
||||
<button type="button" id="set-{{ reg }}">Set</button>
|
||||
</div>
|
||||
<div class="hint">Allowed: {{ spec.min }}–{{ spec.max }} {{ spec.unit }} (default {{ spec.default }})</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="settings-actions">
|
||||
<button type="button" class="secondary" id="set-defaults">Default</button>
|
||||
<span id="write-msg"></span>
|
||||
</div>
|
||||
|
||||
<h2>Advanced Control & Limits</h2>
|
||||
<div class="dashboard">
|
||||
<div class="card">
|
||||
@@ -362,6 +451,94 @@
|
||||
9: 'Tianbangda 485', 10: 'Shenggao CAN'
|
||||
};
|
||||
|
||||
// ---- Writable settings ----
|
||||
const WRITABLE = {{ writable | tojson }};
|
||||
const CURRENT_FIELDS = { 230: 'grid_charge_current', 293: 'grid_peak_shaving_power' };
|
||||
const writeMsg = document.getElementById('write-msg');
|
||||
const dirty = {};
|
||||
|
||||
// Strict check, mirrors the server: digits only, integer, inside the allowed range.
|
||||
function checkValue(reg, text) {
|
||||
const spec = WRITABLE[reg];
|
||||
if (!/^\d+$/.test(text.trim())) return 'Enter a whole number (digits only)';
|
||||
const n = Number(text.trim());
|
||||
if (!Number.isSafeInteger(n) || n < spec.min || n > spec.max) {
|
||||
return 'Must be ' + spec.min + '\u2013' + spec.max + ' ' + spec.unit;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function showMsg(text, ok) {
|
||||
writeMsg.textContent = text;
|
||||
writeMsg.className = ok ? 'ok' : 'err';
|
||||
}
|
||||
|
||||
function setBusy(busy) {
|
||||
document.querySelectorAll('#settings button, #set-defaults').forEach(b => b.disabled = busy);
|
||||
}
|
||||
|
||||
async function writeRegisters(writes) {
|
||||
const summary = Object.entries(writes)
|
||||
.map(([reg, v]) => WRITABLE[reg].label + ' (reg ' + reg + ') = ' + v + ' ' + WRITABLE[reg].unit)
|
||||
.join('\n');
|
||||
if (!confirm('Write to the inverter?\n\n' + summary)) return;
|
||||
setBusy(true);
|
||||
showMsg('Writing...', true);
|
||||
try {
|
||||
const response = await fetch('/api/registers', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ writes }),
|
||||
signal: AbortSignal.timeout(30000)
|
||||
});
|
||||
let result;
|
||||
try { result = await response.json(); } catch (e) { throw new Error('HTTP ' + response.status); }
|
||||
if (result.status !== 'success') throw new Error(result.message || 'Write failed');
|
||||
for (const reg of Object.keys(result.applied)) {
|
||||
dirty[reg] = false;
|
||||
document.getElementById('input-' + reg).value = result.applied[reg];
|
||||
document.getElementById('current-' + reg).textContent = result.applied[reg];
|
||||
}
|
||||
showMsg('Written and verified: ' + Object.entries(result.applied).map(([r, v]) => r + '=' + v).join(', '), true);
|
||||
} catch (error) {
|
||||
showMsg('Error: ' + error.message, false);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
for (const reg of Object.keys(WRITABLE)) {
|
||||
const input = document.getElementById('input-' + reg);
|
||||
input.addEventListener('input', () => {
|
||||
dirty[reg] = true;
|
||||
input.classList.toggle('invalid', input.value !== '' && checkValue(reg, input.value) !== null);
|
||||
});
|
||||
document.getElementById('set-' + reg).addEventListener('click', () => {
|
||||
const problem = checkValue(reg, input.value);
|
||||
if (problem) {
|
||||
input.classList.add('invalid');
|
||||
showMsg('Register ' + reg + ': ' + problem, false);
|
||||
return;
|
||||
}
|
||||
writeRegisters({ [reg]: Number(input.value.trim()) });
|
||||
});
|
||||
}
|
||||
|
||||
document.getElementById('set-defaults').addEventListener('click', () => {
|
||||
const writes = {};
|
||||
for (const [reg, spec] of Object.entries(WRITABLE)) writes[reg] = spec.default;
|
||||
writeRegisters(writes);
|
||||
});
|
||||
|
||||
// Show the inverter's current values; don't overwrite a value the user is typing.
|
||||
function updateSettings(data) {
|
||||
for (const [reg, field] of Object.entries(CURRENT_FIELDS)) {
|
||||
if (data[field] === undefined) continue;
|
||||
document.getElementById('current-' + reg).textContent = data[field];
|
||||
if (!dirty[reg]) document.getElementById('input-' + reg).value = data[field];
|
||||
}
|
||||
}
|
||||
|
||||
const BMS_FIELDS = [
|
||||
['soc', 'SOC', '%'], ['voltage', 'Voltage', 'V'], ['current', 'Current', 'A'],
|
||||
['temp', 'Temp', '°C'], ['charge_voltage', 'Charge Voltage', 'V'],
|
||||
@@ -433,6 +610,7 @@
|
||||
document.getElementById('max-discharge').textContent = data.max_discharge_current;
|
||||
|
||||
renderBms(data.bms_packs || []);
|
||||
updateSettings(data);
|
||||
|
||||
// Advanced Control
|
||||
document.getElementById('max-grid-output').textContent = data.max_grid_output_power;
|
||||
|
||||
@@ -116,15 +116,12 @@ if INVERTER_IP is None or INVERTER_SERIAL is None:
|
||||
# Registers to read
|
||||
REGISTERS = [227, 230, 292, 293]
|
||||
|
||||
# Writable registers whitelist with validation ranges
|
||||
# Format: {register_number: (min_value, max_value)}
|
||||
# These are deliberately tighter than the manual (Deye Modbus V118) allows:
|
||||
# 230 = grid charge current of battery, 1 A, manual range 0-185
|
||||
# 293 = grid peak shaving power, 1 W, manual range 0-16000
|
||||
WRITABLE_REGISTERS = {
|
||||
230: (0, 115),
|
||||
293: (0, 6500),
|
||||
}
|
||||
# Writable registers whitelist with validation ranges, shared with the dashboard.
|
||||
# Format: {register_number: (min_value, max_value)}; see writable_registers.py for
|
||||
# the register meanings and why the limits are tighter than the manual's.
|
||||
from writable_registers import WRITABLE # noqa: E402 (sys.path set above)
|
||||
|
||||
WRITABLE_REGISTERS = {reg: (spec["min"], spec["max"]) for reg, spec in WRITABLE.items()}
|
||||
|
||||
|
||||
def validate_writable_registers():
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Registers that may be written, with their allowed ranges and defaults.
|
||||
|
||||
Single source of truth shared by the dashboard (app.py) and the CLI tool
|
||||
(test/read_registers.py). The limits are deliberately tighter than the manual
|
||||
(Deye Modbus V118) allows.
|
||||
"""
|
||||
|
||||
WRITABLE = {
|
||||
230: { # grid charge current of battery, manual range 0-185
|
||||
"label": "Grid Charge Current",
|
||||
"unit": "A",
|
||||
"min": 0,
|
||||
"max": 115,
|
||||
"default": 43,
|
||||
},
|
||||
293: { # grid peak shaving power, manual range 0-16000
|
||||
"label": "Grid Peak Shaving Power",
|
||||
"unit": "W",
|
||||
"min": 0,
|
||||
"max": 6500,
|
||||
"default": 4500,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def validate_write(register, value):
|
||||
"""Return an error message if (register, value) must not be written, else None.
|
||||
|
||||
Strict: the register must be whitelisted and the value must be a real JSON/Python
|
||||
integer (not a bool, float or string) inside the register's range.
|
||||
"""
|
||||
if type(register) is not int or register not in WRITABLE:
|
||||
return f"Register {register!r} is not writable (allowed: {sorted(WRITABLE)})"
|
||||
if type(value) is not int:
|
||||
return f"Register {register}: value must be an integer, got {value!r}"
|
||||
spec = WRITABLE[register]
|
||||
if not spec["min"] <= value <= spec["max"]:
|
||||
return f"Register {register}: value {value} out of range {spec['min']}-{spec['max']} {spec['unit']}"
|
||||
return None
|
||||
Reference in New Issue
Block a user