tooling: sync bench + debug console to live STM32 protocol
The mppt-testbench Python tooling had drifted from the flashed firmware
(bundled fw e7a23a3 vs live 1b85532) and could no longer communicate:
- stm32_link.py: CRC8 -> CRC-16/CCITT-FALSE; telemetry 68B -> 78B
(btemp, cmp_outer/inner, iout_slow, vfly_ofs_applied); add PTYPE_INT16
and commands 0x12-0x18; replace PARAMS with the current 37-param map
(single dt_normal, no dt brackets; test_corr/phase_ofs, phase PI,
precharge PI, duty dither; vfly_active 0-3).
- tuner.py: retire per-bracket deadtime; sweep the single dt_normal.
- cli.py: update tune-deadtime, help/examples, btemp readout;
default ports COM11 (load) / COM4 (stm32).
- debug console TUI: sync protocol.py/app.py/status_bar/telemetry_panel
from live (new command keys, link RX/TX/loss stats, single dead-time,
new telemetry fields, param-write auto-retry); add duty_fft.py.
- README: rewrite parameter table, deadtime section, ports, keybindings.
Verified: protocol round-trip self-tests + live `bench stm32-read`
reading all 37 params over COM4.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+102
-16
@@ -1,12 +1,14 @@
|
||||
"""Textual TUI application for LVSolarBuck debug console."""
|
||||
import time
|
||||
from collections import deque
|
||||
from textual.app import App, ComposeResult
|
||||
from textual.containers import Horizontal, Vertical, VerticalScroll
|
||||
from textual.widgets import Header, Footer, RichLog
|
||||
|
||||
from .protocol import (
|
||||
CMD_TELEMETRY, CMD_PARAM_WRITE_ACK, CMD_PARAM_VALUE, CMD_PONG, CMD_ERROR_MSG,
|
||||
decode_telemetry, decode_param_value, build_ping, build_param_read_all,
|
||||
CMD_TELEMETRY, CMD_PARAM_WRITE, CMD_PARAM_WRITE_ACK, CMD_PARAM_VALUE, CMD_PONG, CMD_ERROR_MSG,
|
||||
decode_telemetry, decode_param_value, build_ping, build_shutdown, build_reset, build_test_50, build_param_read_all,
|
||||
build_relay_on, build_relay_off, build_hold_converter, build_toggle_precharge,
|
||||
PARAM_BY_ID,
|
||||
)
|
||||
from .serial_worker import SerialWorker
|
||||
@@ -49,9 +51,14 @@ class DebugConsoleApp(App):
|
||||
BINDINGS = [
|
||||
("q", "quit", "Quit"),
|
||||
("p", "ping", "Ping"),
|
||||
("r", "read_params", "Read Params"),
|
||||
("f", "toggle_filter", "Filter On/Off"),
|
||||
("l", "show_log_path", "Log Path"),
|
||||
("s", "shutdown", "SHUTOFF"),
|
||||
("x", "reset", "RESET"),
|
||||
("t", "test50", "TEST 50%"),
|
||||
("c", "relay_on", "Relay ON"),
|
||||
("d", "relay_off", "Relay OFF"),
|
||||
("h", "hold_converter", "HOLD CONV"),
|
||||
("g", "toggle_precharge", "PRECHARGE"),
|
||||
]
|
||||
|
||||
def __init__(self, port: str, baudrate: int = 460800):
|
||||
@@ -60,9 +67,23 @@ class DebugConsoleApp(App):
|
||||
self.serial_baudrate = baudrate
|
||||
self.worker: SerialWorker | None = None
|
||||
self.logger: DataLogger | None = None
|
||||
# Per-tick accumulators (bumped in _on_frame); _sent_count counts the
|
||||
# frames the MCU generated (incl. lost) from the telemetry seq advance.
|
||||
self._telem_count = 0
|
||||
self._fps_time = time.monotonic()
|
||||
self._sent_count = 0
|
||||
# Sliding-window link-rate estimator: a deque of (time, recv, sent)
|
||||
# buckets covering the last _rate_window_s, so the Hz/loss readout is a
|
||||
# moving average refreshed every status tick — smooth (no ±1-frame
|
||||
# 8/12 Hz quantization) yet still responsive.
|
||||
self._rate_window_s = 3.0
|
||||
self._rate_buckets: deque = deque()
|
||||
self._rate_window_start = time.monotonic()
|
||||
self._last_seq = -1
|
||||
# Un-ACKed param writes awaiting retry: the MCU's RX side is EMI-lossy
|
||||
# while the converter is switching (TX/telemetry unaffected), so writes
|
||||
# are resent until the matching CMD_PARAM_WRITE_ACK arrives.
|
||||
# param_id -> [frame_bytes, tries, deadline]
|
||||
self._pending_writes: dict[int, list] = {}
|
||||
|
||||
def compose(self) -> ComposeResult:
|
||||
yield Header()
|
||||
@@ -76,6 +97,7 @@ class DebugConsoleApp(App):
|
||||
yield ParamGroup("CC", self._send_data)
|
||||
yield ParamGroup("MPPT", self._send_data)
|
||||
yield ParamGroup("Deadtime", self._send_data)
|
||||
yield ParamGroup("Manual", self._send_data)
|
||||
yield RichLog(id="error-log", markup=True, wrap=True)
|
||||
yield StatusBar()
|
||||
yield Footer()
|
||||
@@ -93,6 +115,7 @@ class DebugConsoleApp(App):
|
||||
self.worker.start()
|
||||
self.set_interval(0.5, self._update_status)
|
||||
self.set_interval(2.0, self._request_params)
|
||||
self.set_interval(0.3, self._flush_pending_writes)
|
||||
|
||||
def on_unmount(self) -> None:
|
||||
if self.worker:
|
||||
@@ -102,8 +125,33 @@ class DebugConsoleApp(App):
|
||||
|
||||
def _send_data(self, data: bytes) -> None:
|
||||
if self.worker:
|
||||
# Track param writes for ACK-based auto-retry. Frame layout:
|
||||
# [SYNC, cmd, len, payload...]; ParamWritePayload starts with
|
||||
# param_id. A newer write to the same param replaces the pending
|
||||
# entry, so retries never resurrect a stale value.
|
||||
if len(data) > 3 and data[1] == CMD_PARAM_WRITE:
|
||||
self._pending_writes[data[3]] = [data, 0, time.monotonic() + 0.3]
|
||||
self.worker.send(data)
|
||||
|
||||
def _flush_pending_writes(self) -> None:
|
||||
if not self.worker or not self._pending_writes:
|
||||
return
|
||||
now = time.monotonic()
|
||||
for pid in list(self._pending_writes):
|
||||
entry = self._pending_writes.get(pid)
|
||||
if entry is None or now < entry[2]:
|
||||
continue
|
||||
if entry[1] >= 30:
|
||||
self._pending_writes.pop(pid, None)
|
||||
p = PARAM_BY_ID.get(pid)
|
||||
name = p.name if p else f"0x{pid:02X}"
|
||||
self.notify(f"Param write '{name}' got no ACK after 30 tries",
|
||||
severity="error", timeout=10)
|
||||
continue
|
||||
entry[1] += 1
|
||||
entry[2] = now + 0.3
|
||||
self.worker.send(entry[0])
|
||||
|
||||
def _request_params(self) -> None:
|
||||
if self.worker and self.worker.connected:
|
||||
self._send_data(build_param_read_all())
|
||||
@@ -114,11 +162,16 @@ class DebugConsoleApp(App):
|
||||
if t is not None:
|
||||
self._telem_count += 1
|
||||
if self._last_seq >= 0:
|
||||
# seq increments per frame the MCU SENT, so the advance
|
||||
# counts generated frames whether or not they arrived.
|
||||
self._sent_count += (t.seq - self._last_seq) & 0xFF
|
||||
expected = (self._last_seq + 1) & 0xFF
|
||||
if t.seq != expected:
|
||||
diff = (t.seq - expected) & 0xFF
|
||||
if self.worker:
|
||||
self.worker.drop_count += diff
|
||||
else:
|
||||
self._sent_count += 1
|
||||
self._last_seq = t.seq
|
||||
if self.logger:
|
||||
self.logger.log_telemetry(t)
|
||||
@@ -134,6 +187,7 @@ class DebugConsoleApp(App):
|
||||
result = decode_param_value(payload)
|
||||
if result:
|
||||
param_id, value = result
|
||||
self._pending_writes.pop(param_id, None)
|
||||
if self.logger:
|
||||
self.logger.log_param(param_id, value)
|
||||
self.call_from_thread(self._update_param, param_id, value)
|
||||
@@ -180,30 +234,62 @@ class DebugConsoleApp(App):
|
||||
|
||||
def _update_status(self) -> None:
|
||||
now = time.monotonic()
|
||||
elapsed = now - self._fps_time
|
||||
fps = self._telem_count / elapsed if elapsed > 0 else 0.0
|
||||
# Push this tick's counts, then slide the window forward, dropping
|
||||
# buckets older than _rate_window_s. The retained buckets exactly cover
|
||||
# (_rate_window_start, now], so summing their counts and dividing by
|
||||
# that span is an unbiased moving-average rate — no short-window
|
||||
# quantization, and it tracks real changes within the window.
|
||||
self._rate_buckets.append((now, self._telem_count, self._sent_count))
|
||||
self._telem_count = 0
|
||||
self._fps_time = now
|
||||
self._sent_count = 0
|
||||
while len(self._rate_buckets) > 1 and now - self._rate_buckets[0][0] > self._rate_window_s:
|
||||
self._rate_window_start = self._rate_buckets.popleft()[0]
|
||||
span = now - self._rate_window_start
|
||||
recv = sum(b[1] for b in self._rate_buckets)
|
||||
sent = sum(b[2] for b in self._rate_buckets)
|
||||
fps = recv / span if span > 0 else 0.0
|
||||
sent_fps = sent / span if span > 0 else 0.0
|
||||
loss_pct = 100.0 * (1.0 - recv / sent) if sent > 0 else 0.0
|
||||
status = self.query_one(StatusBar)
|
||||
status.fps = fps
|
||||
status.sent_fps = sent_fps
|
||||
status.loss_pct = loss_pct
|
||||
if self.worker:
|
||||
status.connected = self.worker.connected
|
||||
status.refresh_status()
|
||||
# The StatusBar is hidden behind the Footer on most terminals, so the
|
||||
# link stats are mirrored into the always-visible telemetry panel.
|
||||
panel = self.query_one(TelemetryPanel)
|
||||
panel.link_rx = fps
|
||||
panel.link_tx = sent_fps
|
||||
panel.link_loss = loss_pct
|
||||
|
||||
def action_ping(self) -> None:
|
||||
self._send_data(build_ping())
|
||||
|
||||
def action_read_params(self) -> None:
|
||||
self._request_params()
|
||||
def action_shutdown(self) -> None:
|
||||
self._send_data(build_shutdown())
|
||||
|
||||
def action_reset(self) -> None:
|
||||
self._send_data(build_reset())
|
||||
|
||||
def action_test50(self) -> None:
|
||||
self._send_data(build_test_50())
|
||||
|
||||
def action_relay_on(self) -> None:
|
||||
self._send_data(build_relay_on())
|
||||
|
||||
def action_relay_off(self) -> None:
|
||||
self._send_data(build_relay_off())
|
||||
|
||||
def action_hold_converter(self) -> None:
|
||||
self._send_data(build_hold_converter())
|
||||
|
||||
def action_toggle_precharge(self) -> None:
|
||||
self._send_data(build_toggle_precharge())
|
||||
|
||||
def action_toggle_filter(self) -> None:
|
||||
panel = self.query_one(TelemetryPanel)
|
||||
panel.filter_enabled = not panel.filter_enabled
|
||||
state = "ON" if panel.filter_enabled else "OFF"
|
||||
self.notify(f"Filter {state}")
|
||||
|
||||
def action_show_log_path(self) -> None:
|
||||
if self.logger:
|
||||
self.notify(f"Log: {self.logger.db_path}", timeout=10)
|
||||
else:
|
||||
self.notify("Logger not active", severity="warning")
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Reconstruct per-cycle duty from a G1-G4 logic capture and FFT it to find
|
||||
the low-frequency (audible) modulation. G1=T1 (outer/Timer F), G2=T2 (inner/
|
||||
Timer E). common = main-loop duty, diff = V_fly duty-asymmetry (vfly_correction)."""
|
||||
import sys
|
||||
import numpy as np
|
||||
|
||||
CSV = sys.argv[1] if len(sys.argv) > 1 else "digital.csv"
|
||||
|
||||
# --- load (int8 gates to keep memory down) ---
|
||||
try:
|
||||
import pandas as pd
|
||||
df = pd.read_csv(CSV, dtype={"Time [s]": np.float64, "G1": np.int8,
|
||||
"G2": np.int8, "G3": np.int8, "G4": np.int8})
|
||||
t = df["Time [s]"].to_numpy()
|
||||
G = {c: df[c].to_numpy() for c in ("G1", "G2", "G3", "G4")}
|
||||
except ImportError:
|
||||
raw = np.genfromtxt(CSV, delimiter=",", skip_header=1)
|
||||
t = raw[:, 0]
|
||||
G = {f"G{i}": raw[:, i].astype(np.int8) for i in range(1, 5)}
|
||||
|
||||
print(f"rows={len(t)} span={t[-1]-t[0]:.4f}s")
|
||||
|
||||
|
||||
def duty_series(g):
|
||||
"""Return (cycle_start_times, duty[0..1]) from rising/falling edges of g."""
|
||||
dg = np.diff(g.astype(np.int16))
|
||||
tr = t[np.where(dg == 1)[0] + 1] # rising-edge times (cycle starts)
|
||||
tf = t[np.where(dg == -1)[0] + 1] # falling-edge times
|
||||
idx = np.searchsorted(tf, tr, side="right")
|
||||
valid = idx < len(tf)
|
||||
tr, hi = tr[valid], tf[np.clip(idx[valid], 0, len(tf) - 1)] - tr[valid]
|
||||
period = np.diff(tr)
|
||||
return tr[:-1], hi[:-1] / period
|
||||
|
||||
|
||||
t_o, d_o = duty_series(G["G1"]) # outer
|
||||
t_i, d_i = duty_series(G["G2"]) # inner
|
||||
fsw = 1.0 / np.median(np.diff(t_o))
|
||||
print(f"f_sw ~= {fsw/1e3:.1f} kHz outer cycles={len(d_o)} inner cycles={len(d_i)}")
|
||||
print(f"D_outer mean={d_o.mean():.4f} std={d_o.std():.4f} | "
|
||||
f"D_inner mean={d_i.mean():.4f} std={d_i.std():.4f}")
|
||||
|
||||
# resample both onto a uniform grid at f_sw, align, build common / diff
|
||||
t0, t1 = max(t_o[0], t_i[0]), min(t_o[-1], t_i[-1])
|
||||
fs = fsw
|
||||
tu = np.arange(t0, t1, 1.0 / fs)
|
||||
do_u = np.interp(tu, t_o, d_o)
|
||||
di_u = np.interp(tu, t_i, d_i)
|
||||
common = 0.5 * (do_u + di_u) # main control loop
|
||||
diff = 0.5 * (do_u - di_u) # V_fly asymmetry (= corr/MAX_DUTY)
|
||||
|
||||
|
||||
def top_peaks(x, label, n=6, fmin=50.0, fmax=40e3):
|
||||
x = x - x.mean()
|
||||
win = np.hanning(len(x))
|
||||
X = np.abs(np.fft.rfft(x * win)) / (len(x) * 0.5)
|
||||
f = np.fft.rfftfreq(len(x), d=1.0 / fs)
|
||||
band = (f >= fmin) & (f <= fmax)
|
||||
fb, Xb = f[band], X[band]
|
||||
order = np.argsort(Xb)[::-1]
|
||||
# de-duplicate neighbouring bins (keep local maxima >= 25 Hz apart)
|
||||
picks, fseen = [], []
|
||||
for i in order:
|
||||
if all(abs(fb[i] - fs0) > 25 for fs0 in fseen):
|
||||
picks.append(i); fseen.append(fb[i])
|
||||
if len(picks) >= n:
|
||||
break
|
||||
print(f"\n[{label}] rms={x.std()*1e3:.3f}e-3 duty")
|
||||
for i in picks:
|
||||
print(f" {fb[i]:9.1f} Hz amp={Xb[i]*1e3:8.4f}e-3 "
|
||||
f"({Xb[i]/Xb[order[0]]*100:5.1f}% of peak)")
|
||||
return fb[order[0]], Xb[order[0]]
|
||||
|
||||
|
||||
top_peaks(common, "COMMON (main loop)")
|
||||
top_peaks(diff, "DIFF (V_fly asymmetry)")
|
||||
top_peaks(do_u, "OUTER (G1/Timer F)")
|
||||
|
||||
# strongest line above the mains band, + harmonic-ladder check
|
||||
def spectrum(x):
|
||||
x = x - x.mean()
|
||||
X = np.abs(np.fft.rfft(x * np.hanning(len(x)))) / (len(x) * 0.5)
|
||||
f = np.fft.rfftfreq(len(x), d=1.0 / fs)
|
||||
return f, X
|
||||
|
||||
fc, Xc = spectrum(common)
|
||||
above = fc > 400.0
|
||||
ipk = np.argmax(Xc[above])
|
||||
fpk = fc[above][ipk]
|
||||
print(f"\n[COMMON strongest >400Hz] {fpk:.1f} Hz")
|
||||
print(f" f_sw/f_pk = {fsw/fpk:.2f} ; 50kHz-loop/f_pk = {50e3/fpk:.3f}")
|
||||
|
||||
# --- zoom 300-1500 Hz: where is the 500-600 Hz energy, common or diff? ---
|
||||
def band_peak(x, lbl, lo=300, hi=1500):
|
||||
f, X = spectrum(x)
|
||||
b = (f >= lo) & (f <= hi)
|
||||
i = np.argmax(X[b])
|
||||
print(f" [{lbl}] {lo}-{hi}Hz peak: {f[b][i]:7.1f} Hz amp={X[b][i]*1e3:.4f}e-3")
|
||||
print("\n=== 300-1500 Hz band ===")
|
||||
band_peak(common, "COMMON")
|
||||
band_peak(diff, "DIFF ")
|
||||
|
||||
# --- detect large cycle-to-cycle duty steps (per-cycle, not resampled) ---
|
||||
def steps(td, d, lbl, thr=0.02):
|
||||
jumps = np.abs(np.diff(d))
|
||||
idx = np.where(jumps > thr)[0]
|
||||
print(f"\n[{lbl}] cyc-to-cyc |dD|>{thr*100:.0f}%: {len(idx)} events "
|
||||
f"(of {len(d)} cyc), max step={jumps.max()*100:.2f}%")
|
||||
if len(idx) > 3:
|
||||
ev_t = td[idx + 1]
|
||||
gaps = np.diff(ev_t)
|
||||
gaps = gaps[gaps > 1e-4] # ignore bursts within one event
|
||||
if len(gaps):
|
||||
med = np.median(gaps)
|
||||
print(f" median spacing {med*1e3:.3f} ms -> {1/med:.1f} Hz "
|
||||
f"(min {gaps.min()*1e3:.2f}ms max {gaps.max()*1e3:.2f}ms)")
|
||||
steps(t_o, d_o, "OUTER step rate")
|
||||
steps(t_i, d_i, "INNER step rate")
|
||||
|
||||
# plot
|
||||
try:
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
fig, ax = plt.subplots(3, 1, figsize=(11, 9), sharex=True)
|
||||
for a, (x, lbl) in zip(ax, [(common, "COMMON (main loop)"),
|
||||
(diff, "DIFF (V_fly asymmetry)"),
|
||||
(do_u, "OUTER (G1)")]):
|
||||
f, X = spectrum(x)
|
||||
m = f <= 50e3
|
||||
a.semilogy(f[m] / 1e3, X[m])
|
||||
a.set_ylabel(lbl + "\nduty amp"); a.grid(True, which="both", alpha=0.3)
|
||||
a.axvline(24.77, color="r", ls=":", lw=1)
|
||||
ax[-1].set_xlabel("kHz")
|
||||
fig.tight_layout()
|
||||
fig.savefig("debug_console/duty_fft.png", dpi=110)
|
||||
print("\nsaved debug_console/duty_fft.png")
|
||||
except Exception as e:
|
||||
print("plot skipped:", e)
|
||||
@@ -13,30 +13,32 @@ CMD_PARAM_READ_ALL = 0x04
|
||||
CMD_PARAM_VALUE = 0x05
|
||||
CMD_PING = 0x10
|
||||
CMD_PONG = 0x11
|
||||
CMD_SHUTDOWN = 0x12
|
||||
CMD_RESET = 0x13
|
||||
CMD_TEST_50 = 0x14
|
||||
CMD_RELAY_ON = 0x15
|
||||
CMD_RELAY_OFF = 0x16
|
||||
CMD_HOLD_CONVERTER = 0x17
|
||||
CMD_TOGGLE_PRECHARGE = 0x18
|
||||
CMD_ERROR_MSG = 0xE0
|
||||
|
||||
PTYPE_FLOAT = 0
|
||||
PTYPE_UINT16 = 1
|
||||
PTYPE_UINT8 = 2
|
||||
PTYPE_INT32 = 3
|
||||
PTYPE_INT16 = 4 # wire format = sign-extended int32, stored firmware-side as int16_t
|
||||
|
||||
# CRC8 table (poly 0x07)
|
||||
_CRC8_TABLE = [0] * 256
|
||||
def _init_crc8():
|
||||
for i in range(256):
|
||||
crc = i
|
||||
for _ in range(8):
|
||||
if crc & 0x80:
|
||||
crc = ((crc << 1) ^ 0x07) & 0xFF
|
||||
else:
|
||||
crc = (crc << 1) & 0xFF
|
||||
_CRC8_TABLE[i] = crc
|
||||
_init_crc8()
|
||||
|
||||
def crc8(data: bytes) -> int:
|
||||
crc = 0x00
|
||||
# CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, no reflection, no XOR-out.
|
||||
# Matches STM32 hardware CRC configured in main.c MX_CRC_Init.
|
||||
def crc16(data: bytes) -> int:
|
||||
crc = 0xFFFF
|
||||
for b in data:
|
||||
crc = _CRC8_TABLE[crc ^ b]
|
||||
crc ^= b << 8
|
||||
for _ in range(8):
|
||||
if crc & 0x8000:
|
||||
crc = ((crc << 1) ^ 0x1021) & 0xFFFF
|
||||
else:
|
||||
crc = (crc << 1) & 0xFFFF
|
||||
return crc
|
||||
|
||||
|
||||
@@ -48,9 +50,11 @@ class TelemetryData:
|
||||
iout: float = 0.0
|
||||
vfly: float = 0.0
|
||||
etemp: float = 0.0
|
||||
btemp: float = 0.0
|
||||
last_tmp: int = 0
|
||||
VREF: int = 0
|
||||
vfly_correction: int = 0
|
||||
cmp_outer: int = 0 # HRTIM Timer F CMP1xR (outer pair, T1/T4)
|
||||
vfly_integral: float = 0.0
|
||||
vfly_avg_debug: float = 0.0
|
||||
cc_output_f: float = 0.0
|
||||
@@ -59,9 +63,12 @@ class TelemetryData:
|
||||
mppt_last_iin: float = 0.0
|
||||
p_in: float = 0.0
|
||||
p_out: float = 0.0
|
||||
iout_slow: float = 0.0
|
||||
seq: int = 0
|
||||
cmp_inner: int = 0 # HRTIM Timer E CMP1xR (inner pair, T2/T3)
|
||||
vfly_ofs_applied: int = 0 # master-phase offset last written, signed ticks
|
||||
|
||||
TELEMETRY_FMT = "<6f hHh h 6f 2f B3x" # 68 bytes
|
||||
TELEMETRY_FMT = "<7f hHhH 6f 3f BxH h" # 78 bytes
|
||||
TELEMETRY_SIZE = struct.calcsize(TELEMETRY_FMT)
|
||||
|
||||
def decode_telemetry(payload: bytes) -> Optional[TelemetryData]:
|
||||
@@ -70,21 +77,25 @@ def decode_telemetry(payload: bytes) -> Optional[TelemetryData]:
|
||||
vals = struct.unpack(TELEMETRY_FMT, payload[:TELEMETRY_SIZE])
|
||||
return TelemetryData(
|
||||
vin=vals[0], vout=vals[1], iin=vals[2], iout=vals[3],
|
||||
vfly=vals[4], etemp=vals[5],
|
||||
last_tmp=vals[6], VREF=vals[7], vfly_correction=vals[8],
|
||||
# vals[9] is pad
|
||||
vfly_integral=vals[10], vfly_avg_debug=vals[11],
|
||||
cc_output_f=vals[12], mppt_iref=vals[13],
|
||||
mppt_last_vin=vals[14], mppt_last_iin=vals[15],
|
||||
p_in=vals[16], p_out=vals[17],
|
||||
seq=vals[18],
|
||||
vfly=vals[4], etemp=vals[5], btemp=vals[6],
|
||||
last_tmp=vals[7], VREF=vals[8], vfly_correction=vals[9],
|
||||
cmp_outer=vals[10],
|
||||
vfly_integral=vals[11], vfly_avg_debug=vals[12],
|
||||
cc_output_f=vals[13], mppt_iref=vals[14],
|
||||
mppt_last_vin=vals[15], mppt_last_iin=vals[16],
|
||||
p_in=vals[17], p_out=vals[18],
|
||||
iout_slow=vals[19],
|
||||
seq=vals[20],
|
||||
cmp_inner=vals[21],
|
||||
vfly_ofs_applied=vals[22],
|
||||
)
|
||||
|
||||
|
||||
def build_frame(cmd: int, payload: bytes = b"") -> bytes:
|
||||
header = bytes([SYNC_BYTE, cmd, len(payload)])
|
||||
frame_no_crc = header + payload
|
||||
return frame_no_crc + bytes([crc8(frame_no_crc)])
|
||||
crc = crc16(frame_no_crc)
|
||||
return frame_no_crc + bytes([(crc >> 8) & 0xFF, crc & 0xFF]) # big-endian
|
||||
|
||||
|
||||
def build_param_write(param_id: int, param_type: int, value) -> bytes:
|
||||
@@ -96,6 +107,8 @@ def build_param_write(param_id: int, param_type: int, value) -> bytes:
|
||||
val_bytes = struct.pack("<Bxxx", int(value))
|
||||
elif param_type == PTYPE_INT32:
|
||||
val_bytes = struct.pack("<i", int(value))
|
||||
elif param_type == PTYPE_INT16:
|
||||
val_bytes = struct.pack("<i", int(value)) # sign-extended 32-bit wire
|
||||
else:
|
||||
val_bytes = struct.pack("<I", int(value))
|
||||
payload = struct.pack("<BBxx", param_id, param_type) + val_bytes
|
||||
@@ -106,6 +119,34 @@ def build_ping() -> bytes:
|
||||
return build_frame(CMD_PING)
|
||||
|
||||
|
||||
def build_shutdown() -> bytes:
|
||||
return build_frame(CMD_SHUTDOWN)
|
||||
|
||||
|
||||
def build_reset() -> bytes:
|
||||
return build_frame(CMD_RESET)
|
||||
|
||||
|
||||
def build_test_50() -> bytes:
|
||||
return build_frame(CMD_TEST_50)
|
||||
|
||||
|
||||
def build_relay_on() -> bytes:
|
||||
return build_frame(CMD_RELAY_ON)
|
||||
|
||||
|
||||
def build_relay_off() -> bytes:
|
||||
return build_frame(CMD_RELAY_OFF)
|
||||
|
||||
|
||||
def build_hold_converter() -> bytes:
|
||||
return build_frame(CMD_HOLD_CONVERTER)
|
||||
|
||||
|
||||
def build_toggle_precharge() -> bytes:
|
||||
return build_frame(CMD_TOGGLE_PRECHARGE)
|
||||
|
||||
|
||||
def build_param_read_all() -> bytes:
|
||||
return build_frame(CMD_PARAM_READ_ALL)
|
||||
|
||||
@@ -125,6 +166,8 @@ def decode_param_value(payload: bytes) -> Optional[tuple[int, float]]:
|
||||
value = float(value_bytes[0])
|
||||
elif param_type == PTYPE_INT32:
|
||||
value = float(struct.unpack("<i", value_bytes)[0])
|
||||
elif param_type == PTYPE_INT16:
|
||||
value = float(struct.unpack("<i", value_bytes)[0]) # sign-extended 32-bit wire
|
||||
else:
|
||||
value = float(struct.unpack("<I", value_bytes)[0])
|
||||
return (param_id, value)
|
||||
@@ -137,7 +180,8 @@ class FrameParser:
|
||||
WAIT_CMD = 1
|
||||
WAIT_LEN = 2
|
||||
WAIT_PAYLOAD = 3
|
||||
WAIT_CRC = 4
|
||||
WAIT_CRC_HI = 4
|
||||
WAIT_CRC_LO = 5
|
||||
|
||||
def __init__(self):
|
||||
self.state = self.WAIT_SYNC
|
||||
@@ -146,6 +190,7 @@ class FrameParser:
|
||||
self.buf = bytearray()
|
||||
self.payload = bytearray()
|
||||
self.idx = 0
|
||||
self.crc_hi = 0
|
||||
|
||||
def feed(self, data: bytes):
|
||||
"""Feed bytes, yield (cmd, payload) tuples for complete frames."""
|
||||
@@ -164,7 +209,7 @@ class FrameParser:
|
||||
self.payload = bytearray()
|
||||
self.idx = 0
|
||||
if b == 0:
|
||||
self.state = self.WAIT_CRC
|
||||
self.state = self.WAIT_CRC_HI
|
||||
elif b > 128:
|
||||
self.state = self.WAIT_SYNC
|
||||
else:
|
||||
@@ -174,11 +219,15 @@ class FrameParser:
|
||||
self.buf.append(b)
|
||||
self.idx += 1
|
||||
if self.idx >= self.length:
|
||||
self.state = self.WAIT_CRC
|
||||
elif self.state == self.WAIT_CRC:
|
||||
expected = crc8(bytes(self.buf))
|
||||
self.state = self.WAIT_CRC_HI
|
||||
elif self.state == self.WAIT_CRC_HI:
|
||||
self.crc_hi = b
|
||||
self.state = self.WAIT_CRC_LO
|
||||
elif self.state == self.WAIT_CRC_LO:
|
||||
received = (self.crc_hi << 8) | b
|
||||
expected = crc16(bytes(self.buf))
|
||||
self.state = self.WAIT_SYNC
|
||||
if b == expected:
|
||||
if received == expected:
|
||||
yield (self.cmd, bytes(self.payload))
|
||||
|
||||
|
||||
@@ -195,13 +244,17 @@ class ParamDef:
|
||||
|
||||
PARAMS = [
|
||||
# Compensator
|
||||
ParamDef(0x25, "VREF", PTYPE_UINT16, "Compensator", 3100, 3700, ".0f"),
|
||||
ParamDef(0x25, "VREF", PTYPE_UINT16, "Compensator", 2340, 3500, ".0f"),
|
||||
# Vfly
|
||||
ParamDef(0x20, "vfly_kp", PTYPE_FLOAT, "Vfly", -10, 10, ".4f"),
|
||||
ParamDef(0x21, "vfly_ki", PTYPE_FLOAT, "Vfly", -10, 10, ".6f"),
|
||||
ParamDef(0x62, "vfly_kp_phase", PTYPE_FLOAT, "Vfly", -10, 10, ".4f"), # mode 2: P gain, error -> phase
|
||||
ParamDef(0x63, "vfly_phase_clamp", PTYPE_UINT16, "Vfly", 0, 10000, ".0f"), # mode 2: phase offset clamp
|
||||
ParamDef(0x22, "vfly_clamp", PTYPE_UINT16, "Vfly", 0, 10000, ".0f"),
|
||||
ParamDef(0x23, "vfly_loop_trig", PTYPE_UINT16, "Vfly", 1, 10000, ".0f"),
|
||||
ParamDef(0x24, "vfly_active", PTYPE_UINT8, "Vfly", 0, 1, ".0f"),
|
||||
ParamDef(0x24, "vfly_active", PTYPE_UINT8, "Vfly", 0, 3, ".0f"), # 0=off 1=auto duty-asymmetry 2=auto phase offset 3=manual both
|
||||
ParamDef(0x26, "test_corr", PTYPE_INT16, "Vfly", -3000, 3000, ".0f"), # mode-3 manual duty asymmetry
|
||||
ParamDef(0x27, "phase_ofs", PTYPE_INT16, "Vfly", -3000, 3000, ".0f"), # master-phase: mode-3 manual, mode-2 P-driven (readback)
|
||||
# CC
|
||||
ParamDef(0x30, "cc_target", PTYPE_FLOAT, "CC", 0, 60000, ".0f"),
|
||||
ParamDef(0x31, "cc_gain", PTYPE_FLOAT, "CC", -1, 1, ".4f"),
|
||||
@@ -210,23 +263,33 @@ PARAMS = [
|
||||
ParamDef(0x34, "cc_loop_trig", PTYPE_UINT16, "CC", 1, 10000, ".0f"),
|
||||
ParamDef(0x35, "cc_active", PTYPE_INT32, "CC", 0, 1, ".0f"),
|
||||
# MPPT
|
||||
ParamDef(0x40, "mppt_step", PTYPE_FLOAT, "MPPT", 0, 10000, ".1f"),
|
||||
ParamDef(0x41, "mppt_iref_min", PTYPE_FLOAT, "MPPT", 0, 60000, ".0f"),
|
||||
ParamDef(0x42, "mppt_iref_max", PTYPE_FLOAT, "MPPT", 0, 60000, ".0f"),
|
||||
ParamDef(0x43, "mppt_dv_thresh", PTYPE_FLOAT, "MPPT", 0, 10000, ".1f"),
|
||||
ParamDef(0x44, "mppt_loop_trig", PTYPE_UINT16, "MPPT", 1, 10000, ".0f"),
|
||||
ParamDef(0x40, "mppt_step", PTYPE_FLOAT, "MPPT", 1, 200, ".0f"),
|
||||
ParamDef(0x41, "mppt_duty_min", PTYPE_FLOAT, "MPPT", 0, 6800, ".0f"),
|
||||
ParamDef(0x42, "mppt_duty_max", PTYPE_FLOAT, "MPPT", 0, 6800, ".0f"),
|
||||
ParamDef(0x44, "mppt_loop_trig", PTYPE_UINT16, "MPPT", 1, 50000, ".0f"),
|
||||
ParamDef(0x45, "mppt_active", PTYPE_INT32, "MPPT", 0, 1, ".0f"),
|
||||
ParamDef(0x46, "mppt_init_iref", PTYPE_FLOAT, "MPPT", 0, 60000, ".0f"),
|
||||
ParamDef(0x47, "mppt_deadband", PTYPE_FLOAT, "MPPT", 0, 1, ".4f"),
|
||||
# Global
|
||||
ParamDef(0x50, "vin_min_ctrl", PTYPE_FLOAT, "Global", 0, 90000, ".0f"),
|
||||
# Deadtime
|
||||
ParamDef(0x60, "dt 0-3A", PTYPE_UINT8, "Deadtime", 14, 200, ".0f"),
|
||||
ParamDef(0x61, "dt 3-5A", PTYPE_UINT8, "Deadtime", 14, 200, ".0f"),
|
||||
ParamDef(0x62, "dt 5-10A", PTYPE_UINT8, "Deadtime", 14, 200, ".0f"),
|
||||
ParamDef(0x63, "dt 10-20A", PTYPE_UINT8, "Deadtime", 14, 200, ".0f"),
|
||||
ParamDef(0x64, "dt 20-30A", PTYPE_UINT8, "Deadtime", 14, 200, ".0f"),
|
||||
ParamDef(0x65, "dt 30-45A", PTYPE_UINT8, "Deadtime", 14, 200, ".0f"),
|
||||
ParamDef(0x46, "cv_threshold", PTYPE_FLOAT, "MPPT", 20000, 30000, ".0f"),
|
||||
ParamDef(0x47, "cv_hysteresis", PTYPE_FLOAT, "MPPT", 0, 5000, ".0f"),
|
||||
ParamDef(0x48, "cc_threshold", PTYPE_FLOAT, "MPPT", 0, 55000, ".0f"),
|
||||
ParamDef(0x50, "cc_hysteresis", PTYPE_FLOAT, "MPPT", 0, 10000, ".0f"),
|
||||
# Deadtime (single static value, dt register units)
|
||||
ParamDef(0x60, "dt_normal", PTYPE_UINT16, "Deadtime", 14, 200, ".0f"),
|
||||
# Manual fixed-duty mode (base duty in CMP ticks; D = override_duty/7158, 716..6442 = 10..90%)
|
||||
ParamDef(0x64, "override_duty", PTYPE_UINT16, "Manual", 716, 6442, ".0f"), # enable manual_duty_en first (seeds at current duty), then sweep
|
||||
ParamDef(0x65, "manual_duty_en", PTYPE_UINT8, "Manual", 0, 1, ".0f"), # 1 = fixed duty, supervisor parked; FMAC balancer still runs per vfly_active
|
||||
# Duty dither: avoid the V_fly de-stack band by delta-sigma modulating the commanded
|
||||
# duty between two out-of-band anchors in the FMAC ISR (all CMP ticks). Defaults bracket
|
||||
# the Vin=75 collapse band 3686..3801 (D 0.515..0.531) with anchors 3643/3844 (D 0.509/0.537).
|
||||
# Closed-loop precharge: PI controller drives the precharge FET PWM (TIM3_CH1) to Vin/2.
|
||||
ParamDef(0x76, "precharge_kp", PTYPE_FLOAT, "Precharge", 0, 100, ".3f"), # P: CCR ticks per mV of (Vin/2 - Vfly)
|
||||
ParamDef(0x78, "precharge_ki", PTYPE_FLOAT, "Precharge", 0, 10, ".4f"), # I: CCR ticks per mV per ~1 kHz tick
|
||||
ParamDef(0x77, "precharge_reg_en", PTYPE_UINT8, "Precharge", 0, 1, ".0f"), # 1 = closed-loop precharge on
|
||||
ParamDef(0x70, "dither_en", PTYPE_UINT8, "Dither", 0, 1, ".0f"),
|
||||
ParamDef(0x71, "dither_band_lo", PTYPE_UINT16, "Dither", 716, 6442, ".0f"),
|
||||
ParamDef(0x72, "dither_band_hi", PTYPE_UINT16, "Dither", 716, 6442, ".0f"),
|
||||
ParamDef(0x73, "dither_anear", PTYPE_UINT16, "Dither", 716, 6442, ".0f"),
|
||||
ParamDef(0x74, "dither_afar", PTYPE_UINT16, "Dither", 716, 6442, ".0f"),
|
||||
ParamDef(0x75, "dither_dzero", PTYPE_UINT16, "Dither", 716, 6442, ".0f"), # |e| fold center (D=0.5); covers both lobes
|
||||
]
|
||||
|
||||
PARAM_BY_ID = {p.id: p for p in PARAMS}
|
||||
|
||||
@@ -21,8 +21,15 @@ class StatusBar(Static):
|
||||
self.pkt_count = 0
|
||||
self.drop_count = 0
|
||||
self.last_seq = 0
|
||||
self.fps = 0.0
|
||||
self.fps = 0.0 # telemetry frames RECEIVED per second
|
||||
self.sent_fps = 0.0 # frames the MCU GENERATED per second (from seq advance)
|
||||
self.loss_pct = 0.0 # 100 * (1 - received/generated)
|
||||
|
||||
def refresh_status(self):
|
||||
conn = "[green]CONN:OK[/green]" if self.connected else "[red]CONN:LOST[/red]"
|
||||
self.update(f" {conn} PKTS:{self.pkt_count} DROPS:{self.drop_count} SEQ:{self.last_seq} FPS:{self.fps:.1f}")
|
||||
if self.loss_pct >= 5.0:
|
||||
loss = f"[red]LOSS:{self.loss_pct:.0f}%[/red]"
|
||||
else:
|
||||
loss = f"LOSS:{self.loss_pct:.0f}%"
|
||||
self.update(f" {conn} PKTS:{self.pkt_count} DROPS:{self.drop_count} SEQ:{self.last_seq}"
|
||||
f" RX:{self.fps:.1f}Hz TX:{self.sent_fps:.1f}Hz {loss}")
|
||||
|
||||
@@ -18,9 +18,10 @@ class TelemetryPanel(Static):
|
||||
|
||||
ALPHA = 0.05 # EMA filter coefficient
|
||||
|
||||
DT_BREAKPOINTS = [0, 3000, 5000, 10000, 20000, 30000, 45000]
|
||||
DT_DEFAULTS = [25, 20, 20, 20, 15, 15]
|
||||
DT_PARAM_IDS = [0x60, 0x61, 0x62, 0x63, 0x64, 0x65]
|
||||
MASTER_TICKS_MID = 7158 # s = 2*last_tmp - MASTER_TICKS_MID (edge-separation abscissa)
|
||||
# dead-time is a single static value now (dt_normal, 0x60); track it for display
|
||||
DT_IDS = {0x60}
|
||||
DT_DEFAULTS = {0x60: 20}
|
||||
|
||||
def __init__(self):
|
||||
super().__init__("Waiting for telemetry...")
|
||||
@@ -32,7 +33,11 @@ class TelemetryPanel(Static):
|
||||
self._vfly_f: float = 0.0
|
||||
self._seeded: bool = False
|
||||
self.filter_enabled: bool = True
|
||||
self._dt_values: list[int] = list(self.DT_DEFAULTS)
|
||||
self._dt_params: dict[int, float] = dict(self.DT_DEFAULTS)
|
||||
# Link stats, set by the app's 0.5 s status timer
|
||||
self.link_rx: float = 0.0
|
||||
self.link_tx: float | None = None
|
||||
self.link_loss: float = 0.0
|
||||
|
||||
def update_telemetry(self, t: TelemetryData):
|
||||
self._data = t
|
||||
@@ -65,15 +70,25 @@ class TelemetryPanel(Static):
|
||||
else:
|
||||
eta = 0.0
|
||||
|
||||
# Compute active deadtime from iout using same lookup as ISR
|
||||
active_dt = self._dt_values[0]
|
||||
for i in range(len(self.DT_BREAKPOINTS) - 1, -1, -1):
|
||||
if i_out >= self.DT_BREAKPOINTS[i]:
|
||||
active_dt = self._dt_values[min(i, len(self._dt_values) - 1)]
|
||||
break
|
||||
# Dead-time is a single static value (dt_normal), applied to both edges/timers.
|
||||
active_dt = self._dt_params.get(0x60, 20)
|
||||
|
||||
if self.link_tx is not None:
|
||||
if self.link_loss >= 5.0:
|
||||
loss_s = f"[red]{self.link_loss:.0f}%[/red]"
|
||||
else:
|
||||
loss_s = f"{self.link_loss:.0f}%"
|
||||
link_lines = [
|
||||
f" link rx : {self.link_rx:8.1f} Hz",
|
||||
f" link tx : {self.link_tx:8.1f} Hz",
|
||||
f" link loss : {loss_s}",
|
||||
]
|
||||
else:
|
||||
link_lines = [" link : measuring..."]
|
||||
|
||||
lines = [
|
||||
"[bold]MEASUREMENTS[/bold]",
|
||||
*link_lines,
|
||||
"",
|
||||
f" vin : {self._vin_f if self.filter_enabled else t.vin:8.0f} mV",
|
||||
f" vout : {self._vout_f if self.filter_enabled else t.vout:8.0f} mV",
|
||||
@@ -84,23 +99,28 @@ class TelemetryPanel(Static):
|
||||
f" EFF : {eta:8.1f} %" if p_in > 0.1 else " EFF : --- %",
|
||||
f" vfly : {self._vfly_f if self.filter_enabled else t.vfly:8.0f} mV",
|
||||
f" etemp : {t.etemp:8.1f} C",
|
||||
f" deadtime : {active_dt:8d} ticks",
|
||||
f" btemp : {t.btemp:8.1f} C",
|
||||
f" deadtime : {active_dt:8.1f} ticks",
|
||||
f" : {active_dt / 1.36:8.1f} ns",
|
||||
"",
|
||||
f" last_tmp : {t.last_tmp:8d}",
|
||||
f" s : {2 * t.last_tmp - self.MASTER_TICKS_MID:+8d} ({'D>0.5' if 2 * t.last_tmp >= self.MASTER_TICKS_MID else 'D<0.5'})",
|
||||
f" VREF : {t.VREF:8d}",
|
||||
f" vfly_corr : {t.vfly_correction:8d}",
|
||||
f" cmp_outer : {t.cmp_outer:8d} (F: T1/T4)",
|
||||
f" cmp_inner : {t.cmp_inner:8d} (E: T2/T3)",
|
||||
f" cmp_diff : {t.cmp_outer - t.cmp_inner:+8d}",
|
||||
f" phase_ofs : {t.vfly_ofs_applied:+8d} (applied)",
|
||||
"",
|
||||
f" vfly_int : {t.vfly_integral:10.3f}",
|
||||
f" vfly_avg : {t.vfly_avg_debug:10.1f}",
|
||||
f" cc.out_f : {t.cc_output_f:10.1f}",
|
||||
f" mppt.iref : {t.mppt_iref:8.0f} mA",
|
||||
f" mppt.vin : {t.mppt_last_vin:8.0f}",
|
||||
f" mppt.iin : {t.mppt_last_iin:8.0f}",
|
||||
f" mppt.duty : {t.mppt_iref:8.0f}",
|
||||
f" mppt.power: {t.mppt_last_vin:12.0f}",
|
||||
f" mppt.dir : {t.mppt_last_iin:4.0f}",
|
||||
]
|
||||
self.update("\n".join(lines))
|
||||
|
||||
def update_dt_param(self, param_id: int, value: float):
|
||||
if param_id in self.DT_PARAM_IDS:
|
||||
idx = self.DT_PARAM_IDS.index(param_id)
|
||||
self._dt_values[idx] = int(value)
|
||||
if param_id in self.DT_IDS:
|
||||
self._dt_params[param_id] = value
|
||||
|
||||
Reference in New Issue
Block a user