From 9d16b9d120c07d44cefc200e8702303da185a31c Mon Sep 17 00:00:00 2001 From: Muhep Atasoy Date: Wed, 11 Nov 2026 21:28:12 +0300 Subject: [PATCH] fix(ddc): space commands and verify writes so quick changes aren't dropped Some monitors silently ignore a DDC command that follows the previous one too closely, so a quickly changed brightness or volume stopped short of the target value. The worker now keeps a pause between commands, reads brightness and volume back once writes stop, resends a dropped write and lengthens the pause for that monitor. The learned pause is saved per monitor as commandSpacingMs. Tested on a Samsung S34C65xU: quick slider changes now reach the target. --- docs/TROUBLESHOOTING.md | 4 + src/DisplayKnob.App/Composition.cs | 13 + src/DisplayKnob.Core/Ddc/DdcWorker.cs | 259 +++++++++++++++++- src/DisplayKnob.Core/Ddc/DdcWorkerOptions.cs | 40 ++- .../Displays/MonitorRegistry.cs | 39 ++- .../Settings/MonitorSettings.cs | 7 + .../Ddc/DdcWorkerTests.cs | 182 ++++++++++++ .../Displays/MonitorRegistryTests.cs | 42 +++ .../Fakes/FakeMonitorController.cs | 22 +- .../Fakes/ManualTimeProvider.cs | 148 ++++++++++ .../Settings/JsonSettingsStoreTests.cs | 22 ++ 11 files changed, 764 insertions(+), 14 deletions(-) create mode 100644 tests/DisplayKnob.Core.Tests/Fakes/ManualTimeProvider.cs diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index b0533f9..3e2d37c 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -25,6 +25,10 @@ Some docks, adapters and DisplayLink-style outputs don't support DDC/CI. Check t - Many monitors only use part of the 0–100 range. The per-monitor *Maximum volume* squeezes the scale below a limit, and *Volume curve* "Logarithmic" takes finer steps at low volume. Try it if the lowest levels are too loud or the top ones do nothing. - If another computer or the monitor's own buttons left the volume above your limit, the next volume key press brings it back down to the limit. +## Brightness or volume stops short of the value I dragged to + +Some monitors silently ignore a DDC command that comes too soon after the previous one. DisplayKnob keeps a short pause between commands, reads the value back once you stop, and if the last write was lost it sends it again and lengthens the pause for that monitor. What it learned is saved per monitor as `commandSpacingMs` in `settings.json` (delete the entry to learn again). If it still happens, attach the log: it lists every DDC command with its duration. + ## The keyboard shortcuts don't work - Use the **left** Alt key. The right one is AltGr on many keyboards and never triggers a shortcut, so it can't swallow the characters you type with it. diff --git a/src/DisplayKnob.App/Composition.cs b/src/DisplayKnob.App/Composition.cs index 4819e0c..32f29bd 100644 --- a/src/DisplayKnob.App/Composition.cs +++ b/src/DisplayKnob.App/Composition.cs @@ -4,6 +4,7 @@ using DisplayKnob.App.ViewModels; using DisplayKnob.App.Views; using DisplayKnob.Core; +using DisplayKnob.Core.Ddc; using Microsoft.Extensions.DependencyInjection; using Microsoft.UI.Dispatching; @@ -20,6 +21,7 @@ public static ServiceProvider Build(Serilog.ILogger logger) services.AddSingleton(logger); services.AddDisplayKnobCore(); + OverrideDdcSpacingIfRequested(services); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -40,4 +42,15 @@ public static ServiceProvider Build(Serilog.ILogger logger) ValidateScopes = true, }); } + + // Debug builds only: DISPLAYKNOB_DDC_SPACING_MS= starts every monitor with that pause between DDC commands, + // so "a too short pause is noticed and widened" can be tried on real hardware. + [System.Diagnostics.Conditional("DEBUG")] + private static void OverrideDdcSpacingIfRequested(IServiceCollection services) + { + if (int.TryParse(Environment.GetEnvironmentVariable("DISPLAYKNOB_DDC_SPACING_MS"), System.Globalization.CultureInfo.InvariantCulture, out var ms) && ms >= 0) + { + services.AddSingleton(DdcWorkerOptions.Default with { CommandSpacing = TimeSpan.FromMilliseconds(ms) }); + } + } } diff --git a/src/DisplayKnob.Core/Ddc/DdcWorker.cs b/src/DisplayKnob.Core/Ddc/DdcWorker.cs index 5d636eb..8f3ca5e 100644 --- a/src/DisplayKnob.Core/Ddc/DdcWorker.cs +++ b/src/DisplayKnob.Core/Ddc/DdcWorker.cs @@ -12,6 +12,8 @@ namespace DisplayKnob.Core.Ddc; /// observes every write requested before it. /// Failed operations are retried with linear backoff; failures after the last attempt are /// logged and reported as /, never thrown. +/// Commands are spaced (): a monitor drops a command that +/// follows the previous one too closely, and the call still reports success. /// public sealed class DdcWorker : IAsyncDisposable { @@ -27,11 +29,27 @@ public sealed class DdcWorker : IAsyncDisposable private readonly CancellationTokenSource _stop = new(); private readonly Task _loop; private bool _failing; // Only touched by the loop. + private long? _lastCommandEnd; // Only touched by the loop: when the previous DDC command finished. + private long _spacingTicks; // Written by the loop only; read from anywhere through CommandSpacing. + + // Write verification (see DdcWorkerOptions.VerifiedCodes). All of it is only touched by the loop. + private readonly Dictionary _lastKnown = []; // Last value seen or written per verified code. + private readonly Dictionary _toVerify = []; + private readonly Dictionary _oddMismatches = []; + private readonly HashSet _notVerified = []; /// /// Creates the worker and starts its loop. The worker takes ownership of . /// - public DdcWorker(IMonitorController monitor, TimeProvider timeProvider, DdcWorkerOptions options, ILogger logger) + /// The monitor to talk to. + /// Clock for the spacing, retries and verification. + /// Retry, pacing and verification policy. + /// Logger. + /// + /// The command spacing learned for this monitor earlier, if any. It is used when it is longer than + /// . + /// + public DdcWorker(IMonitorController monitor, TimeProvider timeProvider, DdcWorkerOptions options, ILogger logger, TimeSpan? initialSpacing = null) { ArgumentNullException.ThrowIfNull(monitor); ArgumentNullException.ThrowIfNull(timeProvider); @@ -43,9 +61,15 @@ public DdcWorker(IMonitorController monitor, TimeProvider timeProvider, DdcWorke _timeProvider = timeProvider; _options = options; _logger = logger.ForContext(); + _spacingTicks = (initialSpacing is { } learned && learned > options.CommandSpacing ? learned : options.CommandSpacing).Ticks; _loop = Task.Run(() => RunAsync(_stop.Token)); } + /// What the worker expects a verified code to read after its last write. + /// The value last written. + /// The value the monitor held before it, if known: what it still reports if the write was dropped. + private readonly record struct WriteCheck(uint Expected, uint? Previous); + private interface IReadItem { string Operation { get; } @@ -65,6 +89,15 @@ private interface IReadItem /// public event EventHandler? WriteFailed; + /// + /// Raised on the worker's loop after it learned that this monitor needs a longer pause between commands; the + /// argument is the new spacing. Callers persist it so the next start doesn't have to find out again. + /// + public event EventHandler? CommandSpacingChanged; + + /// The pause currently kept between DDC commands. + public TimeSpan CommandSpacing => TimeSpan.FromTicks(Volatile.Read(ref _spacingTicks)); + /// Stable identity of the monitor. public MonitorIdentity Identity => _monitor.Identity; @@ -95,7 +128,20 @@ public void WriteVcp(byte code, uint value) public Task ReadVcpAsync(byte code, CancellationToken cancellationToken = default) => EnqueueRead( $"read VCP 0x{code:X2}", - m => m.TryGetVcp(code, out var value) ? (true, value) : (false, null), + m => + { + if (!m.TryGetVcp(code, out var value)) + { + return (false, null); + } + + if (Verifies(code)) + { + _lastKnown[code] = value.Current; // Runs on the loop, like every other use of the dictionary. + } + + return (true, value); + }, cancellationToken); /// @@ -143,10 +189,33 @@ private async Task RunAsync(CancellationToken stopToken) { try { + // One wait task is kept across iterations, so a signal that arrives while the loop is verifying isn't lost. + var signal = _signal.WaitAsync(stopToken); while (true) { - await _signal.WaitAsync(stopToken).ConfigureAwait(false); - await DrainAsync(stopToken).ConfigureAwait(false); + if (_toVerify.Count == 0) + { + await signal.ConfigureAwait(false); + signal = _signal.WaitAsync(stopToken); + await DrainAsync(stopToken).ConfigureAwait(false); + continue; + } + + // Writes have just been sent. Once nothing new has come in for a while, check that the last one stuck. + using var quietCts = CancellationTokenSource.CreateLinkedTokenSource(stopToken); + var quiet = Task.Delay(_options.VerifyDelay, _timeProvider, quietCts.Token); + if (await Task.WhenAny(signal, quiet).ConfigureAwait(false) == signal) + { + await quietCts.CancelAsync().ConfigureAwait(false); // The wait for quiet starts over after the new work. + await signal.ConfigureAwait(false); + signal = _signal.WaitAsync(stopToken); + await DrainAsync(stopToken).ConfigureAwait(false); + } + else + { + await quiet.ConfigureAwait(false); + await VerifyAsync(stopToken).ConfigureAwait(false); + } } } catch (OperationCanceledException) when (stopToken.IsCancellationRequested) @@ -188,7 +257,11 @@ private async Task DrainAsync(CancellationToken stopToken) foreach (var (code, value) in writes) { stopToken.ThrowIfCancellationRequested(); - if (!await ExecuteWithRetryAsync($"write VCP 0x{code:X2}={value}", m => m.TrySetVcp(code, value), stopToken).ConfigureAwait(false)) + if (await ExecuteWithRetryAsync($"write VCP 0x{code:X2}={value}", m => m.TrySetVcp(code, value), stopToken).ConfigureAwait(false)) + { + TrackWrite(code, value); + } + else { WriteFailed?.Invoke(this, new VcpWriteFailedEventArgs(code, value)); } @@ -223,7 +296,17 @@ private async Task ExecuteWithRetryAsync(string operation, Func ExecuteWithRetryAsync(string operation, Func TimeSpan.Zero) + { + await Task.Delay(wait, _timeProvider, stopToken).ConfigureAwait(false); + } + } + + private bool Verifies(byte code) => + _options.VerifyDelay > TimeSpan.Zero && _options.VerifiedCodes is { } codes && codes.Contains(code); + + // A write went out: remember what the monitor should now report, and what it reported before. + private void TrackWrite(byte code, uint value) + { + if (!Verifies(code) || _notVerified.Contains(code)) + { + return; + } + + // If the previous write of this series was dropped, the monitor still reports the one before it. + uint? previous = _toVerify.TryGetValue(code, out var pending) ? pending.Expected + : _lastKnown.TryGetValue(code, out var known) ? known + : null; + _toVerify[code] = new WriteCheck(value, previous); + _lastKnown[code] = value; + } + + // The writes have stopped: read back what was written last. Runs on the loop. + private async Task VerifyAsync(CancellationToken stopToken) + { + foreach (var (code, check) in _toVerify.ToArray()) + { + lock (_lock) + { + if (_pendingWrites.ContainsKey(code)) + { + continue; // A newer write is waiting; that one will be checked instead. + } + } + + _toVerify.Remove(code); + await VerifyCodeAsync(code, check, stopToken).ConfigureAwait(false); + + lock (_lock) + { + if (_pendingWrites.Count > 0 || _pendingReads.Count > 0) + { + return; // Real work came in; the rest is checked the next time it's quiet. + } + } + } + } + + private async Task VerifyCodeAsync(byte code, WriteCheck check, CancellationToken stopToken) + { + var actual = await ReadBackAsync(code, stopToken).ConfigureAwait(false); + if (actual is null) + { + return; // The monitor isn't answering; the callers find out through their own reads and writes. + } + + if (actual == check.Expected) + { + _oddMismatches.Remove(code); + return; + } + + // A dropped write leaves the monitor at the value before it. Anything else (a monitor that rounds or clamps, + // or someone pressing its buttons) says nothing about timing, so the spacing is left alone. + if (check.Previous is { } previous && actual != previous) + { + var odd = _oddMismatches.GetValueOrDefault(code) + 1; + _oddMismatches[code] = odd; + if (odd >= 2) + { + _notVerified.Add(code); + _logger.Debug("{Monitor} reports other values than written for VCP 0x{Code:X2}; not verifying it any more", DisplayName, code); + } + + return; + } + + var startSpacing = CommandSpacing; + for (var attempt = 1; attempt <= MaxResends; attempt++) + { + GrowSpacing(); + if (!await ExecuteWithRetryAsync($"re-send VCP 0x{code:X2}={check.Expected}", m => m.TrySetVcp(code, check.Expected), stopToken).ConfigureAwait(false)) + { + SetSpacing(startSpacing); + return; + } + + actual = await ReadBackAsync(code, stopToken).ConfigureAwait(false); + if (actual == check.Expected) + { + _oddMismatches.Remove(code); + _lastKnown[code] = check.Expected; + _logger.Information( + "{Monitor} ignored a DDC write sent {Start} ms after the previous command; keeping {Spacing} ms between commands", + DisplayName, + startSpacing.TotalMilliseconds, + CommandSpacing.TotalMilliseconds); + CommandSpacingChanged?.Invoke(this, CommandSpacing); + return; + } + + if (actual is null) + { + SetSpacing(startSpacing); + return; + } + } + + // A longer pause didn't help, so the pause isn't the problem: undo it and stop checking this code. + SetSpacing(startSpacing); + _notVerified.Add(code); + _logger.Warning("{Monitor} doesn't apply writes to VCP 0x{Code:X2} even after longer pauses", DisplayName, code); + } + + private const int MaxResends = 3; + + private async Task ReadBackAsync(byte code, CancellationToken stopToken) + { + uint? value = null; + var ok = await ExecuteWithRetryAsync( + $"verify VCP 0x{code:X2}", + m => + { + if (!m.TryGetVcp(code, out var read)) + { + return false; + } + + value = read.Current; + return true; + }, + stopToken).ConfigureAwait(false); + + if (ok && value is { } current) + { + _lastKnown[code] = current; + } + + return ok ? value : null; + } + + // Half again, at least 40 ms more, up to the limit: 80, 120, 180, 270, 400 ms. + private void GrowSpacing() + { + var current = CommandSpacing; + var next = current + TimeSpan.FromTicks(Math.Max(TimeSpan.FromMilliseconds(40).Ticks, current.Ticks / 2)); + SetSpacing(next < _options.MaxCommandSpacing ? next : TimeSpan.FromTicks(Math.Max(current.Ticks, _options.MaxCommandSpacing.Ticks))); + } + + private void SetSpacing(TimeSpan spacing) => Volatile.Write(ref _spacingTicks, spacing.Ticks); + private void CancelPendingReads() { IReadItem[] reads; diff --git a/src/DisplayKnob.Core/Ddc/DdcWorkerOptions.cs b/src/DisplayKnob.Core/Ddc/DdcWorkerOptions.cs index a96f7bc..3523521 100644 --- a/src/DisplayKnob.Core/Ddc/DdcWorkerOptions.cs +++ b/src/DisplayKnob.Core/Ddc/DdcWorkerOptions.cs @@ -1,12 +1,44 @@ namespace DisplayKnob.Core.Ddc; /// -/// Retry policy for . +/// Retry, pacing and write-verification policy for . /// /// Total attempts per operation (first try included). /// Base delay; attempt n waits n × RetryDelay before retrying. -public sealed record DdcWorkerOptions(int MaxAttempts, TimeSpan RetryDelay) +/// +/// Minimum time between the end of one DDC command and the start of the next (zero: no pause). A monitor that is still +/// busy with a command silently ignores the next one: the call reports success and nothing happens. Measured on a +/// Samsung S34C65xU, the last write of a quick series was lost whenever it followed the previous one by less than about +/// 100 ms (call included), so a dragged brightness slider stopped at an intermediate value instead of the one the +/// user chose. This is where each monitor starts; see for how it adapts. +/// +/// +/// How long after the last write the worker reads a verified value back (zero: no verification). Long enough not to +/// get in the way of a key held down or a slider being dragged. +/// +/// The longest spacing the worker will learn (zero: it never grows). +/// +/// VCP codes whose writes are read back once the writes stop. A monitor can't tell us how long it needs between +/// commands, so the worker finds out by checking whether the last value stuck: if the monitor still reports the +/// value before it, the write was dropped; the worker sends it again and widens the spacing for that monitor. +/// +public sealed record DdcWorkerOptions( + int MaxAttempts, + TimeSpan RetryDelay, + TimeSpan CommandSpacing = default, + TimeSpan VerifyDelay = default, + TimeSpan MaxCommandSpacing = default, + IReadOnlySet? VerifiedCodes = null) { - /// 3 attempts, 50 ms then 100 ms between them. - public static DdcWorkerOptions Default { get; } = new(3, TimeSpan.FromMilliseconds(50)); + /// + /// 3 attempts (50 ms, then 100 ms between them), 80 ms between commands growing to at most 400 ms, and brightness + /// and volume read back 150 ms after their last write. + /// + public static DdcWorkerOptions Default { get; } = new( + 3, + TimeSpan.FromMilliseconds(50), + TimeSpan.FromMilliseconds(80), + TimeSpan.FromMilliseconds(150), + TimeSpan.FromMilliseconds(400), + new HashSet { VcpCodes.Brightness, VcpCodes.AudioVolume }); } diff --git a/src/DisplayKnob.Core/Displays/MonitorRegistry.cs b/src/DisplayKnob.Core/Displays/MonitorRegistry.cs index 31f2642..ed9c4cc 100644 --- a/src/DisplayKnob.Core/Displays/MonitorRegistry.cs +++ b/src/DisplayKnob.Core/Displays/MonitorRegistry.cs @@ -1,4 +1,5 @@ using DisplayKnob.Core.Ddc; +using DisplayKnob.Core.Settings; using Serilog; namespace DisplayKnob.Core.Displays; @@ -15,13 +16,22 @@ public sealed class MonitorRegistry : IAsyncDisposable private readonly IMonitorEnumerator _enumerator; private readonly TimeProvider _timeProvider; private readonly DdcWorkerOptions _workerOptions; + private readonly ISettingsStore? _settings; private readonly ILogger _logger; private readonly SemaphoreSlim _refreshLock = new(1, 1); private IReadOnlyList _monitors = []; private bool _disposed; /// Creates an empty registry; call to populate it. - public MonitorRegistry(IMonitorEnumerator enumerator, TimeProvider timeProvider, DdcWorkerOptions workerOptions, ILogger logger) + /// Finds the monitors. + /// Clock for the DDC workers. + /// Retry, pacing and verification policy for the DDC workers. + /// Logger. + /// + /// When given, the command spacing each monitor needs is read from it and written back when a worker learns + /// a longer one. + /// + public MonitorRegistry(IMonitorEnumerator enumerator, TimeProvider timeProvider, DdcWorkerOptions workerOptions, ILogger logger, ISettingsStore? settings = null) { ArgumentNullException.ThrowIfNull(enumerator); ArgumentNullException.ThrowIfNull(timeProvider); @@ -31,6 +41,7 @@ public MonitorRegistry(IMonitorEnumerator enumerator, TimeProvider timeProvider, _enumerator = enumerator; _timeProvider = timeProvider; _workerOptions = workerOptions; + _settings = settings; _logger = logger.ForContext(); } @@ -60,7 +71,7 @@ public async Task RefreshAsync(CancellationToken cancellationToken = default) _logger.Warning("{Count} monitors share the identity {MonitorId}; per-monitor settings will collide", duplicate.Count(), duplicate.Key); } - Volatile.Write(ref _monitors, [.. controllers.Select(c => new DdcWorker(c, _timeProvider, _workerOptions, _logger))]); + Volatile.Write(ref _monitors, [.. controllers.Select(CreateWorker)]); _logger.Information("Found {Count} monitor(s)", controllers.Count); } finally @@ -91,6 +102,30 @@ public async ValueTask DisposeAsync() } } + private DdcWorker CreateWorker(IMonitorController controller) + { + var key = controller.Identity.Key; + var settings = _settings; + var learned = settings?.Current.ForMonitor(key).CommandSpacingMs; + var worker = new DdcWorker(controller, _timeProvider, _workerOptions, _logger, learned is > 0 ? TimeSpan.FromMilliseconds(learned.Value) : null); + + if (settings is not null) + { + // Raised on the worker's loop. Saving raises the settings' Changed event, whose handlers shouldn't run + // inside the DDC loop, so hand it to the thread pool. + worker.CommandSpacingChanged += (_, spacing) => ThreadPool.QueueUserWorkItem(_ => + settings.Update(s => s with + { + Monitors = new Dictionary(s.Monitors) + { + [key] = s.ForMonitor(key) with { CommandSpacingMs = (int)Math.Round(spacing.TotalMilliseconds) }, + }, + })); + } + + return worker; + } + private async Task DisposeMonitorsAsync() { var old = Volatile.Read(ref _monitors); diff --git a/src/DisplayKnob.Core/Settings/MonitorSettings.cs b/src/DisplayKnob.Core/Settings/MonitorSettings.cs index 7c5d39c..75097ab 100644 --- a/src/DisplayKnob.Core/Settings/MonitorSettings.cs +++ b/src/DisplayKnob.Core/Settings/MonitorSettings.cs @@ -36,6 +36,13 @@ public sealed record MonitorSettings /// public int MaxVolumePercent { get; set; } = 100; + /// + /// The pause, in milliseconds, this monitor needs between DDC commands, as learned by DisplayKnob: a monitor + /// ignores a command that comes too soon after the previous one. means the default. + /// Written by the app; delete it to learn again. + /// + public int? CommandSpacingMs { get; set; } + /// How the 0–100 scale maps onto the usable range. Monitors respond very differently at the low end. public VolumeCurve VolumeCurve { get; set; } = VolumeCurve.Linear; diff --git a/tests/DisplayKnob.Core.Tests/Ddc/DdcWorkerTests.cs b/tests/DisplayKnob.Core.Tests/Ddc/DdcWorkerTests.cs index 0c280b9..6fde9dd 100644 --- a/tests/DisplayKnob.Core.Tests/Ddc/DdcWorkerTests.cs +++ b/tests/DisplayKnob.Core.Tests/Ddc/DdcWorkerTests.cs @@ -1,5 +1,7 @@ +using System.Collections.Concurrent; using DisplayKnob.Core.Ddc; using DisplayKnob.Core.Tests.Fakes; +using Microsoft.Extensions.Time.Testing; using Serilog.Core; namespace DisplayKnob.Core.Tests.Ddc; @@ -70,6 +72,43 @@ public async Task WriteVcp_RapidRepeats_OnlyLatestValueIsWritten() Assert.Equal([14u], volumeWrites); } + [Fact] + public async Task WriteVcp_Consecutive_WaitsForTheCommandSpacing() + { + // A monitor drops a command that follows the previous one too closely, so the worker must keep its distance. + var spacing = TimeSpan.FromMilliseconds(100); + var time = new FakeTimeProvider(); + var monitor = new FakeMonitorController(clock: time); + await using var worker = new DdcWorker(monitor, time, new DdcWorkerOptions(3, TimeSpan.Zero, spacing), Logger.None); + + worker.WriteVcp(VcpCodes.Brightness, 10); + await WaitUntilAsync(() => monitor.Writes.Count == 1); + worker.WriteVcp(VcpCodes.Brightness, 20); + time.Advance(spacing); + await WaitUntilAsync(() => monitor.Writes.Count == 2); + + var times = monitor.WriteTimes; + Assert.True(times[1] - times[0] >= spacing, $"The second write came {times[1] - times[0]} after the first."); + } + + [Fact] + public async Task ReadVcpAsync_AfterWrite_WaitsForTheCommandSpacing() + { + var spacing = TimeSpan.FromMilliseconds(100); + var time = new FakeTimeProvider(); + var monitor = new FakeMonitorController(clock: time); + monitor.SetValue(VcpCodes.Brightness, 10); + await using var worker = new DdcWorker(monitor, time, new DdcWorkerOptions(3, TimeSpan.Zero, spacing), Logger.None); + + worker.WriteVcp(VcpCodes.Brightness, 20); + await WaitUntilAsync(() => monitor.Writes.Count == 1); + var read = worker.ReadVcpAsync(VcpCodes.Brightness, Ct); + time.Advance(spacing); // Reads are commands too: the monitor needs the pause before them as well. + var value = await read.WaitAsync(s_timeout, Ct); + + Assert.Equal(20u, value?.Current); + } + [Fact] public async Task ReadVcpAsync_AfterWrite_SeesWrittenValue() { @@ -122,6 +161,149 @@ public async Task DisposeAsync_PendingRead_IsCancelled() await Assert.ThrowsAnyAsync(() => read.WaitAsync(s_timeout, Ct)); } + // --- Writes that a monitor drops, and the spacing learned from them --- + + private static readonly TimeSpan s_spacing = TimeSpan.FromMilliseconds(80); + + private static DdcWorker CreateVerifyingWorker(FakeMonitorController monitor, ManualTimeProvider time, TimeSpan? initialSpacing = null) => + new( + monitor, + time, + new DdcWorkerOptions( + MaxAttempts: 3, + RetryDelay: TimeSpan.Zero, + CommandSpacing: s_spacing, + VerifyDelay: TimeSpan.FromMilliseconds(150), + MaxCommandSpacing: TimeSpan.FromMilliseconds(400), + VerifiedCodes: new HashSet { VcpCodes.Brightness }), + Logger.None, + initialSpacing); + + [Fact] + public async Task WriteDroppedByTheMonitor_IsSentAgainAndTheSpacingGrows() + { + // The monitor needs 150 ms between commands, the worker starts with 80: the second write is lost. + var time = new ManualTimeProvider(); + var monitor = new FakeMonitorController(clock: time) { DropWritesWithin = TimeSpan.FromMilliseconds(150) }; + monitor.SetValue(VcpCodes.Brightness, 5, 50); + var learned = new ConcurrentQueue(); + await using var worker = CreateVerifyingWorker(monitor, time); + worker.CommandSpacingChanged += (_, spacing) => learned.Enqueue(spacing); + + worker.WriteVcp(VcpCodes.Brightness, 10); + await time.RunUntilAsync(() => monitor.Writes.Count == 1); + worker.WriteVcp(VcpCodes.Brightness, 20); + await time.RunUntilAsync(() => !learned.IsEmpty); + + Assert.Equal(20u, monitor.GetCurrent(VcpCodes.Brightness)); + Assert.True(worker.CommandSpacing >= TimeSpan.FromMilliseconds(150)); + Assert.Equal([worker.CommandSpacing], learned); + } + + [Fact] + public async Task MonitorThatKeepsUp_IsNotWrittenToTwiceOrSlowedDown() + { + var time = new ManualTimeProvider(); + var monitor = new FakeMonitorController(clock: time); + monitor.SetValue(VcpCodes.Brightness, 5, 50); + var learned = new ConcurrentQueue(); + await using var worker = CreateVerifyingWorker(monitor, time); + worker.CommandSpacingChanged += (_, spacing) => learned.Enqueue(spacing); + + worker.WriteVcp(VcpCodes.Brightness, 10); + await time.RunUntilAsync(() => monitor.Writes.Count == 1); + worker.WriteVcp(VcpCodes.Brightness, 20); + await time.RunUntilAsync(() => monitor.CallCount >= 3); // Two writes and the check that reads the value back. + await time.SettleAsync(); + + Assert.Equal(2, monitor.Writes.Count); + Assert.Equal(20u, monitor.GetCurrent(VcpCodes.Brightness)); + Assert.Equal(s_spacing, worker.CommandSpacing); + Assert.Empty(learned); + } + + [Fact] + public async Task MonitorThatChangesTheValue_StopsBeingChecked() + { + // The monitor stores what it was given plus one (rounding, clamping): that says nothing about timing. + var time = new ManualTimeProvider(); + var monitor = new FakeMonitorController(clock: time) { ReportedValueAfterWrite = (_, value) => value + 1 }; + monitor.SetValue(VcpCodes.Brightness, 5, 50); + await using var worker = CreateVerifyingWorker(monitor, time); + await worker.ReadVcpAsync(VcpCodes.Brightness, Ct).WaitAsync(s_timeout, Ct); // The worker now knows the value before its writes. + + worker.WriteVcp(VcpCodes.Brightness, 10); + await time.RunUntilAsync(() => monitor.CallCount >= 3); // The read, the write and its check: 11 is neither 10 nor 5. + await time.SettleAsync(); + worker.WriteVcp(VcpCodes.Brightness, 20); + await time.RunUntilAsync(() => monitor.CallCount >= 5); // The second odd answer: from now on the code isn't checked. + await time.SettleAsync(); + worker.WriteVcp(VcpCodes.Brightness, 30); + await time.RunUntilAsync(() => monitor.Writes.Count == 3); + await time.SettleAsync(); + + Assert.Equal(6, monitor.CallCount); // One read, three writes and two checks; the last write isn't checked. + Assert.Equal(3, monitor.Writes.Count); // Nothing was sent again. + Assert.Equal(s_spacing, worker.CommandSpacing); + } + + [Fact] + public async Task MonitorThatNeverAppliesTheWrite_IsGivenUpOnAndTheSpacingIsKept() + { + // No pause helps, so the pause isn't the problem: the spacing goes back to where it was and nothing is learned. + var time = new ManualTimeProvider(); + var monitor = new FakeMonitorController(clock: time); + monitor.IgnoredWriteCodes.Add(VcpCodes.Brightness); + monitor.SetValue(VcpCodes.Brightness, 5, 50); + var learned = new ConcurrentQueue(); + await using var worker = CreateVerifyingWorker(monitor, time); + worker.CommandSpacingChanged += (_, spacing) => learned.Enqueue(spacing); + + worker.WriteVcp(VcpCodes.Brightness, 10); + await time.RunUntilAsync(() => monitor.Writes.Count == 4); // The write and three sends again. + await time.SettleAsync(); + + Assert.Equal(4, monitor.Writes.Count); + Assert.Equal(s_spacing, worker.CommandSpacing); + Assert.Empty(learned); + } + + [Fact] + public async Task InitialSpacing_LongerThanTheDefault_IsUsed() + { + var time = new ManualTimeProvider(); + var monitor = new FakeMonitorController(clock: time); + await using var worker = CreateVerifyingWorker(monitor, time, initialSpacing: TimeSpan.FromMilliseconds(200)); + + worker.WriteVcp(VcpCodes.AudioVolume, 10); + await time.RunUntilAsync(() => monitor.Writes.Count == 1); + worker.WriteVcp(VcpCodes.AudioVolume, 20); + await time.RunUntilAsync(() => monitor.Writes.Count == 2); + + var times = monitor.WriteTimes; + Assert.Equal(TimeSpan.FromMilliseconds(200), times[1] - times[0]); + } + + [Fact] + public async Task InitialSpacing_ShorterThanTheDefault_IsIgnored() + { + var time = new ManualTimeProvider(); + await using var worker = CreateVerifyingWorker(new FakeMonitorController(clock: time), time, initialSpacing: TimeSpan.FromMilliseconds(20)); + + Assert.Equal(s_spacing, worker.CommandSpacing); + } + + // The worker runs on its own loop; poll for what the test is waiting on instead of sleeping a fixed time. + private static async Task WaitUntilAsync(Func condition) + { + var deadline = Environment.TickCount64 + (long)s_timeout.TotalMilliseconds; + while (!condition()) + { + Assert.True(Environment.TickCount64 < deadline, "Timed out waiting for the worker."); + await Task.Yield(); + } + } + private static DdcWorker CreateWorker(FakeMonitorController monitor) => new(monitor, TimeProvider.System, s_noDelay, Logger.None); } diff --git a/tests/DisplayKnob.Core.Tests/Displays/MonitorRegistryTests.cs b/tests/DisplayKnob.Core.Tests/Displays/MonitorRegistryTests.cs index 6602b8e..a389583 100644 --- a/tests/DisplayKnob.Core.Tests/Displays/MonitorRegistryTests.cs +++ b/tests/DisplayKnob.Core.Tests/Displays/MonitorRegistryTests.cs @@ -1,5 +1,6 @@ using DisplayKnob.Core.Ddc; using DisplayKnob.Core.Displays; +using DisplayKnob.Core.Settings; using DisplayKnob.Core.Tests.Fakes; using Serilog.Core; @@ -63,6 +64,47 @@ public async Task MonitorProbe_RunAsync_ReadsEveryMonitor() Assert.True(a.CallCount >= 4); } + [Fact] + public async Task RefreshAsync_SpacingLearnedEarlier_StartsTheWorkerWithIt() + { + var monitor = new FakeMonitorController("A"); + var settings = new InMemorySettingsStore(); + settings.Update(s => s with { Monitors = new Dictionary { [monitor.Identity.Key] = new() { CommandSpacingMs = 200 } } }); + var options = new DdcWorkerOptions(1, TimeSpan.Zero, CommandSpacing: TimeSpan.FromMilliseconds(80)); + await using var registry = new MonitorRegistry(new FakeMonitorEnumerator(() => [monitor]), TimeProvider.System, options, Logger.None, settings); + + await registry.RefreshAsync(Ct); + + Assert.Equal(TimeSpan.FromMilliseconds(200), registry.Monitors[0].CommandSpacing); + } + + [Fact] + public async Task Worker_LearnsALongerSpacing_TheRegistrySavesItInTheSettings() + { + var time = new ManualTimeProvider(); + var monitor = new FakeMonitorController("A", time) { DropWritesWithin = TimeSpan.FromMilliseconds(150) }; + monitor.SetValue(VcpCodes.Brightness, 5, 50); + var settings = new InMemorySettingsStore(); + var options = new DdcWorkerOptions( + 1, + TimeSpan.Zero, + CommandSpacing: TimeSpan.FromMilliseconds(80), + VerifyDelay: TimeSpan.FromMilliseconds(150), + MaxCommandSpacing: TimeSpan.FromMilliseconds(400), + VerifiedCodes: new HashSet { VcpCodes.Brightness }); + await using var registry = new MonitorRegistry(new FakeMonitorEnumerator(() => [monitor]), time, options, Logger.None, settings); + await registry.RefreshAsync(Ct); + var worker = registry.Monitors[0]; + + worker.WriteVcp(VcpCodes.Brightness, 10); + await time.RunUntilAsync(() => monitor.Writes.Count == 1); + worker.WriteVcp(VcpCodes.Brightness, 20); // Follows too closely and is dropped. + await time.RunUntilAsync(() => settings.Current.ForMonitor(monitor.Identity.Key).CommandSpacingMs is not null); + + Assert.Equal((int)worker.CommandSpacing.TotalMilliseconds, settings.Current.ForMonitor(monitor.Identity.Key).CommandSpacingMs); + Assert.True(worker.CommandSpacing >= TimeSpan.FromMilliseconds(150)); + } + private static MonitorRegistry CreateRegistry(FakeMonitorEnumerator enumerator) => new(enumerator, TimeProvider.System, new DdcWorkerOptions(1, TimeSpan.Zero), Logger.None); } diff --git a/tests/DisplayKnob.Core.Tests/Fakes/FakeMonitorController.cs b/tests/DisplayKnob.Core.Tests/Fakes/FakeMonitorController.cs index ee39c65..b154edf 100644 --- a/tests/DisplayKnob.Core.Tests/Fakes/FakeMonitorController.cs +++ b/tests/DisplayKnob.Core.Tests/Fakes/FakeMonitorController.cs @@ -12,9 +12,14 @@ internal sealed class FakeMonitorController : IMonitorController { private readonly ConcurrentDictionary _values = new(); private readonly ConcurrentQueue<(byte Code, uint Value)> _writes = new(); + private readonly ConcurrentQueue _writeTimes = new(); + private readonly TimeProvider _clock; + private DateTimeOffset _lastCallAt; + private DateTimeOffset? _previousCallAt; - public FakeMonitorController(string name = "Fake Monitor") + public FakeMonitorController(string name = "Fake Monitor", TimeProvider? clock = null) { + _clock = clock ?? TimeProvider.System; DisplayName = name; Identity = MonitorIdentity.Create(null, null, name); } @@ -42,6 +47,15 @@ public FakeMonitorController(string name = "Fake Monitor") public IReadOnlyList<(byte Code, uint Value)> Writes => [.. _writes]; + /// + /// When set, a write that follows the previous command (a read or a write) by less than this is acknowledged but + /// not applied, as some monitors do while they are still busy. + /// + public TimeSpan? DropWritesWithin { get; set; } + + /// When each write happened, by the clock the fake was created with. + public IReadOnlyList WriteTimes => [.. _writeTimes]; + /// Codes whose writes are acknowledged but ignored (some monitors do this). public HashSet IgnoredWriteCodes { get; } = []; @@ -66,7 +80,9 @@ public bool TrySetVcp(byte code, uint value) } _writes.Enqueue((code, value)); - if (IgnoredWriteCodes.Contains(code)) + _writeTimes.Enqueue(_lastCallAt); + var tooSoon = DropWritesWithin is { } gap && _previousCallAt is { } previous && _lastCallAt - previous < gap; + if (IgnoredWriteCodes.Contains(code) || tooSoon) { return true; } @@ -90,6 +106,8 @@ public void Dispose() private bool BeginCall() { + _previousCallAt = _lastCallAt == default ? null : _lastCallAt; + _lastCallAt = _clock.GetUtcNow(); CallStarted.Set(); Gate?.Wait(TimeSpan.FromSeconds(10)); CallCount++; diff --git a/tests/DisplayKnob.Core.Tests/Fakes/ManualTimeProvider.cs b/tests/DisplayKnob.Core.Tests/Fakes/ManualTimeProvider.cs new file mode 100644 index 0000000..ed086d9 --- /dev/null +++ b/tests/DisplayKnob.Core.Tests/Fakes/ManualTimeProvider.cs @@ -0,0 +1,148 @@ +namespace DisplayKnob.Core.Tests.Fakes; + +/// +/// A clock that only moves when a test says so, and only to the next moment something is waiting for. +/// +/// +/// Unlike a clock that is advanced by a fixed step, this one can't run ahead of the code under test: time stops at +/// the next timer (a Task.Delay on this provider) and goes no further, so the gaps between the things the code +/// does are exactly the delays it asked for. +/// +internal sealed class ManualTimeProvider : TimeProvider +{ + private readonly Lock _lock = new(); + private readonly List _timers = []; + private DateTimeOffset _now = new(2026, 1, 1, 0, 0, 0, TimeSpan.Zero); + + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + + public override DateTimeOffset GetUtcNow() + { + lock (_lock) + { + return _now; + } + } + + public override long GetTimestamp() => GetUtcNow().Ticks; + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + var timer = new ManualTimer(this, callback, state); + timer.Change(dueTime, period); + return timer; + } + + /// Moves the clock to the earliest pending timer and fires it. if none is pending. + public bool TryAdvanceToNextTimer() + { + ManualTimer? next; + lock (_lock) + { + next = _timers.Where(t => t.Due is not null).OrderBy(t => t.Due).FirstOrDefault(); + if (next is null) + { + return false; + } + + if (next.Due > _now) + { + _now = next.Due.Value; + } + } + + next.Fire(); + return true; + } + + /// + /// Lets time pass, timer by timer, until holds. When nothing is waiting yet the code + /// under test is still running, so this yields instead of moving the clock. + /// + public async Task RunUntilAsync(Func condition) + { + var deadline = Environment.TickCount64 + 10_000; + while (!condition()) + { + Assert.True(Environment.TickCount64 < deadline, "Timed out waiting for the code under test."); + if (!TryAdvanceToNextTimer()) + { + await Task.Yield(); + } + } + } + + /// Lets everything that is already due or waiting run to its end (no new work is expected). + public async Task SettleAsync() + { + // A fixed number of rounds: this is for "nothing else happens", which can't be waited for. + for (var i = 0; i < 2_000; i++) + { + if (!TryAdvanceToNextTimer()) + { + await Task.Yield(); + } + } + } + + private void Add(ManualTimer timer) + { + lock (_lock) + { + if (!_timers.Contains(timer)) + { + _timers.Add(timer); + } + } + } + + private void Remove(ManualTimer timer) + { + lock (_lock) + { + _timers.Remove(timer); + } + } + + private sealed class ManualTimer : ITimer + { + private readonly ManualTimeProvider _owner; + private readonly TimerCallback _callback; + private readonly object? _state; + + public ManualTimer(ManualTimeProvider owner, TimerCallback callback, object? state) + { + _owner = owner; + _callback = callback; + _state = state; + } + + public DateTimeOffset? Due { get; private set; } + + public bool Change(TimeSpan dueTime, TimeSpan period) + { + // Only one-shot timers are used here (Task.Delay); a period is ignored. + Due = dueTime == Timeout.InfiniteTimeSpan ? null : _owner.GetUtcNow() + dueTime; + if (Due is not null) + { + _owner.Add(this); + } + + return true; + } + + public void Fire() + { + Due = null; + _callback(_state); + } + + public void Dispose() => _owner.Remove(this); + + public ValueTask DisposeAsync() + { + Dispose(); + return ValueTask.CompletedTask; + } + } +} diff --git a/tests/DisplayKnob.Core.Tests/Settings/JsonSettingsStoreTests.cs b/tests/DisplayKnob.Core.Tests/Settings/JsonSettingsStoreTests.cs index 57796fb..d9a5335 100644 --- a/tests/DisplayKnob.Core.Tests/Settings/JsonSettingsStoreTests.cs +++ b/tests/DisplayKnob.Core.Tests/Settings/JsonSettingsStoreTests.cs @@ -65,6 +65,28 @@ public void Update_MaxVolumePercent_PersistsAcrossInstances() Assert.Equal(55, reloaded.Current.ForMonitor("DEL4123-ABC|PATH").MaxVolumePercent); } + [Fact] + public void Update_CommandSpacing_PersistsAcrossInstances() + { + var store = new JsonSettingsStore(SettingsPath, Logger.None); + + store.Update(s => s with { Monitors = new Dictionary { ["DEL4123-ABC|PATH"] = new() { CommandSpacingMs = 180 } } }); + var reloaded = new JsonSettingsStore(SettingsPath, Logger.None); + + Assert.Equal(180, reloaded.Current.ForMonitor("DEL4123-ABC|PATH").CommandSpacingMs); + } + + [Fact] + public void Constructor_MonitorEntryWithoutCommandSpacing_UsesTheDefault() + { + Directory.CreateDirectory(_dir); + File.WriteAllText(SettingsPath, """{ "monitors": { "DEL4123-ABC|PATH": { "ddcVolumeEnabled": true } } }"""); + + var monitor = new JsonSettingsStore(SettingsPath, Logger.None).Current.ForMonitor("DEL4123-ABC|PATH"); + + Assert.Null(monitor.CommandSpacingMs); + } + [Fact] public void Update_VolumeCurve_PersistsAcrossInstances() {