From 625765d3ea0eac9500ad2b3d09b5433684934aa2 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 09:44:59 +0200 Subject: [PATCH 01/20] feat(chirp): predict closed-loop response from the identified plant --- src/core/PSbuildController.m | 84 ++++++++++++++++++++++++ src/core/PSpredictClosedLoop.m | 30 +++++++++ tests/test_PSbuildController.m | 83 ++++++++++++++++++++++++ tests/test_PSpredictClosedLoop.m | 106 +++++++++++++++++++++++++++++++ 4 files changed, 303 insertions(+) create mode 100644 src/core/PSbuildController.m create mode 100644 src/core/PSpredictClosedLoop.m create mode 100644 tests/test_PSbuildController.m create mode 100644 tests/test_PSpredictClosedLoop.m diff --git a/src/core/PSbuildController.m b/src/core/PSbuildController.m new file mode 100644 index 0000000..d5c7d6d --- /dev/null +++ b/src/core/PSbuildController.m @@ -0,0 +1,84 @@ +function [A, D, F] = PSbuildController(gains, fp, Fs, freq) +%% PSbuildController - Betaflight PID controller as a frequency response +% Splits the controller the way the loop actually uses it: the PI part acts on +% the error, the D part on the gyro, the feedforward part on the setpoint. +% Output units match the logged axisP/axisI/axisD/axisF, so the result can be +% checked straight against a log. +% +% gains - struct with P, I, D, F (as entered in the firmware), optional tpa +% fp - filter params from PSparseFilterParams, or [] for no dterm filtering +% Fs - PID loop rate (Hz) +% freq - frequency vector (Hz) +% +% A - Kp + Ki/s, on the error +% D - Kd*s*Hdterm, on the gyro (enters the loop with a minus sign) +% F - Kff*s, on the setpoint +% +% Feedforward smoothing is not modelled, so F is optimistic on a log flown +% with heavy smoothing - compare against the logged axisF before trusting it. + +PTERM_SCALE = 0.032029; +ITERM_SCALE = 0.244381; +DTERM_SCALE = 0.000529; +FF_SCALE = 0.013754; + +tpa = 1; +if isfield(gains, 'tpa') && ~isempty(gains.tpa), tpa = gains.tpa; end + +Kp = gains.P * PTERM_SCALE * tpa; +Ki = gains.I * ITERM_SCALE; +Kd = gains.D * DTERM_SCALE * tpa; +Kf = gains.F * FF_SCALE; + +Ts = 1 / Fs; +freq = freq(:); +zinv = exp(-2j*pi*freq*Ts); + +A = Kp + Ki * Ts ./ (1 - zinv); +dc = (freq == 0); +if any(dc) + if Ki > 0, A(dc) = Inf; else, A(dc) = Kp; end +end + +deriv = (1 - zinv) / Ts; +D = Kd * deriv .* dtermChain(fp, Fs, freq); +F = Kf * deriv; + +end + + +function H = dtermChain(fp, Fs, freq) + def = struct('dterm_lpf1_type', 0, 'dterm_lpf1_hz', 0, ... + 'dterm_lpf2_type', 0, 'dterm_lpf2_hz', 0, ... + 'dterm_notch_hz', 0, 'dterm_notch_cut', 0); + fn = fieldnames(def); + for k = 1:numel(fn) + if isstruct(fp) && isfield(fp, fn{k}) && ~isempty(fp.(fn{k})) + def.(fn{k}) = fp.(fn{k}); + end + end + + H = notchResp(def.dterm_notch_hz, def.dterm_notch_cut, Fs, freq); + H = H .* lpfResp(def.dterm_lpf1_type, def.dterm_lpf1_hz, Fs, freq); + H = H .* lpfResp(def.dterm_lpf2_type, def.dterm_lpf2_hz, Fs, freq); +end + + +function H = lpfResp(type, hz, Fs, freq) + types = {'pt1', 'biquad', 'pt2', 'pt3'}; % BF enum 0..3 + H = ones(numel(freq), 1); + if hz <= 0 || type < 0 || type >= numel(types), return; end + [b, a] = PSbfFilters(types{type+1}, hz, Fs); + H = freqz(b, a, freq, Fs); + H = H(:); +end + + +function H = notchResp(center_hz, cutoff_hz, Fs, freq) + H = ones(numel(freq), 1); + if center_hz <= 0 || cutoff_hz <= 0 || cutoff_hz >= center_hz, return; end + Q = center_hz * cutoff_hz / (center_hz^2 - cutoff_hz^2); + [b, a] = PSbfFilters('notch', center_hz, Fs, Q); + H = freqz(b, a, freq, Fs); + H = H(:); +end diff --git a/src/core/PSpredictClosedLoop.m b/src/core/PSpredictClosedLoop.m new file mode 100644 index 0000000..bc5d827 --- /dev/null +++ b/src/core/PSpredictClosedLoop.m @@ -0,0 +1,30 @@ +function [T, L, S, Guw] = PSpredictClosedLoop(P, A, D, F) +%% PSpredictClosedLoop - closed-loop response of the BF loop around a measured plant +% P - plant, controller output to gyro (G_plant from PSrunChirpAnalysis) +% A - PI response on the error (from PSbuildController) +% D - D response on the gyro +% F - feedforward response on the setpoint +% +% The loop the firmware runs is u = (A+F)*r - (A+D)*y with y = P*u, giving +% L = P*(A+D), S = 1/(1+L), T = P*(A+F)*S, Guw = u/r = (A+F)*S +% T./Guw is P again by construction, which is exactly how the plant was +% measured in the first place - so Guw can be held against the logged +% setpoint-to-axisSum response to check the controller model against a log. +% +% All four are elementwise on the frequency grid P, A, D and F share. + +P = P(:); A = A(:); D = D(:); F = F(:); + +L = P .* (A + D); +S = 1 ./ (1 + L); +T = P .* (A + F) .* S; +Guw = (A + F) .* S; + +% The integrator is infinite at DC, where the limits are exact: the loop +% tracks the setpoint and the controller has to invert the plant to do it. +open = ~isfinite(L); +S(open) = 0; +T(open) = 1; +Guw(open) = 1 ./ P(open); + +end diff --git a/tests/test_PSbuildController.m b/tests/test_PSbuildController.m new file mode 100644 index 0000000..d2d2742 --- /dev/null +++ b/tests/test_PSbuildController.m @@ -0,0 +1,83 @@ +% test_PSbuildController.m - tests for the BF controller frequency response model + +%!test +%! % P-only: flat at the scaled P gain, nothing on the other two paths +%! Fs = 8000; freq = (0:10:1000)'; +%! g = struct('P', 45, 'I', 0, 'D', 0, 'F', 0); +%! [A, D, F] = PSbuildController(g, [], Fs, freq); +%! assert(max(abs(A - 45*0.032029)) < 1e-12, 'P-only controller must be flat at Kp'); +%! assert(all(D == 0), 'D path must be zero when the D gain is zero'); +%! assert(all(F == 0), 'F path must be zero when the FF gain is zero'); + +%!test +%! % Integrator: infinite at DC, follows Ki/(j*w) well below Nyquist. +%! % The accumulator BF runs leads the ideal integral by half a sample, so the +%! % comparison only holds where f << Fs - it is 8 % out by Nyquist/20. +%! Fs = 8000; freq = [0; (1:5:50)']; +%! g = struct('P', 0, 'I', 80, 'D', 0, 'F', 0); +%! A = PSbuildController(g, [], Fs, freq); +%! assert(isinf(A(1)), 'integrator must be infinite at DC'); +%! ideal = 80*0.244381 ./ (1j*2*pi*freq(2:end)); +%! assert(max(abs(A(2:end) - ideal) ./ abs(ideal)) < 0.02, ... +%! 'discrete integrator must match Ki/s below Nyquist'); + +%!test +%! % Unfiltered D path is a differentiator: |D| = Kd*w +%! Fs = 8000; freq = (10:10:200)'; +%! g = struct('P', 0, 'I', 0, 'D', 30, 'F', 0); +%! [~, D] = PSbuildController(g, [], Fs, freq); +%! ideal = 30*0.000529 * 2*pi*freq; +%! assert(max(abs(abs(D) - ideal) ./ ideal) < 0.01, 'unfiltered D must be Kd*w'); + +%!test +%! % The dterm lowpass lands on the D path and nowhere else +%! Fs = 8000; freq = (50:50:500)'; +%! g = struct('P', 0, 'I', 0, 'D', 30, 'F', 0); +%! [~, Draw] = PSbuildController(g, [], Fs, freq); +%! fp = struct('dterm_lpf1_type', 0, 'dterm_lpf1_hz', 100, ... +%! 'dterm_lpf2_type', 0, 'dterm_lpf2_hz', 0, ... +%! 'dterm_notch_hz', 0, 'dterm_notch_cut', 0); +%! [~, Dlp] = PSbuildController(g, fp, Fs, freq); +%! [b, a] = PSbfFilters('pt1', 100, Fs); +%! H = freqz(b, a, freq, Fs); +%! assert(max(abs(Dlp - Draw .* H(:))) < 1e-12, 'D path must carry the dterm lowpass'); +%! assert(abs(Dlp(end)) < 0.3*abs(Draw(end)), 'lowpass must cut the D path at 500 Hz'); + +%!test +%! % TPA scales P and D, never I or FF +%! Fs = 8000; freq = (20:20:400)'; +%! g = struct('P', 45, 'I', 80, 'D', 30, 'F', 120); +%! gt = g; gt.tpa = 0.5; +%! [A1, D1, F1] = PSbuildController(g, [], Fs, freq); +%! [A2, D2, F2] = PSbuildController(gt, [], Fs, freq); +%! assert(max(abs(D2 - 0.5*D1)) < 1e-18, 'TPA must halve the D path'); +%! assert(max(abs(F2 - F1)) < 1e-18, 'TPA must not touch feedforward'); +%! Aint = A1 - 45*0.032029; +%! assert(max(abs(A2 - (0.5*45*0.032029 + Aint))) < 1e-12, ... +%! 'TPA must scale only the proportional part of A'); + +%!test +%! % The transfer functions must match the difference equations BF actually runs. +%! % Time domain is the reference here: it mirrors the C code sample by sample, +%! % the frequency response is the derived form under test. +%! Fs = 2000; Ts = 1/Fs; N = 40000; +%! randn('state', 7); +%! g = struct('P', 45, 'I', 80, 'D', 30, 'F', 0); +%! Kp = 45*0.032029; Ki = 80*0.244381; Kd = 30*0.000529; +%! e = randn(N, 1); +%! uA = Kp*e + Ki*Ts*cumsum(e); +%! y = randn(N, 1); +%! [b, a] = PSbfFilters('pt1', 90, Fs); +%! yd = filter(b, a, y); +%! uD = Kd * [0; diff(yd)] / Ts; +%! [Ahat, ~, freq] = PSestimateFreqResponse(e, uA, Fs); +%! [Dhat, ~, ~] = PSestimateFreqResponse(y, uD, Fs); +%! fp = struct('dterm_lpf1_type', 0, 'dterm_lpf1_hz', 90, ... +%! 'dterm_lpf2_type', 0, 'dterm_lpf2_hz', 0, ... +%! 'dterm_notch_hz', 0, 'dterm_notch_cut', 0); +%! [A, D] = PSbuildController(g, fp, Fs, freq); +%! band = freq > 10 & freq < 400; % below 10 Hz a 2.5 s Welch segment holds too few cycles +%! assert(max(abs(Ahat(band) - A(band)) ./ abs(A(band))) < 0.01, ... +%! 'A must match the PI difference equation'); +%! assert(max(abs(Dhat(band) - D(band)) ./ abs(D(band))) < 0.01, ... +%! 'D must match the filtered-derivative difference equation'); diff --git a/tests/test_PSpredictClosedLoop.m b/tests/test_PSpredictClosedLoop.m new file mode 100644 index 0000000..6b8a630 --- /dev/null +++ b/tests/test_PSpredictClosedLoop.m @@ -0,0 +1,106 @@ +% test_PSpredictClosedLoop.m - tests for the predicted closed-loop response + +%!test +%! % T/Guw must give the plant back - that is the identity PSrunChirpAnalysis +%! % relies on when it measures the plant as G_track./G_uw +%! freq = (0.5:0.5:500)'; w = 2*pi*freq; +%! P = 0.6 ./ (1 + 1j*w/(2*pi*70)); +%! A = 1.4 + 15 ./ (1j*w); +%! D = 0.015 * 1j*w ./ (1 + 1j*w/(2*pi*90)); +%! F = 1.2 * 1j*w ./ (1 + 1j*w/(2*pi*50)); +%! [T, L, S, Guw] = PSpredictClosedLoop(P, A, D, F); +%! assert(max(abs(T ./ Guw - P)) < 1e-9, 'T/Guw must return the plant'); +%! assert(max(abs(S .* (1 + L) - 1)) < 1e-9, 'S must be 1/(1+L)'); +%! assert(max(abs(L - P .* (A + D))) < 1e-12, 'L must be P*(A+D)'); + +%!test +%! % An integrator makes A infinite at DC: the loop tracks exactly there +%! freq = [0; 1; 10]; +%! P = [0.6; 0.6; 0.5]; +%! A = [Inf; 10; 1.5]; +%! D = zeros(3,1); F = zeros(3,1); +%! [T, ~, S, Guw] = PSpredictClosedLoop(P, A, D, F); +%! assert(T(1), 1, 1e-12); +%! assert(S(1), 0, 1e-12); +%! assert(Guw(1), 1/0.6, 1e-12); +%! assert(all(isfinite(T)), 'T must stay finite everywhere'); + +%!test +%! % Proportional control around a plant: plain T = PC/(1+PC) +%! freq = (1:1:200)'; +%! P = 0.8 ./ (1 + 1j*2*pi*freq/(2*pi*50)); +%! Kp = 1.44; +%! A = Kp * ones(size(freq)); +%! T = PSpredictClosedLoop(P, A, zeros(size(freq)), zeros(size(freq))); +%! expected = (P*Kp) ./ (1 + P*Kp); +%! assert(max(abs(T - expected)) < 1e-12, 'P-only loop must reduce to PC/(1+PC)'); + +%!test +%! % Raising P must raise the closed-loop bandwidth +%! freq = (1:1:400)'; +%! P = 0.8 ./ (1 + 1j*freq/50); +%! Tlow = PSpredictClosedLoop(P, 0.5*ones(size(freq)), zeros(size(freq)), zeros(size(freq))); +%! Thigh = PSpredictClosedLoop(P, 4.0*ones(size(freq)), zeros(size(freq)), zeros(size(freq))); +%! bw = @(T) freq(find(abs(T) < abs(T(1))/sqrt(2), 1)); +%! assert(bw(Thigh) > bw(Tlow), 'more P must widen the closed loop'); + +%!test +%! % End to end: run the BF loop around a known plant sample by sample, identify +%! % the plant the way PSrunChirpAnalysis does, then predict the loop back from +%! % it. The identified plant is model-free, so a wrong controller model (sign, +%! % sample offset, scaling) shows up here even though the plant still matches. +%! Fs = 2000; Ts = 1/Fs; N = 60000; +%! g = struct('P', 45, 'I', 60, 'D', 20, 'F', 90); +%! fp = struct('dterm_lpf1_type', 0, 'dterm_lpf1_hz', 80, ... +%! 'dterm_lpf2_type', 0, 'dterm_lpf2_hz', 0, ... +%! 'dterm_notch_hz', 0, 'dterm_notch_cut', 0); +%! Kp = 45*0.032029; Ki = 60*0.244381; Kd = 20*0.000529; Kf = 90*0.013754; +%! pt1k = @(fc) (1/Fs) / (1/(2*pi*fc) + 1/Fs); +%! kPlant = pt1k(60 * 1.553773974); % pt2 at 60 Hz, as PSbfFilters builds it +%! kDterm = pt1k(80); +%! gPlant = 0.5; +%! randn('state', 11); +%! [br, ar] = PSbfFilters('pt2', 250, Fs); % a setpoint the feedforward can differentiate +%! r = filter(br, ar, randn(N, 1)); r = 40 * r / std(r); +%! y = zeros(N, 1); u = zeros(N, 1); +%! s1 = 0; s2 = 0; sd = 0; Iacc = 0; sdPrev = 0; rPrev = 0; yNext = 0; +%! for k = 1:N +%! y(k) = yNext; % gyro the controller consumes now +%! ek = r(k) - y(k); +%! Iacc = Iacc + Ki*Ts*ek; +%! sd = sd + kDterm*(y(k) - sd); +%! uD = Kd*(sd - sdPrev)/Ts; sdPrev = sd; +%! uF = Kf*(r(k) - rPrev)/Ts; rPrev = r(k); +%! u(k) = Kp*ek + Iacc - uD + uF; +%! s1 = s1 + kPlant*(gPlant*u(k) - s1); % plant acts on this iteration's output +%! s2 = s2 + kPlant*(s1 - s2); +%! yNext = s2; +%! end +%! assert(all(isfinite(y)) && max(abs(y)) < 1e6, 'simulated loop must stay stable'); +%! [G_track, ~, freq] = PSestimateFreqResponse(r, y, Fs); +%! [G_uw, ~, ~] = PSestimateFreqResponse(r, u, Fs); +%! G_plant = G_track ./ (G_uw + 1e-12); +%! [A, D, F] = PSbuildController(g, fp, Fs, freq); +%! [T, ~, ~, Guw] = PSpredictClosedLoop(G_plant, A, D, F); +%! band = freq > 10 & freq < 250; % below 10 Hz a 2.5 s Welch segment holds too few cycles +%! assert(max(abs(T(band) - G_track(band)) ./ abs(G_track(band))) < 0.01, ... +%! 'predicted tracking response must reproduce the simulated loop'); +%! assert(max(abs(Guw(band) - G_uw(band)) ./ abs(G_uw(band))) < 0.01, ... +%! 'predicted controller output must reproduce the simulated one'); + +%!test +%! % Predicting a gain change must move the step response the way it should: +%! % same measured plant, more P, faster rise +%! Fs = 2000; freq = (0:0.4:1000)'; w = 2*pi*freq; +%! P = 0.6 * exp(-1j*w*0.002) ./ (1 + 1j*w/(2*pi*60)).^2; +%! fp = []; +%! g = struct('P', 40, 'I', 50, 'D', 20, 'F', 0); +%! [A1, D1, F1] = PSbuildController(g, fp, Fs, freq); +%! g.P = 70; +%! [A2, D2, F2] = PSbuildController(g, fp, Fs, freq); +%! T1 = PSpredictClosedLoop(P, A1, D1, F1); +%! T2 = PSpredictClosedLoop(P, A2, D2, F2); +%! [t1, s1] = PSstepFromFRD(freq, T1, 300); +%! [t2, s2] = PSstepFromFRD(freq, T2, 300); +%! rise = @(t, s) t(find(s > 0.63, 1)); +%! assert(rise(t2, s2) < rise(t1, s1), 'more P must reach 63 %% sooner'); From 76603313313a9cfe7b660bfe2a3cd1c04ed79b58 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 10:12:43 +0200 Subject: [PATCH 02/20] fix(chirp): treat a wrapping sinarg as one window instead of one per cycle --- src/core/PSfindChirpWindow.m | 20 ++++++++++------- tests/test_PSfindChirpWindow.m | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 8 deletions(-) diff --git a/src/core/PSfindChirpWindow.m b/src/core/PSfindChirpWindow.m index 16a69c7..4720375 100644 --- a/src/core/PSfindChirpWindow.m +++ b/src/core/PSfindChirpWindow.m @@ -6,19 +6,23 @@ if nargin < 3, varThresh = 500; end -sinarg = sinarg_raw / 5000; -active = sinarg > 0.01 & sinarg < max(sinarg) * 0.99; +sinarg_raw = sinarg_raw(:); -% find contiguous active regions -d = diff([0; active(:); 0]); -starts = find(d > 0.5); -ends = find(d < -0.5) - 1; +% sinarg is a phase wrapping through [0, 2*pi], so it passes near zero on every +% cycle - hundreds of times a second at the top of the sweep. Only a real gap +% between runs separates two windows, not a wrap or a sample landing on one. +maxGap = 50; +act = find(sinarg_raw ~= 0); -if isempty(starts) - idx_start = 1; idx_end = length(sinarg); +if isempty(act) + idx_start = 1; idx_end = length(sinarg_raw); return end +brk = find(diff(act) > maxGap); +starts = act([1; brk+1]); +ends = act([brk; numel(act)]); + % pick longest window with sufficient gyro variance best_len = 0; idx_start = starts(1); diff --git a/tests/test_PSfindChirpWindow.m b/tests/test_PSfindChirpWindow.m index f137057..0e4012b 100644 --- a/tests/test_PSfindChirpWindow.m +++ b/tests/test_PSfindChirpWindow.m @@ -18,3 +18,43 @@ %! [i0, i1] = PSfindChirpWindow(sinarg_raw, gyro); %! assert(i0, 1); %! assert(i1, N); + +%!test +%! % The firmware logs sinarg as a phase wrapping through [0, 2*pi], so a run +%! % sweeping to 600 Hz wraps hundreds of times per second. The whole run is one +%! % window, not one window per wrap. +%! Fs = 2000; Tc = 20; N = 60*Fs; +%! sinarg_raw = zeros(N, 1); gyro = 2*randn(N, 1); +%! a = 10*Fs; b = a + Tc*Fs - 1; +%! tt = (0:Tc*Fs-1)'/Fs; +%! ph = 2*pi*(0.2*tt + (600-0.2)/(2*Tc)*tt.^2); +%! sinarg_raw(a:b) = round(mod(ph, 2*pi) * 5000); +%! gyro(a:b) = 200*sin(ph); +%! [i0, i1] = PSfindChirpWindow(sinarg_raw, gyro); +%! assert(i1-i0+1 > 0.98*Tc*Fs, 'must return the whole sweep, not one phase cycle'); +%! assert(abs(i0-a) < 0.01*Fs && abs(i1-b) < 0.01*Fs, 'window must line up with the run'); + +%!test +%! % A log holds one run per axis; pick the run that moved this axis +%! Fs = 2000; Tc = 10; N = 50*Fs; +%! sinarg_raw = zeros(N, 1); gyro = 2*randn(N, 1); +%! tt = (0:Tc*Fs-1)'/Fs; +%! ph = 2*pi*(0.2*tt + (400-0.2)/(2*Tc)*tt.^2); +%! for k = 0:2 +%! a = (5 + k*14)*Fs; b = a + Tc*Fs - 1; +%! sinarg_raw(a:b) = round(mod(ph, 2*pi) * 5000); +%! if k == 1, gyro(a:b) = 200*sin(ph); end +%! end +%! [i0, i1] = PSfindChirpWindow(sinarg_raw, gyro); +%! assert(abs(i0 - 19*Fs) < 0.01*Fs, 'must pick the run where the axis responded'); + +%!test +%! % A sample landing exactly on the wrap logs a zero; it must not split the run +%! Fs = 2000; Tc = 10; N = 30*Fs; +%! sinarg_raw = zeros(N, 1); gyro = 2*randn(N, 1); +%! a = 5*Fs; b = a + Tc*Fs - 1; +%! sinarg_raw(a:b) = 15000; +%! gyro(a:b) = 200*randn(Tc*Fs, 1); +%! sinarg_raw(a + 3*Fs) = 0; +%! [i0, i1] = PSfindChirpWindow(sinarg_raw, gyro); +%! assert(i1-i0+1 > 0.98*Tc*Fs, 'one stray zero must not halve the window'); From 052b9f144349e8daf485880f7df4f09bfca4a17b Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 10:13:07 +0200 Subject: [PATCH 03/20] fix(firmware): DEBUG_CHIRP is 97, not the enum count --- src/core/PSdebugModeIndices.m | 2 +- tests/test_PSdebugModeIndices.m | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/core/PSdebugModeIndices.m b/src/core/PSdebugModeIndices.m index 346f3cc..60f8eee 100644 --- a/src/core/PSdebugModeIndices.m +++ b/src/core/PSdebugModeIndices.m @@ -20,7 +20,7 @@ idx.RPM_FILTER = 45; idx.FEEDFORWARD = 58; idx.DSHOT_RPM_TELEMETRY = 36; - idx.CHIRP = 119; + idx.CHIRP = 97; end end diff --git a/tests/test_PSdebugModeIndices.m b/tests/test_PSdebugModeIndices.m index 8bbc3ce..7264312 100644 --- a/tests/test_PSdebugModeIndices.m +++ b/tests/test_PSdebugModeIndices.m @@ -19,6 +19,8 @@ %! assert(idx.FFT_FREQ, 16); %! assert(idx.RPM_FILTER, 45); %! assert(idx.FEEDFORWARD, 58); +%! % DEBUG_CHIRP is 97 in debugType_e; 119 is DEBUG_COUNT, the end sentinel +%! assert(idx.CHIRP, 97); %!test %! % INAV (uses default old indices) From 3cb1b2e94a64c4c9cf0919b2802b18ed8632c13a Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 10:32:01 +0200 Subject: [PATCH 04/20] fix(parser): undo blackbox high resolution scaling on load --- src/core/PSapplyHighRes.m | 30 ++++++++++++++++++ src/core/PSimport.m | 4 +++ tests/test_PSapplyHighRes.m | 63 +++++++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 src/core/PSapplyHighRes.m create mode 100644 tests/test_PSapplyHighRes.m diff --git a/src/core/PSapplyHighRes.m b/src/core/PSapplyHighRes.m new file mode 100644 index 0000000..d1518d6 --- /dev/null +++ b/src/core/PSapplyHighRes.m @@ -0,0 +1,30 @@ +function T = PSapplyHighRes(T, setupInfo) +%% PSapplyHighRes - undo blackbox high resolution scaling +% With blackbox_high_resolution on, BF logs gyroADC, gyroUnfilt, rcCommand and +% setpoint multiplied by 10 (blackbox.c). setpoint[3] carries the mixer throttle +% and is written past that loop without the scale, so it is left alone. +% blackbox_decode keeps the raw values; Blackbox Explorer divides on load and +% this does the same, so everything downstream stays in deg/s and stick units. + +scale = 1; +for k = 1:size(setupInfo, 1) + if strcmp(strtrim(setupInfo{k,1}), 'blackbox_high_resolution') + v = str2double(strtrim(setupInfo{k,2})); + if ~isnan(v) && v > 0, scale = 10; end + break + end +end + +if scale == 1, return; end + +fn = fieldnames(T); +for k = 1:numel(fn) + nm = fn{k}; + scaled = ~isempty(regexp(nm, '^(gyroADC|gyroUnfilt|rcCommand)_\d+_$', 'once')) || ... + ~isempty(regexp(nm, '^setpoint_[0-2]_$', 'once')); + if scaled && isnumeric(T.(nm)) + T.(nm) = T.(nm) / scale; + end +end + +end diff --git a/src/core/PSimport.m b/src/core/PSimport.m index 5fc88d8..af9424d 100644 --- a/src/core/PSimport.m +++ b/src/core/PSimport.m @@ -66,6 +66,10 @@ end +if exist('SetupInfo','var') + T = PSapplyHighRes(T, SetupInfo); +end + % DAT.T=T; DAT.mainFname=BBLFileName; diff --git a/tests/test_PSapplyHighRes.m b/tests/test_PSapplyHighRes.m new file mode 100644 index 0000000..86367fe --- /dev/null +++ b/tests/test_PSapplyHighRes.m @@ -0,0 +1,63 @@ +% test_PSapplyHighRes.m - tests for undoing blackbox high resolution scaling + +%!shared T0, si_on, si_off +%! T0 = struct(); +%! T0.gyroADC_0_ = [10; 20; 30]; +%! T0.gyroADC_1_ = [-40; 50; 60]; +%! T0.gyroUnfilt_0_ = [70; 80; 90]; +%! T0.rcCommand_0_ = [100; 200; 300]; +%! T0.rcCommand_3_ = [10000; 15000; 20000]; +%! T0.setpoint_0_ = [1000; 2000; 3000]; +%! T0.setpoint_2_ = [11; 22; 33]; +%! T0.setpoint_3_ = [1500; 1600; 1700]; +%! T0.axisP_0_ = [5; 6; 7]; +%! T0.debug_0_ = [31415; 0; 100]; +%! si_on = {'Firmware revision', 'Betaflight 2025.12.0'; 'blackbox_high_resolution', '1'}; +%! si_off = {'Firmware revision', 'Betaflight 2025.12.0'; 'blackbox_high_resolution', '0'}; + +%!test +%! % Flag on: the four scaled field groups come back to real units +%! T = PSapplyHighRes(T0, si_on); +%! assert(T.gyroADC_0_, [1; 2; 3], 1e-12); +%! assert(T.gyroADC_1_, [-4; 5; 6], 1e-12); +%! assert(T.gyroUnfilt_0_, [7; 8; 9], 1e-12); +%! assert(T.rcCommand_0_, [10; 20; 30], 1e-12); +%! assert(T.rcCommand_3_, [1000; 1500; 2000], 1e-12); +%! assert(T.setpoint_0_, [100; 200; 300], 1e-12); +%! assert(T.setpoint_2_, [1.1; 2.2; 3.3], 1e-12); + +%!test +%! % setpoint[3] is the mixer throttle, written past the scaled loop in blackbox.c +%! T = PSapplyHighRes(T0, si_on); +%! assert(T.setpoint_3_, [1500; 1600; 1700], 1e-12); + +%!test +%! % PID terms and debug are logged unscaled and must stay untouched +%! T = PSapplyHighRes(T0, si_on); +%! assert(T.axisP_0_, [5; 6; 7], 1e-12); +%! assert(T.debug_0_, [31415; 0; 100], 1e-12); + +%!test +%! % Flag off or absent leaves every field alone +%! T = PSapplyHighRes(T0, si_off); +%! assert(T.gyroADC_0_, [10; 20; 30], 1e-12); +%! assert(T.setpoint_0_, [1000; 2000; 3000], 1e-12); +%! T = PSapplyHighRes(T0, {'looptime', '125'}); +%! assert(T.gyroADC_0_, [10; 20; 30], 1e-12); +%! T = PSapplyHighRes(T0, {}); +%! assert(T.gyroADC_0_, [10; 20; 30], 1e-12); + +%!test +%! % Missing fields are fine - not every firmware logs gyroUnfilt +%! Tmin = struct('gyroADC_0_', [10; 20], 'axisP_0_', [1; 2]); +%! T = PSapplyHighRes(Tmin, si_on); +%! assert(T.gyroADC_0_, [1; 2], 1e-12); +%! assert(T.axisP_0_, [1; 2], 1e-12); + +%!test +%! % readtable hands back a struct carrying Properties; it must survive intact +%! Tp = T0; +%! Tp.Properties = struct('VariableNames', {{'gyroADC_0_', 'axisP_0_'}}); +%! T = PSapplyHighRes(Tp, si_on); +%! assert(isfield(T, 'Properties'), 'Properties must be preserved'); +%! assert(T.Properties.VariableNames{1}, 'gyroADC_0_'); From a580636a960dc1cd044425dc2a4eb0f0099b4053 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 10:34:47 +0200 Subject: [PATCH 05/20] feat(chirp): read PID gains and PID loop rate from the log header --- src/util/PSparseFilterParams.m | 6 ++++ src/util/PSparsePIDGains.m | 41 ++++++++++++++++++++++++++ tests/test_PSparsePIDGains.m | 54 ++++++++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+) create mode 100644 src/util/PSparsePIDGains.m create mode 100644 tests/test_PSparsePIDGains.m diff --git a/src/util/PSparseFilterParams.m b/src/util/PSparseFilterParams.m index 507bd49..4f43856 100644 --- a/src/util/PSparseFilterParams.m +++ b/src/util/PSparseFilterParams.m @@ -30,6 +30,12 @@ else fp.gyro_rate_hz = 0; end + +% The PID loop, and with it the dterm filters and the D difference, runs +% pid_process_denom times slower than the gyro +denom = hval(si, 'pid_process_denom', 1); +if denom < 1, denom = 1; end +fp.pid_rate_hz = round(fp.gyro_rate_hz / denom); end function v = hval(si, key, default) diff --git a/src/util/PSparsePIDGains.m b/src/util/PSparsePIDGains.m new file mode 100644 index 0000000..9994d88 --- /dev/null +++ b/src/util/PSparsePIDGains.m @@ -0,0 +1,41 @@ +function g = PSparsePIDGains(si, axisIdx) +%% PSparsePIDGains - PID gains for one axis out of the log header +% si - setupInfo cell array {param, value} +% axisIdx - 0=Roll, 1=Pitch, 2=Yaw +% +% Values are as entered in the firmware, not scaled - PSbuildController does +% the scaling. dMax above D means dynamic D was active, which the controller +% model does not cover. + +axKeys = {'rollPID', 'pitchPID', 'yawPID'}; +pid = hlist(si, axKeys{axisIdx + 1}, [0 0 0]); + +g.P = pid(1); +g.I = pid(2); +g.D = pid(3); + +ff = hlist(si, 'feedforward_weight', []); +if isempty(ff), ff = hlist(si, 'ff_weight', [0 0 0]); end +g.F = pick(ff, axisIdx + 1); + +g.dMax = pick(hlist(si, 'd_max', [0 0 0]), axisIdx + 1); + +end + + +function v = hlist(si, key, default) + v = default; + for k = 1:size(si, 1) + if strcmp(strtrim(si{k,1}), key) + tmp = str2double(strsplit(strtrim(si{k,2}), ',')); + if ~any(isnan(tmp)), v = tmp; end + return; + end + end +end + + +function v = pick(list, n) + v = 0; + if numel(list) >= n, v = list(n); end +end diff --git a/tests/test_PSparsePIDGains.m b/tests/test_PSparsePIDGains.m new file mode 100644 index 0000000..2fae0eb --- /dev/null +++ b/tests/test_PSparsePIDGains.m @@ -0,0 +1,54 @@ +% test_PSparsePIDGains.m - tests for reading PID gains out of a log header + +%!shared si +%! si = {'Firmware revision', 'Betaflight 2025.12.0'; ... +%! 'rollPID', '46,66,32'; ... +%! 'pitchPID', '71,105,49'; ... +%! 'yawPID', '30,65,3'; ... +%! 'ff_weight', '85,90,100'; ... +%! 'd_max', '0,0,0'; ... +%! 'looptime', '125'; ... +%! 'pid_process_denom', '2'}; + +%!test +%! % Roll, pitch and yaw come back in firmware units, in that order +%! g = PSparsePIDGains(si, 0); +%! assert([g.P g.I g.D g.F], [46 66 32 85]); +%! g = PSparsePIDGains(si, 1); +%! assert([g.P g.I g.D g.F], [71 105 49 90]); +%! g = PSparsePIDGains(si, 2); +%! assert([g.P g.I g.D g.F], [30 65 3 100]); + +%!test +%! % BF 4.x spells feedforward weight differently +%! si2 = {'rollPID', '45,60,30'; 'feedforward_weight', '120,120,120'}; +%! g = PSparsePIDGains(si2, 0); +%! assert([g.P g.I g.D g.F], [45 60 30 120]); + +%!test +%! % A missing key gives zero rather than an error +%! g = PSparsePIDGains({'looptime', '125'}, 0); +%! assert([g.P g.I g.D g.F], [0 0 0 0]); +%! g = PSparsePIDGains({'rollPID', '40,50,25'}, 0); +%! assert([g.P g.I g.D g.F], [40 50 25 0]); + +%!test +%! % d_max above the D gain means dynamic D, which the controller model ignores +%! si3 = {'rollPID', '46,66,32'; 'd_max', '40,45,0'}; +%! g = PSparsePIDGains(si3, 0); +%! assert(g.dMax, 40); +%! g = PSparsePIDGains(si, 0); +%! assert(g.dMax, 0); + +%!test +%! % PID loop rate is the gyro rate divided by pid_process_denom +%! fp = PSparseFilterParams(si); +%! assert(fp.gyro_rate_hz, 8000); +%! assert(fp.pid_rate_hz, 4000); + +%!test +%! % Without pid_process_denom the PID loop runs at the gyro rate +%! fp = PSparseFilterParams({'looptime', '125'}); +%! assert(fp.pid_rate_hz, 8000); +%! fp = PSparseFilterParams({'gyro_lpf1_type', '0'}); +%! assert(fp.pid_rate_hz, 0); From 5c7ef0d26ea6b121e9fde347e0e4ed87a719a6cb Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 13:09:36 +0200 Subject: [PATCH 06/20] feat(chirp): live PID sliders predicting the closed loop on the Bode figure --- src/core/PSmarginsFromL.m | 40 +++++++ src/plot/PSplotBode.m | 207 ++++++++++++++++++++++++++-------- src/plot/PSrunChirpAnalysis.m | 12 +- src/util/PStheme.m | 1 + tests/test_PSmarginsFromL.m | 58 ++++++++++ 5 files changed, 268 insertions(+), 50 deletions(-) create mode 100644 src/core/PSmarginsFromL.m create mode 100644 tests/test_PSmarginsFromL.m diff --git a/src/core/PSmarginsFromL.m b/src/core/PSmarginsFromL.m new file mode 100644 index 0000000..d50dba1 --- /dev/null +++ b/src/core/PSmarginsFromL.m @@ -0,0 +1,40 @@ +function [gm_dB, pm_deg, wcg, wcp] = PSmarginsFromL(freq, L) +%% PSmarginsFromL - gain and phase margin of an open loop +% freq - frequency vector (Hz) +% L - complex open loop response on that grid (P*C, not a closed loop) +% +% gm_dB, wcg - gain margin (dB) and the phase crossover it sits at (Hz) +% pm_deg, wcp - phase margin (deg, in (-180, 180]) and the gain crossover (Hz) +% Either pair is NaN when the loop has no such crossing in the band given. +% +% The phase comes from the principal value rather than from unwrapping. A quad +% rate loop is already past -180 deg at the bottom of the band - the plant is +% an integrator and the I term adds its own 90 deg - so unwrapping from the +% first bin puts every later value a full turn out. + +freq = freq(:); +L = L(:); +mag_dB = 20*log10(abs(L) + 1e-12); + +wcp = NaN; pm_deg = NaN; +ci = find(diff(sign(mag_dB)) ~= 0, 1); +if ~isempty(ci) + wcp = interp1(mag_dB(ci:ci+1), freq(ci:ci+1), 0, 'linear'); + Lc = interp1(freq(ci:ci+1), L(ci:ci+1), wcp, 'linear'); + pm_deg = 180 + angle(Lc) * 180/pi; + if pm_deg > 180, pm_deg = pm_deg - 360; end +end + +% The gain margin is the first phase crossover above the gain crossover: that +% is the one saying how much more gain the loop takes. Crossings below it +% belong to the conditionally stable region every PI-on-integrator loop has. +wcg = NaN; gm_dB = NaN; +crossed = find(diff(sign(imag(L))) ~= 0 & real(L(1:end-1)) < 0); +if ~isnan(wcp), crossed = crossed(freq(crossed) > wcp); end +if ~isempty(crossed) + ci = crossed(1); + wcg = interp1(imag(L(ci:ci+1)), freq(ci:ci+1), 0, 'linear'); + gm_dB = -interp1(freq(ci:ci+1), mag_dB(ci:ci+1), wcg, 'linear'); +end + +end diff --git a/src/plot/PSplotBode.m b/src/plot/PSplotBode.m index cde6543..4cea026 100644 --- a/src/plot/PSplotBode.m +++ b/src/plot/PSplotBode.m @@ -1,4 +1,4 @@ -function PSplotBode(freq, G_track, G_plant, C, stepData, titleStr) +function PSplotBode(freq, G_track, G_plant, C, stepData, titleStr, pred) %% PSplotBode - Bode plot with magnitude, phase, coherence, and step response % freq - frequency vector (Hz) % G_track - complex tracking transfer function (setpoint → gyro) @@ -6,6 +6,11 @@ function PSplotBode(freq, G_track, G_plant, C, stepData, titleStr) % C - coherence 0..1 % stepData - struct with .t_ms and .step (or [] to skip) % titleStr - plot title suffix +% pred - struct with .gains, .fp and .FsPid to enable the prediction +% sliders (or [] / omitted for the plain plot) + +if nargin < 7, pred = []; end +hasPred = ~isempty(pred) && ~isempty(G_plant); th = PStheme(); fontsz = th.fontsz; @@ -20,33 +25,75 @@ function PSplotBode(freq, G_track, G_plant, C, stepData, titleStr) freq = freq(:); fPlot = freq(freq > 0); % skip DC for log plot +fMask = freq > 0; + +% The prediction is only worth as much as the plant under it, and the plant +% stops meaning anything once the chirp no longer moves the airframe. Cut it at +% the same 0.8 coherence the plot already draws a line at, and take a run of +% bins rather than the first one so a single noisy bin does not end the band. +low = freq > 2 & C(:) < 0.8; +run = 5; +iBad = []; +if numel(low) >= run + iBad = find(conv(double(low), ones(run, 1), 'valid') == run, 1); +end +if isempty(iBad) + fTrust = max(freq); +else + fTrust = freq(max(iBad - 1, 2)); +end +predMask = fMask & freq <= fTrust; +fPred = freq(predMask); + +if hasPred + pos4 = [.72 .58 .24 .37]; + pos5 = [.72 .38 .24 .17]; +else + pos4 = [.72 .42 .24 .52]; + pos5 = [.72 .08 .24 .26]; +end % --- magnitude --- ax1 = axes('Parent', fig, 'Units', 'normalized', 'Position', [.08 .72 .55 .22]); -mag_T = 20*log10(abs(G_track(freq > 0))); +mag_T = 20*log10(abs(G_track(fMask))); semilogx(ax1, fPlot, mag_T, 'Color', th.bodeMain, 'LineWidth', 1.5); hold(ax1, 'on'); +legEntries = {'Tracking (T)'}; if ~isempty(G_plant) - mag_P = 20*log10(abs(G_plant(freq > 0))); + mag_P = 20*log10(abs(G_plant(fMask))); semilogx(ax1, fPlot, mag_P, 'Color', th.bodeSecondary, 'LineWidth', 1.2); - h_leg = legend(ax1, {'Tracking (T)', 'Plant (P)'}, 'Location', 'southwest'); + legEntries{end+1} = 'Plant (P)'; +end +hPredMag = []; +if hasPred + hPredMag = semilogx(ax1, fPred, nan(size(fPred)), ... + 'Color', th.bodePredicted, 'LineWidth', 1.5); + legEntries{end+1} = 'Predicted'; +end +if numel(legEntries) > 1 + h_leg = legend(ax1, legEntries, 'Location', 'southwest'); try PSstyleLegend(h_leg, th); catch, end end line(ax1, [fPlot(1) fPlot(end)], [0 0], 'Color', th.bodeRef, 'LineStyle', '--'); hold(ax1, 'off'); PSstyleAxes(ax1, th); set(get(ax1, 'YLabel'), 'String', 'Magnitude (dB)'); -th1 = title(ax1, ['Bode - ' titleStr]); +title(ax1, ['Bode - ' titleStr]); % --- phase --- ax2 = axes('Parent', fig, 'Units', 'normalized', 'Position', [.08 .42 .55 .22]); -phase_T = unwrap(angle(G_track(freq > 0))) * 180/pi; +phase_T = unwrap(angle(G_track(fMask))) * 180/pi; semilogx(ax2, fPlot, phase_T, 'Color', th.bodeMain, 'LineWidth', 1.5); hold(ax2, 'on'); if ~isempty(G_plant) - phase_P = unwrap(angle(G_plant(freq > 0))) * 180/pi; + phase_P = unwrap(angle(G_plant(fMask))) * 180/pi; semilogx(ax2, fPlot, phase_P, 'Color', th.bodeSecondary, 'LineWidth', 1.2); end +hPredPh = []; +if hasPred + hPredPh = semilogx(ax2, fPred, nan(size(fPred)), ... + 'Color', th.bodePredicted, 'LineWidth', 1.5); +end line(ax2, [fPlot(1) fPlot(end)], [-180 -180], 'Color', th.btnDash1, 'LineStyle', '--'); hold(ax2, 'off'); PSstyleAxes(ax2, th); @@ -54,7 +101,7 @@ function PSplotBode(freq, G_track, G_plant, C, stepData, titleStr) % --- coherence --- ax3 = axes('Parent', fig, 'Units', 'normalized', 'Position', [.08 .08 .55 .26]); -semilogx(ax3, fPlot, C(freq > 0), 'Color', th.bodeCoherence, 'LineWidth', 1.2); +semilogx(ax3, fPlot, C(fMask), 'Color', th.bodeCoherence, 'LineWidth', 1.2); hold(ax3, 'on'); line(ax3, [fPlot(1) fPlot(end)], [.8 .8], 'Color', th.bodeRef, 'LineStyle', '--'); hold(ax3, 'off'); @@ -69,81 +116,143 @@ function PSplotBode(freq, G_track, G_plant, C, stepData, titleStr) end % --- step response (right side) --- -ax4 = axes('Parent', fig, 'Units', 'normalized', 'Position', [.72 .42 .24 .52]); +ax4 = axes('Parent', fig, 'Units', 'normalized', 'Position', pos4); +hold(ax4, 'on'); if ~isempty(stepData) && isfield(stepData, 't_ms') && isfield(stepData, 'step') plot(ax4, stepData.t_ms, stepData.step, 'Color', th.bodeMain, 'LineWidth', 1.8); - hold(ax4, 'on'); line(ax4, [0 max(stepData.t_ms)], [1 1], 'Color', th.bodeRef, 'LineStyle', '--'); - % overshoot peak = max(stepData.step); if peak > 1.01 - os_pct = (peak - 1) * 100; [~, pk_idx] = max(stepData.step); plot(ax4, stepData.t_ms(pk_idx), peak, 'ro', 'MarkerSize', 8, 'LineWidth', 2); - text(stepData.t_ms(pk_idx)+5, peak, sprintf('%.0f%%', os_pct), ... + text(stepData.t_ms(pk_idx)+5, peak, sprintf('%.0f%%', (peak-1)*100), ... 'Color', th.btnDash1, 'FontSize', fontsz, 'FontWeight', 'bold', 'Parent', ax4); end - hold(ax4, 'off'); end +hPredStep = []; +if hasPred + hPredStep = plot(ax4, nan, nan, 'Color', th.bodePredicted, 'LineWidth', 1.8); +end +hold(ax4, 'off'); PSstyleAxes(ax4, th); set(get(ax4, 'XLabel'), 'String', 'Time (ms)'); set(get(ax4, 'YLabel'), 'String', 'Step Response'); title(ax4, 'Step (from FRD)'); -% --- info panel (bottom right) --- -ax5 = axes('Parent', fig, 'Units', 'normalized', 'Position', [.72 .08 .24 .26]); +% --- info panel --- +ax5 = axes('Parent', fig, 'Units', 'normalized', 'Position', pos5); set(ax5, 'Visible', 'off'); -% gain/phase margins from tracking TF -[gm_dB, pm_deg, wcg, wcp] = margins_from_G(fPlot, G_track(freq > 0)); - infoLines = {}; -infoLines{end+1} = sprintf('Gain margin: %.1f dB @ %.0f Hz', gm_dB, wcg); -infoLines{end+1} = sprintf('Phase margin: %.1f deg @ %.0f Hz', pm_deg, wcp); if ~isempty(stepData) && isfield(stepData, 'step') peak = max(stepData.step); - infoLines{end+1} = sprintf('Overshoot: %.0f%%', max(0, (peak-1)*100)); - % settling time (2% band) + infoLines{end+1} = sprintf('Measured overshoot: %.0f%%', max(0, (peak-1)*100)); settled = find(abs(stepData.step - 1) < 0.02 & stepData.t_ms > stepData.t_ms(end)*0.1, 1); if ~isempty(settled) - infoLines{end+1} = sprintf('Settling (2%%): %.0f ms', stepData.t_ms(settled)); + infoLines{end+1} = sprintf('Measured settling (2%%): %.0f ms', stepData.t_ms(settled)); end end -text(0.05, 0.9, infoLines, 'Parent', ax5, 'Color', th.bodeMain, ... +if ~hasPred + % Margins need the open loop. Without the PID terms in the log there is no + % plant and so no open loop - the numbers that used to go here were taken + % off the closed loop and meant nothing. + infoLines{end+1} = 'Margins need the PID terms in the log'; +end +hInfo = text(0.05, 0.95, infoLines, 'Parent', ax5, 'Color', th.bodeMain, ... 'FontSize', fontsz, 'FontWeight', 'bold', 'VerticalAlignment', 'top', ... 'Units', 'normalized'); -PSdatatipSetup(fig); +hPredInfo = []; +hSl = []; hLbl = []; +gNames = {'P', 'I', 'D', 'FF'}; +g0 = [0 0 0 0]; +if hasPred + hPredInfo = text(0.05, 0.45, {''}, 'Parent', ax5, 'Color', th.bodePredicted, ... + 'FontSize', fontsz, 'FontWeight', 'bold', 'VerticalAlignment', 'top', ... + 'Units', 'normalized'); + g0 = [pred.gains.P pred.gains.I pred.gains.D pred.gains.F]; + buildPanel(); + redraw(); + PSstyleControls(fig, th); end +PSdatatipSetup(fig); + + function buildPanel() + % zero has no scale of its own, so fall back to a firmware-typical range + fallbackHi = [100 100 100 200]; + yTop = .30; rh = .032; dy = .048; + for k = 1:4 + hi = 2.5 * g0(k); + if hi <= 0, hi = fallbackHi(k); end + yy = yTop - (k-1)*dy; + hLbl(k) = uicontrol(fig, 'Style', 'text', 'Units', 'normalized', ... + 'String', sprintf('%s %g', gNames{k}, g0(k)), ... + 'Position', [.700 yy-.004 .052 rh], 'FontSize', fontsz, ... + 'HorizontalAlignment', 'right', ... + 'ForegroundColor', th.textPrimary, 'BackgroundColor', th.figBg); + hSl(k) = uicontrol(fig, 'Style', 'slider', 'Units', 'normalized', ... + 'Position', [.758 yy .200 rh], ... + 'Min', 0, 'Max', hi, 'Value', min(g0(k), hi), ... + 'SliderStep', [1/hi, 10/hi], ... + 'Callback', @(~,~) redraw()); + end + uicontrol(fig, 'Style', 'pushbutton', 'Units', 'normalized', ... + 'String', 'Reset to log', 'Position', [.758 yTop-4.6*dy .095 rh], ... + 'FontSize', fontsz, 'ForegroundColor', th.textPrimary, ... + 'Callback', @(~,~) resetGains()); + end -function [gm_dB, pm_deg, wcg, wcp] = margins_from_G(freq, G) - % gain margin: gain at -180 deg phase crossing - % phase margin: phase at 0 dB gain crossing - mag = abs(G); - phase = unwrap(angle(G)) * 180/pi; - % 0 dB crossing → phase margin - mag_dB = 20*log10(mag + 1e-12); - crossings = find(diff(sign(mag_dB)) ~= 0); - if ~isempty(crossings) - ci = crossings(1); - wcp = interp1(mag_dB(ci:ci+1), freq(ci:ci+1), 0, 'linear'); - pm_deg = interp1(freq(ci:ci+1), phase(ci:ci+1), wcp, 'linear') + 180; - else - wcp = NaN; pm_deg = NaN; + function resetGains() + for k = 1:4 + set(hSl(k), 'Value', min(g0(k), get(hSl(k), 'Max'))); + end + redraw(); end - % -180 deg crossing → gain margin - crossings = find(diff(sign(phase + 180)) ~= 0); - if ~isempty(crossings) - ci = crossings(end); - wcg = interp1(phase(ci:ci+1), freq(ci:ci+1), -180, 'linear'); - gm_val = interp1(freq(ci:ci+1), mag(ci:ci+1), wcg, 'linear'); - gm_dB = -20*log10(gm_val + 1e-12); - else - wcg = NaN; gm_dB = NaN; + + function redraw() + v = zeros(1, 4); + for k = 1:4 + v(k) = round(get(hSl(k), 'Value')); + set(hLbl(k), 'String', sprintf('%s %g', gNames{k}, v(k))); + end + + g = struct('P', v(1), 'I', v(2), 'D', v(3), 'F', v(4)); + [A, D, F] = PSbuildController(g, pred.fp, pred.FsPid, freq); + [Tp, Lp] = PSpredictClosedLoop(G_plant, A, D, F); + + set(hPredMag, 'YData', 20*log10(abs(Tp(predMask)) + 1e-12)); + set(hPredPh, 'YData', unwrap(angle(Tp(predMask))) * 180/pi); + + [tp, sp] = PSstepFromFRD(freq, Tp, min(fTrust, 300)); + set(hPredStep, 'XData', tp, 'YData', sp); + + lines = {}; + pk = max(sp); + lines{end+1} = sprintf('Predicted overshoot: %.0f%%', max(0, (pk-1)*100)); + st = find(abs(sp - 1) < 0.02 & tp > tp(end)*0.1, 1); + if ~isempty(st) + lines{end+1} = sprintf('Predicted settling (2%%): %.0f ms', tp(st)); + end + % margins belong to the open loop, which only exists once a controller + % is put around the measured plant + [gm, pm, wg, wp] = PSmarginsFromL(fPred, Lp(predMask)); + if isnan(pm) + lines{end+1} = 'Phase margin: no 0 dB crossing in band'; + else + lines{end+1} = sprintf('Phase margin: %.0f deg @ %.0f Hz', pm, wp); + end + if isnan(gm) + lines{end+1} = 'Gain margin: no phase crossover in band'; + else + lines{end+1} = sprintf('Gain margin: %.1f dB @ %.0f Hz', gm, wg); + end + lines{end+1} = sprintf('Plant good to %.0f Hz', fTrust); + set(hPredInfo, 'String', lines); end + end diff --git a/src/plot/PSrunChirpAnalysis.m b/src/plot/PSrunChirpAnalysis.m index c260025..b6b5e89 100644 --- a/src/plot/PSrunChirpAnalysis.m +++ b/src/plot/PSrunChirpAnalysis.m @@ -78,7 +78,17 @@ function PSrunChirpAnalysis(T, setupInfo, debugIdx, Fs, tIND, axisIdx) stepData = []; end +% controller model for the prediction sliders - needs the gains and the dterm +% filters from the header, and the PID rate rather than the logging rate +pred = []; +if hasAxisSum && ~isempty(setupInfo) + fp = PSparseFilterParams(setupInfo); + FsPid = fp.pid_rate_hz; + if FsPid <= 0, FsPid = Fs; end + pred = struct('gains', PSparsePIDGains(setupInfo, axisIdx), 'fp', fp, 'FsPid', FsPid); +end + % plot -PSplotBode(freq, G_track, G_plant, C_track, stepData, axNames{ax}); +PSplotBode(freq, G_track, G_plant, C_track, stepData, axNames{ax}, pred); end diff --git a/src/util/PStheme.m b/src/util/PStheme.m index eee4128..2691c04 100644 --- a/src/util/PStheme.m +++ b/src/util/PStheme.m @@ -91,6 +91,7 @@ th.bodeSecondary = [1.0 .50 0]; % plant TF - orange th.bodeCoherence = [.30 .90 .30]; % coherence - green th.bodeRef = [.50 .50 .50]; % reference lines (0dB, -180, unity) +th.bodePredicted = [.70 .40 .95]; % predicted closed loop - chirp purple % transport buttons (Player) th.btnPlay = [0 .60 0]; % play - dark green diff --git a/tests/test_PSmarginsFromL.m b/tests/test_PSmarginsFromL.m new file mode 100644 index 0000000..c4522e2 --- /dev/null +++ b/tests/test_PSmarginsFromL.m @@ -0,0 +1,58 @@ +% test_PSmarginsFromL.m - tests for stability margins of the open loop + +%!test +%! % Third order lag with known margins: L = K/(1 + j f/f0)^3, K=2, f0=1 Hz. +%! % |L| = 1 at f = 0.766421, phase there -112.3754 deg -> PM 67.6246 +%! % phase = -180 at f = tan(60 deg) = 1.7320508, |L| = K/8 -> GM 12.0412 dB +%! f = (0.01:0.001:5)'; +%! L = 2 ./ (1 + 1j*f).^3; +%! [gm, pm, wg, wp] = PSmarginsFromL(f, L); +%! assert(wp, 0.766421, 1e-3); +%! assert(pm, 67.6246, 0.05); +%! assert(wg, 1.7320508, 1e-3); +%! assert(gm, 12.0412, 0.05); + +%!test +%! % A quad rate loop is already past -180 deg at the bottom of the band, so +%! % the principal value has to be used - unwrapping from the first bin puts +%! % the answer a full turn out and reports a phase margin over 360 deg. +%! f = (0.4:0.01:200)'; +%! phd = min(-210 + 4*f, -100); % -208.4 deg at the first bin, levels off +%! L = (25 ./ f) .* exp(1j*phd*pi/180); +%! assert(angle(L(1)) > 0, 'fixture must start with a positive principal angle'); +%! [gm, pm, wg, wp] = PSmarginsFromL(f, L); +%! assert(wp, 25, 0.05); +%! assert(pm, 70, 0.2); +%! % the -180 crossing at 7.5 Hz sits below the gain crossover and belongs to +%! % the conditionally stable region, so it is not the gain margin +%! assert(isnan(gm), 'a crossing below the gain crossover is not the gain margin'); + +%!test +%! % Pure integrator: crosses 0 dB at fc with 90 deg to spare and never +%! % reaches -180, so there is no gain margin to report +%! fc = 12; +%! f = (0.1:0.005:100)'; +%! L = fc ./ (1j*f); +%! [gm, pm, wg, wp] = PSmarginsFromL(f, L); +%! assert(wp, fc, 0.02); +%! assert(pm, 90, 0.1); +%! assert(isnan(gm)); +%! assert(isnan(wg)); + +%!test +%! % A loop that never reaches 0 dB has no phase margin +%! f = (1:0.5:500)'; +%! L = 0.01 ./ (1 + 1j*f/50); +%! [gm, pm, wg, wp] = PSmarginsFromL(f, L); +%! assert(isnan(pm)); +%! assert(isnan(wp)); + +%!test +%! % Margins are returned in (-180, 180]: a loop crossing over with 200 deg of +%! % lag is unstable and must read as a negative margin, not 160 +%! f = (0.4:0.01:200)'; +%! phd = -260 + 3*f; % -200 deg at the 20 Hz crossover +%! L = (20 ./ f) .* exp(1j*phd*pi/180); +%! [~, pm, ~, wp] = PSmarginsFromL(f, L); +%! assert(wp, 20, 0.05); +%! assert(pm, -20, 0.2); From 9f62b58cdafe47a0560a93f41b64287234fd8a41 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 13:16:58 +0200 Subject: [PATCH 07/20] fix(filter-sim): use the firmware formula for notch Q from centre and cutoff --- src/core/PSbuildController.m | 4 ++-- src/plot/PSfilterSim.m | 6 ++++-- src/ui/PSTestSignalConfig.m | 3 ++- src/util/PSnotchQ.m | 17 +++++++++++++++++ tests/test_PSnotchQ.m | 35 +++++++++++++++++++++++++++++++++++ 5 files changed, 60 insertions(+), 5 deletions(-) create mode 100644 src/util/PSnotchQ.m create mode 100644 tests/test_PSnotchQ.m diff --git a/src/core/PSbuildController.m b/src/core/PSbuildController.m index d5c7d6d..b290fe2 100644 --- a/src/core/PSbuildController.m +++ b/src/core/PSbuildController.m @@ -76,8 +76,8 @@ function H = notchResp(center_hz, cutoff_hz, Fs, freq) H = ones(numel(freq), 1); - if center_hz <= 0 || cutoff_hz <= 0 || cutoff_hz >= center_hz, return; end - Q = center_hz * cutoff_hz / (center_hz^2 - cutoff_hz^2); + Q = PSnotchQ(center_hz, cutoff_hz); + if Q <= 0, return; end [b, a] = PSbfFilters('notch', center_hz, Fs, Q); H = freqz(b, a, freq, Fs); H = H(:); diff --git a/src/plot/PSfilterSim.m b/src/plot/PSfilterSim.m index cce7abe..7d8e32b 100644 --- a/src/plot/PSfilterSim.m +++ b/src/plot/PSfilterSim.m @@ -1018,7 +1018,8 @@ function barClick(ax, edits, fMax) function y = applyNotch(x, center_hz, cutoff_hz, Fs) if center_hz == 0, y = x; return; end if cutoff_hz <= 0, cutoff_hz = center_hz * 0.7; end - Q = center_hz / (center_hz - cutoff_hz + 1); + Q = PSnotchQ(center_hz, cutoff_hz); + if Q <= 0, y = x; return; end [b, a] = PSbfFilters('notch', center_hz, Fs, Q); y = filter(b, a, x); end @@ -1041,7 +1042,8 @@ function barClick(ax, edits, fMax) H = ones(Nfft, 1); if center_hz == 0, return; end if cutoff_hz <= 0, cutoff_hz = center_hz * 0.7; end - Q = center_hz / (center_hz - cutoff_hz + 1); + Q = PSnotchQ(center_hz, cutoff_hz); + if Q <= 0, return; end [b, a] = PSbfFilters('notch', center_hz, Fs, Q); [H, ~] = freqz(b, a, Nfft, Fs); H = H(:); diff --git a/src/ui/PSTestSignalConfig.m b/src/ui/PSTestSignalConfig.m index 39e2ae1..4c90644 100644 --- a/src/ui/PSTestSignalConfig.m +++ b/src/ui/PSTestSignalConfig.m @@ -375,7 +375,8 @@ function applyToLogViewer() function y = applyNotch(x, center_hz, cutoff_hz, Fs) if center_hz == 0, y = x; return; end if cutoff_hz <= 0, cutoff_hz = center_hz * 0.7; end - Q = center_hz / (center_hz - cutoff_hz + 1); + Q = PSnotchQ(center_hz, cutoff_hz); + if Q <= 0, y = x; return; end [b, a] = PSbfFilters('notch', center_hz, Fs, Q); y = filter(b, a, x); end diff --git a/src/util/PSnotchQ.m b/src/util/PSnotchQ.m new file mode 100644 index 0000000..ced8c32 --- /dev/null +++ b/src/util/PSnotchQ.m @@ -0,0 +1,17 @@ +function q = PSnotchQ(center_hz, cutoff_hz) +%% PSnotchQ - quality factor BF derives from a notch centre and cutoff +% Mirrors filterGetNotchQ in BF common/filter.c. The cutoff is the lower +% -3 dB corner of the notch, which is what sets how wide it is and so how +% much delay it costs. +% +% Returns 0 when the pair cannot describe a notch - the firmware skips the +% filter on a zero cutoff, and a cutoff at or above the centre has no meaning. + +if center_hz <= 0 || cutoff_hz <= 0 || cutoff_hz >= center_hz + q = 0; + return +end + +q = center_hz * cutoff_hz / (center_hz^2 - cutoff_hz^2); + +end diff --git a/tests/test_PSnotchQ.m b/tests/test_PSnotchQ.m new file mode 100644 index 0000000..22ed3c0 --- /dev/null +++ b/tests/test_PSnotchQ.m @@ -0,0 +1,35 @@ +% test_PSnotchQ.m - tests for the BF notch quality factor + +%!test +%! % filterGetNotchQ in BF common/filter.c: +%! % centerFreq * cutoffFreq / (centerFreq^2 - cutoffFreq^2) +%! assert(PSnotchQ(500, 350), 1.3725490196, 1e-9); +%! assert(PSnotchQ(300, 200), 1.2, 1e-9); +%! assert(PSnotchQ(200, 100), 0.6666666667, 1e-9); +%! assert(PSnotchQ(150, 120), 2.2222222222, 1e-9); + +%!test +%! % What the formula is for: cutoff is the lower -3 dB corner of the notch, +%! % so the response there must be down 3 dB and not somewhere else. +%! Fs = 8000; +%! for c = [300 500 700] +%! for cut = [0.5 0.7 0.85] * c +%! [b, a] = PSbfFilters('notch', c, Fs, PSnotchQ(c, cut)); +%! H = freqz(b, a, [cut c], Fs); +%! assert(20*log10(abs(H(1))), -3.01, 0.3); +%! assert(abs(H(2)) < 0.01, 'the notch must still be deep at its centre'); +%! end +%! end + +%!test +%! % A cutoff closer to the centre means a narrower, higher Q notch +%! q = arrayfun(@(cut) PSnotchQ(500, cut), [100 200 300 400 450]); +%! assert(all(diff(q) > 0), 'Q must rise as the cutoff approaches the centre'); + +%!test +%! % Unusable settings disable the notch rather than returning a negative Q +%! assert(PSnotchQ(500, 0), 0); +%! assert(PSnotchQ(0, 350), 0); +%! assert(PSnotchQ(350, 350), 0); +%! assert(PSnotchQ(350, 500), 0); +%! assert(PSnotchQ(-1, 350), 0); From ad981bbae673dd8118c3827b54c38aeb8aa67989 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:05:02 +0200 Subject: [PATCH 08/20] chore: bump version to 26.09.0-alpha --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index bf58b94..83d4f78 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -26.08.0 +26.09.0-alpha From eb709b53d57b03c52281bcc75d05e7c1ceecf0af Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:22:42 +0200 Subject: [PATCH 09/20] ci: ship the flatpak in releases and stop rebuilding it on every push --- .github/workflows/ci.yml | 24 ------------------ .github/workflows/flatpak.yml | 48 +++++++++++++++++++++++++++++++++++ .github/workflows/release.yml | 4 ++- 3 files changed, 51 insertions(+), 25 deletions(-) create mode 100644 .github/workflows/flatpak.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 96dad49..79dcfff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,27 +43,3 @@ jobs: - name: Run unit tests run: octave --no-gui --eval "run('tests/run_tests.m')" - - flatpak: - runs-on: ubuntu-24.04 - timeout-minutes: 60 - permissions: - contents: read - container: - image: ghcr.io/flathub-infra/flatpak-github-actions:kde-6.10 - options: --privileged - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - persist-credentials: false - - - name: Add Flathub remote for the Octave base app - run: | - flatpak remote-add --if-not-exists --user flathub \ - https://dl.flathub.org/repo/flathub.flatpakrepo - - - uses: flatpak/flatpak-github-actions/flatpak-builder@79327416609af08178ad73b352877e51450790b3 # v6.8 - with: - bundle: PIDscope.flatpak - manifest-path: packaging/flatpak/com.pidscope.PIDscope.yml - cache-key: flatpak-builder-${{ github.sha }} diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.yml new file mode 100644 index 0000000..7024769 --- /dev/null +++ b/.github/workflows/flatpak.yml @@ -0,0 +1,48 @@ +name: Flatpak + +# The flatpak build takes up to an hour and only breaks when the manifest or the +# revisions it pins move, so it runs on those paths rather than on every push. +# Release builds it separately and ships the bundle. +on: + push: + branches: [main, pidscope] + paths: + - 'packaging/flatpak/**' + - '.github/workflows/flatpak.yml' + pull_request: + branches: [main] + paths: + - 'packaging/flatpak/**' + - '.github/workflows/flatpak.yml' + workflow_dispatch: + +permissions: {} + +concurrency: + group: flatpak-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + flatpak: + runs-on: ubuntu-24.04 + timeout-minutes: 60 + permissions: + contents: read + container: + image: ghcr.io/flathub-infra/flatpak-github-actions:kde-6.10 + options: --privileged + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Add Flathub remote for the Octave base app + run: | + flatpak remote-add --if-not-exists --user flathub \ + https://dl.flathub.org/repo/flathub.flatpakrepo + + - uses: flatpak/flatpak-github-actions/flatpak-builder@79327416609af08178ad73b352877e51450790b3 # v6.8 + with: + bundle: PIDscope.flatpak + manifest-path: packaging/flatpak/com.pidscope.PIDscope.yml + cache-key: flatpak-builder-${{ github.sha }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ff0f870..fea813e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -147,6 +147,7 @@ jobs: path: dist/PIDscope-*-x86_64.AppImage build-flatpak: + needs: test runs-on: ubuntu-24.04 timeout-minutes: 60 permissions: @@ -271,7 +272,7 @@ jobs: # Stage 3: Create GitHub Release release: if: startsWith(github.ref, 'refs/tags/') - needs: [build-appimage, build-windows, build-macos] + needs: [build-appimage, build-windows, build-macos, build-flatpak] runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: @@ -288,6 +289,7 @@ jobs: artifacts/appimage/* artifacts/windows-zip/* artifacts/macos-zip/* + artifacts/flatpak/* generate_release_notes: true draft: ${{ contains(github.ref_name, 'beta') }} prerelease: ${{ contains(github.ref_name, 'rc') || contains(github.ref_name, 'beta') }} From 3c78fdf9b4d8e630791436cdf82e712abd47f8e2 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:26:26 +0200 Subject: [PATCH 10/20] ci: run the flatpak build on demand only, not on push or PR --- .github/workflows/flatpak.yml | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.yml index 7024769..58f773d 100644 --- a/.github/workflows/flatpak.yml +++ b/.github/workflows/flatpak.yml @@ -1,19 +1,8 @@ name: Flatpak -# The flatpak build takes up to an hour and only breaks when the manifest or the -# revisions it pins move, so it runs on those paths rather than on every push. -# Release builds it separately and ships the bundle. +# Packaging, not a test. Release builds and ships the bundle; this is here for +# checking a manifest change without cutting a tag. on: - push: - branches: [main, pidscope] - paths: - - 'packaging/flatpak/**' - - '.github/workflows/flatpak.yml' - pull_request: - branches: [main] - paths: - - 'packaging/flatpak/**' - - '.github/workflows/flatpak.yml' workflow_dispatch: permissions: {} From b6484504097731107964d1bb042c51542fe04993 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:29:18 +0200 Subject: [PATCH 11/20] fix(chirp): scale feedforward by 0.01 and yaw I gain by 2.5 as the firmware does --- src/core/PSbuildController.m | 10 +++++++++- src/util/PSparsePIDGains.m | 1 + tests/test_PSbuildController.m | 33 ++++++++++++++++++++++++++++++++ tests/test_PSpredictClosedLoop.m | 2 +- 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/core/PSbuildController.m b/src/core/PSbuildController.m index b290fe2..f7f8d6c 100644 --- a/src/core/PSbuildController.m +++ b/src/core/PSbuildController.m @@ -6,6 +6,7 @@ % checked straight against a log. % % gains - struct with P, I, D, F (as entered in the firmware), optional tpa +% and axis (0=Roll, 1=Pitch, 2=Yaw; yaw runs 2.5x the I gain) % fp - filter params from PSparseFilterParams, or [] for no dterm filtering % Fs - PID loop rate (Hz) % freq - frequency vector (Hz) @@ -24,11 +25,18 @@ tpa = 1; if isfield(gains, 'tpa') && ~isempty(gains.tpa), tpa = gains.tpa; end +axis = 0; +if isfield(gains, 'axis') && ~isempty(gains.axis), axis = gains.axis; end Kp = gains.P * PTERM_SCALE * tpa; Ki = gains.I * ITERM_SCALE; Kd = gains.D * DTERM_SCALE * tpa; -Kf = gains.F * FF_SCALE; +% pid_init.c divides the feedforward slider by 100 before scaling it +Kf = gains.F * FF_SCALE * 0.01; + +if axis == 2 + Ki = Ki * 2.5; +end Ts = 1 / Fs; freq = freq(:); diff --git a/src/util/PSparsePIDGains.m b/src/util/PSparsePIDGains.m index 9994d88..eaaf037 100644 --- a/src/util/PSparsePIDGains.m +++ b/src/util/PSparsePIDGains.m @@ -10,6 +10,7 @@ axKeys = {'rollPID', 'pitchPID', 'yawPID'}; pid = hlist(si, axKeys{axisIdx + 1}, [0 0 0]); +g.axis = axisIdx; g.P = pid(1); g.I = pid(2); g.D = pid(3); diff --git a/tests/test_PSbuildController.m b/tests/test_PSbuildController.m index d2d2742..9fb727a 100644 --- a/tests/test_PSbuildController.m +++ b/tests/test_PSbuildController.m @@ -43,6 +43,39 @@ %! assert(max(abs(Dlp - Draw .* H(:))) < 1e-12, 'D path must carry the dterm lowpass'); %! assert(abs(Dlp(end)) < 0.3*abs(Draw(end)), 'lowpass must cut the D path at 500 Hz'); +%!test +%! % Feedforward carries an extra 0.01 the other three terms do not: +%! % pid_init.c has Kf = FEEDFORWARD_SCALE * (pid[axis].F * 0.01f) +%! Fs = 8000; freq = (10:10:200)'; +%! g = struct('P', 0, 'I', 0, 'D', 0, 'F', 120); +%! [~, ~, F] = PSbuildController(g, [], Fs, freq); +%! ideal = 120 * 0.013754 * 0.01 * 2*pi*freq; +%! assert(max(abs(abs(F) - ideal) ./ ideal) < 0.01, 'FF must carry the 0.01 from pid_init'); + +%!test +%! % Yaw runs 2.5x the I gain of roll and pitch (pid_init.c), and nothing else +%! % on that axis is scaled +%! Fs = 8000; freq = (1:2:99)'; +%! g = struct('P', 40, 'I', 80, 'D', 25, 'F', 100); +%! roll = g; roll.axis = 0; +%! yaw = g; yaw.axis = 2; +%! [Ar, Dr, Fr] = PSbuildController(roll, [], Fs, freq); +%! [Ay, Dy, Fy] = PSbuildController(yaw, [], Fs, freq); +%! assert(max(abs(Dy - Dr)) < 1e-18, 'yaw must not scale the D path'); +%! assert(max(abs(Fy - Fr)) < 1e-18, 'yaw must not scale feedforward'); +%! Kp = 40*0.032029; +%! assert(max(abs((Ay - Kp) - 2.5*(Ar - Kp))) < 1e-12, 'yaw I gain must be 2.5x'); + +%!test +%! % An axis that is not named behaves like roll +%! Fs = 8000; freq = (1:2:99)'; +%! g = struct('P', 40, 'I', 80, 'D', 25, 'F', 0); +%! A0 = PSbuildController(g, [], Fs, freq); +%! g.axis = 0; A1 = PSbuildController(g, [], Fs, freq); +%! g.axis = 1; A2 = PSbuildController(g, [], Fs, freq); +%! assert(max(abs(A1 - A0)) < 1e-18); +%! assert(max(abs(A2 - A0)) < 1e-18); + %!test %! % TPA scales P and D, never I or FF %! Fs = 8000; freq = (20:20:400)'; diff --git a/tests/test_PSpredictClosedLoop.m b/tests/test_PSpredictClosedLoop.m index 6b8a630..7e9c493 100644 --- a/tests/test_PSpredictClosedLoop.m +++ b/tests/test_PSpredictClosedLoop.m @@ -54,7 +54,7 @@ %! fp = struct('dterm_lpf1_type', 0, 'dterm_lpf1_hz', 80, ... %! 'dterm_lpf2_type', 0, 'dterm_lpf2_hz', 0, ... %! 'dterm_notch_hz', 0, 'dterm_notch_cut', 0); -%! Kp = 45*0.032029; Ki = 60*0.244381; Kd = 20*0.000529; Kf = 90*0.013754; +%! Kp = 45*0.032029; Ki = 60*0.244381; Kd = 20*0.000529; Kf = 90*0.013754*0.01; %! pt1k = @(fc) (1/Fs) / (1/(2*pi*fc) + 1/Fs); %! kPlant = pt1k(60 * 1.553773974); % pt2 at 60 Hz, as PSbfFilters builds it %! kDterm = pt1k(80); From d75656c60bb5018cbab8dedd2425406b55a15884 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:33:43 +0200 Subject: [PATCH 12/20] chore: bump version to 26.09.0-rc1 --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index 83d4f78..ddb1ce6 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -26.09.0-alpha +26.09.0-rc1 From 0b10ff15a8f2375c7ce368bc0183a37f0e180e8c Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:34:09 +0200 Subject: [PATCH 13/20] test(chirp): pin the PID scaling constants to the firmware and cover the FF path --- src/core/PSbuildController.m | 6 ++-- tests/test_PSbuildController.m | 52 ++++++++++++++++++++++++-------- tests/test_PSpredictClosedLoop.m | 11 +++++++ 3 files changed, 54 insertions(+), 15 deletions(-) diff --git a/src/core/PSbuildController.m b/src/core/PSbuildController.m index f7f8d6c..b3bb6c7 100644 --- a/src/core/PSbuildController.m +++ b/src/core/PSbuildController.m @@ -15,8 +15,10 @@ % D - Kd*s*Hdterm, on the gyro (enters the loop with a minus sign) % F - Kff*s, on the setpoint % -% Feedforward smoothing is not modelled, so F is optimistic on a log flown -% with heavy smoothing - compare against the logged axisF before trusting it. +% F is the weakest of the three. The firmware differentiates the setpoint at +% the RX rate, not the PID rate, then puts it through PT3 smoothing, boost and +% jitter reduction (rc.c:439,463,505,510). This models a plain derivative at +% the PID rate, so hold F against the logged axisF before trusting it. PTERM_SCALE = 0.032029; ITERM_SCALE = 0.244381; diff --git a/tests/test_PSbuildController.m b/tests/test_PSbuildController.m index 9fb727a..89b70bb 100644 --- a/tests/test_PSbuildController.m +++ b/tests/test_PSbuildController.m @@ -44,13 +44,27 @@ %! assert(abs(Dlp(end)) < 0.3*abs(Draw(end)), 'lowpass must cut the D path at 500 Hz'); %!test -%! % Feedforward carries an extra 0.01 the other three terms do not: -%! % pid_init.c has Kf = FEEDFORWARD_SCALE * (pid[axis].F * 0.01f) -%! Fs = 8000; freq = (10:10:200)'; -%! g = struct('P', 0, 'I', 0, 'D', 0, 'F', 120); -%! [~, ~, F] = PSbuildController(g, [], Fs, freq); -%! ideal = 120 * 0.013754 * 0.01 * 2*pi*freq; -%! assert(max(abs(abs(F) - ideal) ./ ideal) < 0.01, 'FF must carry the 0.01 from pid_init'); +%! % Every scaling constant pinned to where the firmware sets it, so they can be +%! % rechecked against the source instead of taken on trust. This suite once +%! % passed with the feedforward path 100x too large because nothing here held +%! % a constant against anything outside the model. +%! % pid.h:46-48,52 PTERM 0.032029 ITERM 0.244381 DTERM 0.000529 FF 0.013754 +%! % pid_init.c:373-375 Kp, Ki, Kd = SCALE * slider +%! % pid_init.c:376 Kf = FEEDFORWARD_SCALE * (slider * 0.01f) +%! % pid_init.c:378 pidCoefficient[FD_YAW].Ki *= 2.5f +%! Fs = 8000; freq = (5:5:200)'; +%! zinv = exp(-2j*pi*freq/Fs); +%! deriv = (1 - zinv) * Fs; +%! [A, D, F] = PSbuildController(struct('P', 100, 'I', 0, 'D', 0, 'F', 0), [], Fs, freq); +%! assert(max(abs(A - 100*0.032029)) < 1e-14, 'PTERM_SCALE'); +%! A = PSbuildController(struct('P', 0, 'I', 100, 'D', 0, 'F', 0), [], Fs, freq); +%! assert(max(abs(A .* (1 - zinv) - 100*0.244381/Fs)) < 1e-15, 'ITERM_SCALE'); +%! [~, D] = PSbuildController(struct('P', 0, 'I', 0, 'D', 100, 'F', 0), [], Fs, freq); +%! assert(max(abs(D ./ deriv - 100*0.000529)) < 1e-15, 'DTERM_SCALE'); +%! [~, ~, F] = PSbuildController(struct('P', 0, 'I', 0, 'D', 0, 'F', 100), [], Fs, freq); +%! assert(max(abs(F ./ deriv - 100*0.013754*0.01)) < 1e-15, 'FEEDFORWARD_SCALE and its 0.01'); +%! Ay = PSbuildController(struct('P', 0, 'I', 100, 'D', 0, 'F', 0, 'axis', 2), [], Fs, freq); +%! assert(max(abs(Ay .* (1 - zinv) - 2.5*100*0.244381/Fs)) < 1e-15, 'yaw I gain 2.5x'); %!test %! % Yaw runs 2.5x the I gain of roll and pitch (pid_init.c), and nothing else @@ -90,27 +104,39 @@ %! 'TPA must scale only the proportional part of A'); %!test -%! % The transfer functions must match the difference equations BF actually runs. -%! % Time domain is the reference here: it mirrors the C code sample by sample, -%! % the frequency response is the derived form under test. +%! % The transfer functions must match the difference equations BF runs. The +%! % time domain is the reference: these are transcribed from the firmware, with +%! % the line each one comes from, so the transcription can be checked. All three +%! % paths are covered - leaving F out of here is how the 0.01 stayed missing. +%! % pid.c:1294 P = Kp * errorRate +%! % pid.c:1318,1326 iTermChange = Ki * dT * errorRate; I = previousIterm + iTermChange +%! % pid.c:1151-1153 dterm chain: notch, then lowpass, then lowpass2 +%! % pid.c:1359-1360 delta = -(gyroRateDterm[k] - gyroRateDterm[k-1]) * pidFrequency +%! % preTpaD = Kd * delta +%! % pid.c:1410 F = Kf * pidSetpointDelta %! Fs = 2000; Ts = 1/Fs; N = 40000; %! randn('state', 7); -%! g = struct('P', 45, 'I', 80, 'D', 30, 'F', 0); -%! Kp = 45*0.032029; Ki = 80*0.244381; Kd = 30*0.000529; +%! g = struct('P', 45, 'I', 80, 'D', 30, 'F', 120); +%! Kp = 45*0.032029; Ki = 80*0.244381; Kd = 30*0.000529; Kf = 120*0.013754*0.01; %! e = randn(N, 1); %! uA = Kp*e + Ki*Ts*cumsum(e); %! y = randn(N, 1); %! [b, a] = PSbfFilters('pt1', 90, Fs); %! yd = filter(b, a, y); %! uD = Kd * [0; diff(yd)] / Ts; +%! r = randn(N, 1); +%! uF = Kf * [0; diff(r)] / Ts; %! [Ahat, ~, freq] = PSestimateFreqResponse(e, uA, Fs); %! [Dhat, ~, ~] = PSestimateFreqResponse(y, uD, Fs); +%! [Fhat, ~, ~] = PSestimateFreqResponse(r, uF, Fs); %! fp = struct('dterm_lpf1_type', 0, 'dterm_lpf1_hz', 90, ... %! 'dterm_lpf2_type', 0, 'dterm_lpf2_hz', 0, ... %! 'dterm_notch_hz', 0, 'dterm_notch_cut', 0); -%! [A, D] = PSbuildController(g, fp, Fs, freq); +%! [A, D, F] = PSbuildController(g, fp, Fs, freq); %! band = freq > 10 & freq < 400; % below 10 Hz a 2.5 s Welch segment holds too few cycles %! assert(max(abs(Ahat(band) - A(band)) ./ abs(A(band))) < 0.01, ... %! 'A must match the PI difference equation'); %! assert(max(abs(Dhat(band) - D(band)) ./ abs(D(band))) < 0.01, ... %! 'D must match the filtered-derivative difference equation'); +%! assert(max(abs(Fhat(band) - F(band)) ./ abs(F(band))) < 0.01, ... +%! 'F must match the scaled setpoint-derivative difference equation'); diff --git a/tests/test_PSpredictClosedLoop.m b/tests/test_PSpredictClosedLoop.m index 7e9c493..1b83d3c 100644 --- a/tests/test_PSpredictClosedLoop.m +++ b/tests/test_PSpredictClosedLoop.m @@ -49,6 +49,17 @@ %! % the plant the way PSrunChirpAnalysis does, then predict the loop back from %! % it. The identified plant is model-free, so a wrong controller model (sign, %! % sample offset, scaling) shows up here even though the plant still matches. +%! % The loop below is transcribed from the firmware, not from PSbuildController - +%! % if both sides came from the same belief this test would only confirm it: +%! % pid.c:1294 P = Kp * errorRate +%! % pid.c:1318,1326 I = previousIterm + Ki * dT * errorRate +%! % pid.c:1359-1360 D = Kd * -(dtermGyro[k] - dtermGyro[k-1]) * pidFrequency +%! % pid.c:1410 F = Kf * pidSetpointDelta +%! % pid_init.c:376 Kf carries an extra 0.01 the other three do not +%! % Known gap: the firmware differentiates the setpoint at the RX rate and runs +%! % it through PT3 smoothing, boost and jitter reduction (rc.c:439,463,505,510). +%! % This models a plain derivative at the PID rate, so the F path is an +%! % approximation - see the header of PSbuildController. %! Fs = 2000; Ts = 1/Fs; N = 60000; %! g = struct('P', 45, 'I', 60, 'D', 20, 'F', 90); %! fp = struct('dterm_lpf1_type', 0, 'dterm_lpf1_hz', 80, ... From c4132d6599cd4fda8b26e1f5ceb7ac9cfa5110df Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:39:55 +0200 Subject: [PATCH 14/20] fix(firmware): correct debug mode indices per Betaflight version --- src/core/PSdebugModeIndices.m | 44 ++++++++++++++++++++----- tests/test_PSdebugModeIndices.m | 58 ++++++++++++++++++++++++++++++--- 2 files changed, 88 insertions(+), 14 deletions(-) diff --git a/src/core/PSdebugModeIndices.m b/src/core/PSdebugModeIndices.m index 60f8eee..788e318 100644 --- a/src/core/PSdebugModeIndices.m +++ b/src/core/PSdebugModeIndices.m @@ -1,26 +1,52 @@ function idx = PSdebugModeIndices(fwType, fwMajor, fwMinor) %% PSdebugModeIndices - return debug mode index constants for a given firmware version % idx = PSdebugModeIndices(fwType, fwMajor, fwMinor) +% +% Positions in debugType_e (src/main/build/debug.h), read at the firmware tags: +% +% mode 4.0 4.1-4.2 4.3-4.5 2025.12 2026.6 +% GYRO_FILTERED 3 3 3 3 3 +% GYRO_SCALED 6 6 6 - - +% RC_INTERPOLATION 7 7 7 6 6 +% FFT_FREQ 17 17 17 16 16 +% DSHOT_RPM_TELEMETRY 47 45 45 45 45 +% RPM_FILTER 48 46 46 46 46 +% FEEDFORWARD - - 59 59 59 +% CHIRP - - - 97 96 +% +% Dropping GYRO_SCALED in 2025.12 shifted RC_INTERPOLATION and FFT_FREQ down +% by one but left the RPM and feedforward entries where they were - modes were +% added ahead of them in the same release. -% Default: BF 4.x / Emuflight / INAV / FETTEC / QuickSilver / Rotorflight / KISS +% Default: BF 4.3-4.5 / Emuflight / INAV / FETTEC / QuickSilver / Rotorflight / KISS idx.GYRO_SCALED = 6; idx.GYRO_FILTERED = 3; idx.RC_INTERPOLATION = 7; idx.FFT_FREQ = 17; +idx.DSHOT_RPM_TELEMETRY = 45; idx.RPM_FILTER = 46; idx.FEEDFORWARD = 59; -idx.DSHOT_RPM_TELEMETRY = 37; -idx.CHIRP = -1; % not available in BF 4.x +idx.CHIRP = -1; -% BF 2025.12+ (aka "4.6"): GYRO_SCALED removed at index 6, all indices >= 6 shift by -1 -if strcmp(fwType, 'Betaflight') && fwMajor >= 2025 +isBF = strcmp(fwType, 'Betaflight'); + +if isBF && fwMajor == 4 && fwMinor < 3 + idx.FEEDFORWARD = -1; % arrived in 4.3 + if fwMinor < 1 + idx.DSHOT_RPM_TELEMETRY = 47; + idx.RPM_FILTER = 48; + end +end + +if isBF && fwMajor >= 2025 idx.GYRO_SCALED = -1; idx.RC_INTERPOLATION = 6; idx.FFT_FREQ = 16; - idx.RPM_FILTER = 45; - idx.FEEDFORWARD = 58; - idx.DSHOT_RPM_TELEMETRY = 36; - idx.CHIRP = 97; + if fwMajor >= 2026 + idx.CHIRP = 96; + else + idx.CHIRP = 97; + end end end diff --git a/tests/test_PSdebugModeIndices.m b/tests/test_PSdebugModeIndices.m index 7264312..77c22a5 100644 --- a/tests/test_PSdebugModeIndices.m +++ b/tests/test_PSdebugModeIndices.m @@ -1,27 +1,75 @@ % test_PSdebugModeIndices.m - tests for PSdebugModeIndices +% +% Values read out of debugType_e in src/main/build/debug.h at the firmware tags +% 4.0.6, 4.1.1, 4.2.11, 4.3.2, 4.5.5, 2025.12.5 and 2026.6.2: +% +% mode 4.0 4.1-4.2 4.3-4.5 2025.12 2026.6 +% GYRO_FILTERED 3 3 3 3 3 +% GYRO_SCALED 6 6 6 - - +% RC_INTERPOLATION 7 7 7 6 6 +% FFT_FREQ 17 17 17 16 16 +% DSHOT_RPM_TELEMETRY 47 45 45 45 45 +% RPM_FILTER 48 46 46 46 46 +% FEEDFORWARD - - 59 59 59 +% CHIRP - - - 97 96 +% +% Dropping GYRO_SCALED in 2025.12 did not shift RPM_FILTER, FEEDFORWARD or +% DSHOT_RPM_TELEMETRY - entries were added ahead of them in the same release. %!test -%! % BF 4.5 (old indices) +%! % BF 4.0: the RPM pair sits two higher than it does from 4.1 on +%! idx = PSdebugModeIndices('Betaflight', 4, 0); +%! assert(idx.GYRO_SCALED, 6); +%! assert(idx.GYRO_FILTERED, 3); +%! assert(idx.RC_INTERPOLATION, 7); +%! assert(idx.FFT_FREQ, 17); +%! assert(idx.DSHOT_RPM_TELEMETRY, 47); +%! assert(idx.RPM_FILTER, 48); +%! assert(idx.FEEDFORWARD, -1); +%! assert(idx.CHIRP, -1); + +%!test +%! % BF 4.2: still no feedforward debug +%! idx = PSdebugModeIndices('Betaflight', 4, 2); +%! assert(idx.DSHOT_RPM_TELEMETRY, 45); +%! assert(idx.RPM_FILTER, 46); +%! assert(idx.FEEDFORWARD, -1); + +%!test +%! % BF 4.5 %! idx = PSdebugModeIndices('Betaflight', 4, 5); %! assert(idx.GYRO_SCALED, 6); %! assert(idx.GYRO_FILTERED, 3); %! assert(idx.RC_INTERPOLATION, 7); %! assert(idx.FFT_FREQ, 17); +%! assert(idx.DSHOT_RPM_TELEMETRY, 45); %! assert(idx.RPM_FILTER, 46); %! assert(idx.FEEDFORWARD, 59); +%! assert(idx.CHIRP, -1); %!test -%! % BF 2025.12 (new indices, GYRO_SCALED removed) +%! % BF 2025.12: GYRO_SCALED gone, chirp arrives at 97 %! idx = PSdebugModeIndices('Betaflight', 2025, 12); %! assert(idx.GYRO_SCALED, -1); %! assert(idx.GYRO_FILTERED, 3); %! assert(idx.RC_INTERPOLATION, 6); %! assert(idx.FFT_FREQ, 16); -%! assert(idx.RPM_FILTER, 45); -%! assert(idx.FEEDFORWARD, 58); -%! % DEBUG_CHIRP is 97 in debugType_e; 119 is DEBUG_COUNT, the end sentinel +%! assert(idx.DSHOT_RPM_TELEMETRY, 45); +%! assert(idx.RPM_FILTER, 46); +%! assert(idx.FEEDFORWARD, 59); %! assert(idx.CHIRP, 97); +%!test +%! % BF 2026.6: one entry ahead of chirp went away, so it moved down to 96 +%! idx = PSdebugModeIndices('Betaflight', 2026, 6); +%! assert(idx.CHIRP, 96); +%! assert(idx.GYRO_SCALED, -1); +%! assert(idx.RC_INTERPOLATION, 6); +%! assert(idx.FFT_FREQ, 16); +%! assert(idx.DSHOT_RPM_TELEMETRY, 45); +%! assert(idx.RPM_FILTER, 46); +%! assert(idx.FEEDFORWARD, 59); + %!test %! % INAV (uses default old indices) %! idx = PSdebugModeIndices('INAV', 7, 1); From 138e7c9fb5f43bc8fc48080e5a42854764c5cb78 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:41:21 +0200 Subject: [PATCH 15/20] ci: cache docker layers and the macOS decoder, stop releases clobbering :latest --- .github/workflows/build-builders.yml | 6 ++++ .github/workflows/release.yml | 45 +++++++++++++++++++--------- 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/.github/workflows/build-builders.yml b/.github/workflows/build-builders.yml index d39f4e8..11576b9 100644 --- a/.github/workflows/build-builders.yml +++ b/.github/workflows/build-builders.yml @@ -30,6 +30,8 @@ jobs: context: ./packaging/appimage push: true tags: ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-appimage:latest + cache-from: type=gha,scope=builder-appimage + cache-to: type=gha,mode=max,scope=builder-appimage build-windows-builder: runs-on: ubuntu-latest @@ -52,6 +54,8 @@ jobs: context: ./packaging/windows push: true tags: ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-windows:latest + cache-from: type=gha,scope=builder-windows + cache-to: type=gha,mode=max,scope=builder-windows build-macos-builder: runs-on: ubuntu-latest @@ -74,3 +78,5 @@ jobs: context: ./packaging/macos push: true tags: ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-macos:latest + cache-from: type=gha,scope=builder-macos + cache-to: type=gha,mode=max,scope=builder-macos diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fea813e..03235e1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -49,16 +49,21 @@ jobs: with: persist-credentials: false + - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 + - uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Build and push builder image - run: | - docker build -t ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-appimage:latest ./packaging/appimage - docker push ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-appimage:latest + - uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0 + with: + context: ./packaging/appimage + push: true + tags: ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-appimage:${{ github.sha }} + cache-from: type=gha,scope=builder-appimage + cache-to: type=gha,mode=max,scope=builder-appimage build-windows-builder: needs: test @@ -72,16 +77,21 @@ jobs: with: persist-credentials: false + - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 + - uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Build and push builder image - run: | - docker build -t ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-windows:latest ./packaging/windows - docker push ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-windows:latest + - uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0 + with: + context: ./packaging/windows + push: true + tags: ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-windows:${{ github.sha }} + cache-from: type=gha,scope=builder-windows + cache-to: type=gha,mode=max,scope=builder-windows build-macos-blackbox: needs: test @@ -96,10 +106,17 @@ jobs: timeout-minutes: 20 permissions: contents: read + env: + BF_BLACKBOX_REV: f832acf9cd9dbe5ad8220de1a5f4eb4021523d72 steps: + - id: bbcache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: blackbox_decode.${{ matrix.arch_name }} + key: blackbox-decode-${{ matrix.arch_name }}-${{ env.BF_BLACKBOX_REV }} + - name: Build blackbox_decode - env: - BF_BLACKBOX_REV: f832acf9cd9dbe5ad8220de1a5f4eb4021523d72 + if: steps.bbcache.outputs.cache-hit != 'true' run: | git clone https://github.com/betaflight/blackbox-tools.git cd blackbox-tools @@ -135,11 +152,11 @@ jobs: - name: Build AppImage run: | mkdir -p dist - docker pull ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-appimage:latest + docker pull ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-appimage:${{ github.sha }} docker run --rm \ -v ${{ github.workspace }}:/src \ -v ${{ github.workspace }}/dist:/dist \ - ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-appimage:latest + ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-appimage:${{ github.sha }} - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 with: @@ -197,11 +214,11 @@ jobs: - name: Build Windows ZIP run: | mkdir -p dist - docker pull ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-windows:latest + docker pull ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-windows:${{ github.sha }} docker run --rm \ -v ${{ github.workspace }}:/src \ -v ${{ github.workspace }}/dist:/dist \ - ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-windows:latest + ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-builder-windows:${{ github.sha }} - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0 with: From 230ae305ae9a05ea2fc4f3cb492e5b45d47a7eee Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:49:34 +0200 Subject: [PATCH 16/20] ci: run unit tests in a dedicated image instead of the appimage builder --- .github/workflows/build-builders.yml | 24 +++++++++++++++++++ .github/workflows/ci.yml | 2 +- .github/workflows/release.yml | 2 +- packaging/test/Dockerfile | 35 ++++++++++++++++++++++++++++ 4 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 packaging/test/Dockerfile diff --git a/.github/workflows/build-builders.yml b/.github/workflows/build-builders.yml index 11576b9..8bbcf70 100644 --- a/.github/workflows/build-builders.yml +++ b/.github/workflows/build-builders.yml @@ -9,6 +9,30 @@ env: permissions: {} jobs: + build-test-image: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 + + - uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0 + with: + context: ./packaging/test + push: true + tags: ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-test:latest + cache-from: type=gha,scope=test-image + cache-to: type=gha,mode=max,scope=test-image + build-appimage-builder: runs-on: ubuntu-latest permissions: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 79dcfff..e29d8b7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,7 @@ jobs: contents: read packages: read container: - image: ghcr.io/${{ github.repository_owner }}/pidscope-builder-appimage:latest + image: ghcr.io/${{ github.repository_owner }}/pidscope-test:latest credentials: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 03235e1..42dadb8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,7 +24,7 @@ jobs: contents: read packages: read container: - image: ghcr.io/${{ github.repository_owner }}/pidscope-builder-appimage:latest + image: ghcr.io/${{ github.repository_owner }}/pidscope-test:latest credentials: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} diff --git a/packaging/test/Dockerfile b/packaging/test/Dockerfile new file mode 100644 index 0000000..7331fa1 --- /dev/null +++ b/packaging/test/Dockerfile @@ -0,0 +1,35 @@ +# Unit test environment for PIDscope +# docker build -t pidscope-test packaging/test/ +# docker run --rm -v $(pwd):/src -w /src pidscope-test octave --no-gui --eval "run('tests/run_tests.m')" + +FROM ubuntu:22.04 AS forge +ENV DEBIAN_FRONTEND=noninteractive + +RUN apt-get update && apt-get install -y software-properties-common && \ + add-apt-repository -y ppa:ubuntuhandbook1/octave && \ + apt-get update && \ + apt-get install -y octave octave-dev build-essential libsuitesparse-dev && \ + rm -rf /var/lib/apt/lists/* + +RUN octave --eval "\ + pkg install 'https://github.com/gnu-octave/pkg-control/releases/download/control-4.2.1/control-4.2.1.tar.gz'; \ + pkg install 'https://github.com/gnu-octave/octave-signal/releases/download/1.4.7/signal-1.4.7.tar.gz';" + + +FROM ubuntu:22.04 +ENV DEBIAN_FRONTEND=noninteractive + +RUN apt-get update && apt-get install -y software-properties-common && \ + add-apt-repository -y ppa:ubuntuhandbook1/octave && \ + apt-get update && \ + apt-get install -y octave libfftw3-3 libopenblas0 libfontconfig1 libfreetype6 && \ + apt-get purge -y software-properties-common && apt-get autoremove -y && \ + rm -rf /var/lib/apt/lists/* + +COPY --from=forge /usr/share/octave/packages /usr/share/octave/packages +COPY --from=forge /usr/lib/x86_64-linux-gnu/octave/packages /usr/lib/x86_64-linux-gnu/octave/packages +COPY --from=forge /usr/share/octave/site/api-v61/octave_packages /usr/share/octave/site/api-v61/octave_packages + +RUN octave-cli --eval "pkg load signal; pkg load control; disp(version); pkg list" + +WORKDIR /src From a4b0703e2505ab5d40a334d6dc508c813b6b6afa Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:53:12 +0200 Subject: [PATCH 17/20] Revert "ci: run unit tests in a dedicated image instead of the appimage builder" This reverts commit 230ae305ae9a05ea2fc4f3cb492e5b45d47a7eee. --- .github/workflows/build-builders.yml | 24 ------------------- .github/workflows/ci.yml | 2 +- .github/workflows/release.yml | 2 +- packaging/test/Dockerfile | 35 ---------------------------- 4 files changed, 2 insertions(+), 61 deletions(-) delete mode 100644 packaging/test/Dockerfile diff --git a/.github/workflows/build-builders.yml b/.github/workflows/build-builders.yml index 8bbcf70..11576b9 100644 --- a/.github/workflows/build-builders.yml +++ b/.github/workflows/build-builders.yml @@ -9,30 +9,6 @@ env: permissions: {} jobs: - build-test-image: - runs-on: ubuntu-latest - permissions: - contents: read - packages: write - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0 - - - uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0 - with: - registry: ${{ env.REGISTRY }} - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0 - with: - context: ./packaging/test - push: true - tags: ${{ env.REGISTRY }}/${{ github.repository_owner }}/pidscope-test:latest - cache-from: type=gha,scope=test-image - cache-to: type=gha,mode=max,scope=test-image - build-appimage-builder: runs-on: ubuntu-latest permissions: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e29d8b7..79dcfff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,7 +32,7 @@ jobs: contents: read packages: read container: - image: ghcr.io/${{ github.repository_owner }}/pidscope-test:latest + image: ghcr.io/${{ github.repository_owner }}/pidscope-builder-appimage:latest credentials: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 42dadb8..03235e1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,7 +24,7 @@ jobs: contents: read packages: read container: - image: ghcr.io/${{ github.repository_owner }}/pidscope-test:latest + image: ghcr.io/${{ github.repository_owner }}/pidscope-builder-appimage:latest credentials: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} diff --git a/packaging/test/Dockerfile b/packaging/test/Dockerfile deleted file mode 100644 index 7331fa1..0000000 --- a/packaging/test/Dockerfile +++ /dev/null @@ -1,35 +0,0 @@ -# Unit test environment for PIDscope -# docker build -t pidscope-test packaging/test/ -# docker run --rm -v $(pwd):/src -w /src pidscope-test octave --no-gui --eval "run('tests/run_tests.m')" - -FROM ubuntu:22.04 AS forge -ENV DEBIAN_FRONTEND=noninteractive - -RUN apt-get update && apt-get install -y software-properties-common && \ - add-apt-repository -y ppa:ubuntuhandbook1/octave && \ - apt-get update && \ - apt-get install -y octave octave-dev build-essential libsuitesparse-dev && \ - rm -rf /var/lib/apt/lists/* - -RUN octave --eval "\ - pkg install 'https://github.com/gnu-octave/pkg-control/releases/download/control-4.2.1/control-4.2.1.tar.gz'; \ - pkg install 'https://github.com/gnu-octave/octave-signal/releases/download/1.4.7/signal-1.4.7.tar.gz';" - - -FROM ubuntu:22.04 -ENV DEBIAN_FRONTEND=noninteractive - -RUN apt-get update && apt-get install -y software-properties-common && \ - add-apt-repository -y ppa:ubuntuhandbook1/octave && \ - apt-get update && \ - apt-get install -y octave libfftw3-3 libopenblas0 libfontconfig1 libfreetype6 && \ - apt-get purge -y software-properties-common && apt-get autoremove -y && \ - rm -rf /var/lib/apt/lists/* - -COPY --from=forge /usr/share/octave/packages /usr/share/octave/packages -COPY --from=forge /usr/lib/x86_64-linux-gnu/octave/packages /usr/lib/x86_64-linux-gnu/octave/packages -COPY --from=forge /usr/share/octave/site/api-v61/octave_packages /usr/share/octave/site/api-v61/octave_packages - -RUN octave-cli --eval "pkg load signal; pkg load control; disp(version); pkg list" - -WORKDIR /src From e3985098f284f84b36979df5e9eee1434bfb3e76 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:56:46 +0200 Subject: [PATCH 18/20] fix(chirp): take the feedforward path from the log instead of modelling it --- src/plot/PSplotBode.m | 6 ++++ src/plot/PSrunChirpAnalysis.m | 8 ++++- tests/test_PSpredictClosedLoop.m | 54 ++++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 1 deletion(-) diff --git a/src/plot/PSplotBode.m b/src/plot/PSplotBode.m index 4cea026..e2ab1fd 100644 --- a/src/plot/PSplotBode.m +++ b/src/plot/PSplotBode.m @@ -166,12 +166,14 @@ function PSplotBode(freq, G_track, G_plant, C, stepData, titleStr, pred) hSl = []; hLbl = []; gNames = {'P', 'I', 'D', 'FF'}; g0 = [0 0 0 0]; +useMeasuredF = false; if hasPred hPredInfo = text(0.05, 0.45, {''}, 'Parent', ax5, 'Color', th.bodePredicted, ... 'FontSize', fontsz, 'FontWeight', 'bold', 'VerticalAlignment', 'top', ... 'Units', 'normalized'); g0 = [pred.gains.P pred.gains.I pred.gains.D pred.gains.F]; + useMeasuredF = isfield(pred, 'Fref') && ~isempty(pred.Fref) && g0(4) > 0; buildPanel(); redraw(); PSstyleControls(fig, th); @@ -222,7 +224,11 @@ function redraw() end g = struct('P', v(1), 'I', v(2), 'D', v(3), 'F', v(4)); + if isfield(pred.gains, 'axis'), g.axis = pred.gains.axis; end [A, D, F] = PSbuildController(g, pred.fp, pred.FsPid, freq); + if useMeasuredF + F = pred.Fref * (v(4) / g0(4)); + end [Tp, Lp] = PSpredictClosedLoop(G_plant, A, D, F); set(hPredMag, 'YData', 20*log10(abs(Tp(predMask)) + 1e-12)); diff --git a/src/plot/PSrunChirpAnalysis.m b/src/plot/PSrunChirpAnalysis.m index b6b5e89..588bde6 100644 --- a/src/plot/PSrunChirpAnalysis.m +++ b/src/plot/PSrunChirpAnalysis.m @@ -56,6 +56,7 @@ function PSrunChirpAnalysis(T, setupInfo, debugIdx, Fs, tIND, axisIdx) axisSumPI_w = P(i0:i1) + I(i0:i1); axisSum_filt = PSrotFiltFilt(axisSum_w, sinarg_w, Fs); + axisF_filt = PSrotFiltFilt(F(i0:i1), sinarg_w, Fs); hasAxisSum = true; end @@ -64,10 +65,14 @@ function PSrunChirpAnalysis(T, setupInfo, debugIdx, Fs, tIND, axisIdx) % estimate plant if PID terms available G_plant = []; +G_ff = []; if hasAxisSum [G_uw, ~, ~] = PSestimateFreqResponse(sp_filt, axisSum_filt, Fs); % P = T / Guw (transfer function from controller output to gyro) G_plant = G_track ./ (G_uw + 1e-12); + if any(F(i0:i1) ~= 0) + [G_ff, ~, ~] = PSestimateFreqResponse(sp_filt, axisF_filt, Fs); + end end % step response from tracking TF @@ -85,7 +90,8 @@ function PSrunChirpAnalysis(T, setupInfo, debugIdx, Fs, tIND, axisIdx) fp = PSparseFilterParams(setupInfo); FsPid = fp.pid_rate_hz; if FsPid <= 0, FsPid = Fs; end - pred = struct('gains', PSparsePIDGains(setupInfo, axisIdx), 'fp', fp, 'FsPid', FsPid); + pred = struct('gains', PSparsePIDGains(setupInfo, axisIdx), 'fp', fp, ... + 'FsPid', FsPid, 'Fref', G_ff); end % plot diff --git a/tests/test_PSpredictClosedLoop.m b/tests/test_PSpredictClosedLoop.m index 1b83d3c..b97973b 100644 --- a/tests/test_PSpredictClosedLoop.m +++ b/tests/test_PSpredictClosedLoop.m @@ -115,3 +115,57 @@ %! [t2, s2] = PSstepFromFRD(freq, T2, 300); %! rise = @(t, s) t(find(s > 0.63, 1)); %! assert(rise(t2, s2) < rise(t1, s1), 'more P must reach 63 %% sooner'); + +%!test +%! % The firmware builds feedforward from the RX-rate setpoint delta and then +%! % smooths it (rc.c:439,463,505,510) - none of which PSbuildController models. +%! % So the F path is taken from the log instead: axisF against the logged +%! % setpoint is the same measured-FRF trick the plant already uses. This loop +%! % carries a PT3 on the F path that the model knows nothing about; predicting +%! % with the modelled F must miss, predicting with the measured F must not. +%! Fs = 2000; Ts = 1/Fs; N = 60000; +%! g = struct('P', 45, 'I', 60, 'D', 20, 'F', 90); +%! fp = struct('dterm_lpf1_type', 0, 'dterm_lpf1_hz', 80, ... +%! 'dterm_lpf2_type', 0, 'dterm_lpf2_hz', 0, ... +%! 'dterm_notch_hz', 0, 'dterm_notch_cut', 0); +%! Kp = 45*0.032029; Ki = 60*0.244381; Kd = 20*0.000529; Kf = 90*0.013754*0.01; +%! pt1k = @(fc) (1/Fs) / (1/(2*pi*fc) + 1/Fs); +%! kPlant = pt1k(60 * 1.553773974); +%! kDterm = pt1k(80); +%! kFF = pt1k(25 * 1.961459177); % pt3 at 25 Hz on the feedforward +%! gPlant = 0.5; +%! randn('state', 11); +%! [br, ar] = PSbfFilters('pt2', 250, Fs); +%! r = filter(br, ar, randn(N, 1)); r = 40 * r / std(r); +%! y = zeros(N, 1); u = zeros(N, 1); aF = zeros(N, 1); +%! s1 = 0; s2 = 0; sd = 0; f1 = 0; f2 = 0; f3 = 0; +%! Iacc = 0; sdPrev = 0; rPrev = 0; yNext = 0; +%! for k = 1:N +%! y(k) = yNext; +%! ek = r(k) - y(k); +%! Iacc = Iacc + Ki*Ts*ek; +%! sd = sd + kDterm*(y(k) - sd); +%! uD = Kd*(sd - sdPrev)/Ts; sdPrev = sd; +%! uFraw = Kf*(r(k) - rPrev)/Ts; rPrev = r(k); +%! f1 = f1 + kFF*(uFraw - f1); +%! f2 = f2 + kFF*(f1 - f2); +%! f3 = f3 + kFF*(f2 - f3); +%! aF(k) = f3; +%! u(k) = Kp*ek + Iacc - uD + aF(k); +%! s1 = s1 + kPlant*(gPlant*u(k) - s1); +%! s2 = s2 + kPlant*(s1 - s2); +%! yNext = s2; +%! end +%! assert(all(isfinite(y)) && max(abs(y)) < 1e6, 'simulated loop must stay stable'); +%! [G_track, ~, freq] = PSestimateFreqResponse(r, y, Fs); +%! [G_uw, ~, ~] = PSestimateFreqResponse(r, u, Fs); +%! [G_ff, ~, ~] = PSestimateFreqResponse(r, aF, Fs); +%! G_plant = G_track ./ (G_uw + 1e-12); +%! [A, D, Fmod] = PSbuildController(g, fp, Fs, freq); +%! Tmod = PSpredictClosedLoop(G_plant, A, D, Fmod); +%! Tmea = PSpredictClosedLoop(G_plant, A, D, G_ff); +%! band = freq > 10 & freq < 250; +%! eMea = max(abs(Tmea(band) - G_track(band)) ./ abs(G_track(band))); +%! eMod = max(abs(Tmod(band) - G_track(band)) ./ abs(G_track(band))); +%! assert(eMea < 0.01, 'the measured F path must reproduce the loop'); +%! assert(eMod > 0.05, 'the modelled F path must visibly miss, or this proves nothing'); From c5d37b735a16a8309703c0d36e02fda4a8baf335 Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 14:58:53 +0200 Subject: [PATCH 19/20] fix(filter-sim): hide the notch column with Show Both and end the step axes on the window --- src/plot/PSfilterSim.m | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/plot/PSfilterSim.m b/src/plot/PSfilterSim.m index 7d8e32b..fddef2c 100644 --- a/src/plot/PSfilterSim.m +++ b/src/plot/PSfilterSim.m @@ -300,17 +300,17 @@ function applyLayout() end if sBoth - set(axNmag, 'Position', offscr); - set(axNdelay, 'Position', offscr); - set(axNphase, 'Position', offscr); - set(axNstep, 'Position', offscr); + set(axNmag, 'Position', offscr, 'Visible', 'off'); + set(axNdelay, 'Position', offscr, 'Visible', 'off'); + set(axNphase, 'Position', offscr, 'Visible', 'off'); + set(axNstep, 'Position', offscr, 'Visible', 'off'); set(hTitleN, 'Visible', 'off'); set(axBarN, 'Position', offscr); set(axBarL, 'Position', [plotL barY plotR-plotL barH]); else - set(axNmag, 'Position', [colL(2) rB1 colW rH]); - set(axNdelay, 'Position', [colL(2) rB2 colW rH]); - set(axNphase, 'Position', [colL(2) rB3 colW rH]); + set(axNmag, 'Position', [colL(2) rB1 colW rH], 'Visible', 'on'); + set(axNdelay, 'Position', [colL(2) rB2 colW rH], 'Visible', 'on'); + set(axNphase, 'Position', [colL(2) rB3 colW rH], 'Visible', 'on'); if sStep set(axNstep, 'Position', [colL(2) rB4 colW rH], 'Visible', 'on'); else @@ -742,9 +742,9 @@ function doUpdate() end hideRest(AX_LSTP, li); if row4mode == 1 - set(axLstep, 'XLim', [tSigL(1) tSigL(end)], 'YLim', [-0.05 1.15]); + set(axLstep, 'XLim', [0 lpfStepMs], 'YLim', [-0.05 1.15]); else - set(axLstep, 'XLim', [tSigL(1) tSigL(end)]); + set(axLstep, 'XLim', [0 lpfStepMs]); end end xlabel(axLstep, r4labelL, 'Color', thm.textPrimary); @@ -885,9 +885,9 @@ function doUpdate() end hideRest(AX_NSTP, li); if row4mode == 1 - set(axNstep, 'XLim', [tSigN(1) tSigN(end)], 'YLim', [0.8 1.2]); + set(axNstep, 'XLim', [0 notchStepMs], 'YLim', [0.8 1.2]); else - set(axNstep, 'XLim', [tSigN(1) tSigN(end)]); + set(axNstep, 'XLim', [0 notchStepMs]); end end xlabel(axNstep, r4labelN, 'Color', thm.textPrimary); From a649a2556231f23a008b53dd802596b689f5d94d Mon Sep 17 00:00:00 2001 From: Grzegorz Sterniczuk Date: Sat, 19 Sep 2026 15:13:07 +0200 Subject: [PATCH 20/20] fix(ui): keep the font size usable when the toolkit reports no screen --- src/util/PStheme.m | 11 ++++++++--- tests/test_PStheme.m | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 tests/test_PStheme.m diff --git a/src/util/PStheme.m b/src/util/PStheme.m index 2691c04..461038c 100644 --- a/src/util/PStheme.m +++ b/src/util/PStheme.m @@ -1,4 +1,4 @@ -function th = PStheme() +function th = PStheme(screenHeight) %% PStheme - central UI theme for PIDscope (dark) % figure & panel @@ -51,12 +51,17 @@ th.overlayRPM = [.6 .9 .6]; % RPM est - light green % font size - single source of truth -screensz = get(0, 'ScreenSize'); -th.fontsz = round(screensz(4) * .011); +if nargin < 1 || isempty(screenHeight) + screensz = get(0, 'ScreenSize'); + screenHeight = screensz(4); +end +th.fontsz = round(screenHeight * .011); % Octave Qt renders fonts bigger than MATLAB if exist('OCTAVE_VERSION', 'builtin') th.fontsz = round(th.fontsz * 0.85); end +% a toolkit with no display reports a 1x1 screen, and uipanel refuses FontSize 0 +th.fontsz = max(th.fontsz, 8); % period marker (Step Response) th.periodMarker = [.95 .20 .20]; diff --git a/tests/test_PStheme.m b/tests/test_PStheme.m new file mode 100644 index 0000000..471e4d8 --- /dev/null +++ b/tests/test_PStheme.m @@ -0,0 +1,22 @@ +% test_PStheme.m - tests for the theme constants + +%!test +%! % A toolkit with no display reports ScreenSize [1 1 1 1], and round(1*.011) +%! % is zero. uipanel refuses any FontSize <= 0, so the control panel fails to +%! % build and PIDscope dies at startup. +%! th = PStheme(1); +%! assert(th.fontsz >= 8, 'font size must stay usable on a degenerate display'); +%! th = PStheme(0); +%! assert(th.fontsz >= 8); + +%!test +%! % and it still tracks screen height where there is one +%! small = PStheme(1080); +%! big = PStheme(2160); +%! assert(big.fontsz > small.fontsz, 'font size must scale with screen height'); +%! assert(small.fontsz >= 8 && big.fontsz <= 40); + +%!test +%! % no argument still reads the screen +%! th = PStheme(); +%! assert(th.fontsz >= 8);