Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions CopperPad.Gui/MainWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public MainWindow()
MinHeight = 640;
Content = BuildContent();

_host.DevicesChanged += (_, args) => Dispatcher.UIThread.Post(() => OnDevicesChanged(args.Devices));
_host.DevicesChanged += (_, args) => Dispatcher.UIThread.Post(() => OnDevicesChanged(args));
_host.RawReportReceived += (_, args) => Dispatcher.UIThread.Post(() => OnRawReport(args));
_host.StateChanged += (_, args) => Dispatcher.UIThread.Post(() => OnStateChanged(args.State));
Opened += async (_, _) => await InitializeAsync().ConfigureAwait(true);
Expand Down Expand Up @@ -365,17 +365,30 @@ private async Task InitializeAsync()
SetStatus("Profile load failed: " + ex.Message);
}

_host.Start();
StartHost();
}

private void RefreshDevices()
{
_host.Stop();
_host.Start();
try
{
_host.Stop();
_host.Start();
}
catch (Exception ex) when (IsRecoverableHidException(ex))
{
SetStatus("Controller refresh failed: " + ex.Message);
}
}

private void OnDevicesChanged(IReadOnlyList<HidDeviceInfo> devices)
private void OnDevicesChanged(HidDevicesChangedEventArgs args)
{
var devices = args.Devices;
if (!string.IsNullOrWhiteSpace(args.Diagnostic))
{
SetStatus(args.Diagnostic);
}

var selectedId = _selectedDevice?.Id;
var items = devices.Select(device => new DeviceListItem(device)).ToArray();
_deviceList.ItemsSource = items;
Expand All @@ -392,6 +405,18 @@ private void OnDevicesChanged(IReadOnlyList<HidDeviceInfo> devices)
}
}

private void StartHost()
{
try
{
_host.Start();
}
catch (Exception ex) when (IsRecoverableHidException(ex))
{
SetStatus("Controller scan failed: " + ex.Message);
}
}

private void SelectDevice(HidDeviceInfo? device)
{
_selectedDevice = device;
Expand Down Expand Up @@ -932,6 +957,9 @@ private static void AddCell(Grid grid, Control control, int row, int column)
private static int DecimalToInt(decimal? value)
=> (int)(value ?? 0);

private static bool IsRecoverableHidException(Exception ex)
=> ex is IOException or InvalidOperationException or TimeoutException or UnauthorizedAccessException or NotSupportedException;

private static string ToHexRows(byte[] bytes)
{
if (bytes.Length == 0)
Expand Down
26 changes: 25 additions & 1 deletion CopperPad.Tests/ControllerDiagnosticsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ public void DiagnosticsHost_EnumeratesAllHidDevices()
Assert.Equal(observed, host.GetDevices());
}

[Fact]
public void DiagnosticsHost_PublishesScanDiagnosticWhenEnumerationFails()
{
var provider = new FakeHidDeviceProvider { GetDevicesException = new NotSupportedException("descriptor unavailable") };
using var host = new ControllerDiagnosticsHost(provider, new ControllerHostOptions());
HidDevicesChangedEventArgs? observed = null;
host.DevicesChanged += (_, args) => observed = args;

host.Start();

Assert.Empty(host.GetDevices());
Assert.NotNull(observed);
Assert.Equal("HID scan failed: descriptor unavailable", observed.Diagnostic);
}

[Fact]
public async Task DiagnosticsHost_PublishesRawReportsAndProfileMappedState()
{
Expand Down Expand Up @@ -89,10 +104,19 @@ private sealed class FakeHidDeviceProvider : IHidDeviceProvider
private readonly Dictionary<string, FakeHidInputStream> _streams = new(StringComparer.Ordinal);
private IReadOnlyList<HidDeviceDescriptor> _devices = Array.Empty<HidDeviceDescriptor>();

public Exception? GetDevicesException { get; init; }

public event EventHandler? Changed;

public IReadOnlyList<HidDeviceDescriptor> GetDevices()
=> _devices;
{
if (GetDevicesException != null)
{
throw GetDevicesException;
}

return _devices;
}

public IHidInputStream Open(HidDeviceDescriptor device, TimeSpan readTimeout)
=> _streams.TryGetValue(device.Id, out var stream)
Expand Down
38 changes: 29 additions & 9 deletions CopperPad/ControllerDiagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ public sealed record HidDeviceInfo(
bool ReportsUseId,
string? Diagnostic);

public sealed class HidDevicesChangedEventArgs(IReadOnlyList<HidDeviceInfo> devices) : EventArgs
public sealed class HidDevicesChangedEventArgs(IReadOnlyList<HidDeviceInfo> devices, string? diagnostic = null) : EventArgs
{
public IReadOnlyList<HidDeviceInfo> Devices { get; } = devices;
public string? Diagnostic { get; } = diagnostic;
}

public sealed class ControllerRawReportReceivedEventArgs(HidDeviceInfo device, byte[] report, int length, DateTimeOffset timestamp) : EventArgs
Expand All @@ -38,6 +39,7 @@ public sealed class ControllerDiagnosticsHost : IDisposable
private IReadOnlyList<HidDeviceDescriptor> _descriptors = Array.Empty<HidDeviceDescriptor>();
private IReadOnlyList<HidDeviceInfo> _devices = Array.Empty<HidDeviceInfo>();
private ControllerProfileSet _profiles;
private string? _diagnostic;
private string? _selectedDeviceId;
private CancellationTokenSource? _readerCancellation;
private Task? _readerTask;
Expand Down Expand Up @@ -168,12 +170,27 @@ private void OnProviderChanged(object? sender, EventArgs args)

private void RescanLocked(bool restartReader)
{
_descriptors = _provider.GetDevices()
.GroupBy(device => device.Id, StringComparer.Ordinal)
.Select(group => group.First())
.OrderBy(device => device.ProductName, StringComparer.OrdinalIgnoreCase)
.ThenBy(device => device.Id, StringComparer.Ordinal)
.ToArray();
try
{
_descriptors = _provider.GetDevices()
.GroupBy(device => device.Id, StringComparer.Ordinal)
.Select(group => group.First())
.OrderBy(device => device.ProductName, StringComparer.OrdinalIgnoreCase)
.ThenBy(device => device.Id, StringComparer.Ordinal)
.ToArray();
_diagnostic = null;
}
catch (Exception ex) when (IsRecoverableHidException(ex))
{
StopReaderLocked();
_descriptors = Array.Empty<HidDeviceDescriptor>();
_devices = Array.Empty<HidDeviceInfo>();
_selectedDeviceId = null;
_diagnostic = "HID scan failed: " + ex.Message;
RaiseDevicesChangedLocked();
return;
}

_devices = _descriptors.Select(ToInfo).ToArray();
if (_selectedDeviceId != null && !_descriptors.Any(device => string.Equals(device.Id, _selectedDeviceId, StringComparison.Ordinal)))
{
Expand Down Expand Up @@ -260,7 +277,7 @@ private async Task ReadLoopAsync(HidDeviceDescriptor device, IControllerMapper m
catch (OperationCanceledException)
{
}
catch (Exception ex) when (ex is IOException or InvalidOperationException or TimeoutException or UnauthorizedAccessException)
catch (Exception ex) when (IsRecoverableHidException(ex))
{
var failed = info with { Diagnostic = "HID read failed: " + ex.Message };
var controller = new ControllerInfo(
Expand All @@ -276,7 +293,10 @@ private async Task ReadLoopAsync(HidDeviceDescriptor device, IControllerMapper m
}

private void RaiseDevicesChangedLocked()
=> DevicesChanged?.Invoke(this, new HidDevicesChangedEventArgs(_devices));
=> DevicesChanged?.Invoke(this, new HidDevicesChangedEventArgs(_devices, _diagnostic));

private static bool IsRecoverableHidException(Exception ex)
=> ex is IOException or InvalidOperationException or TimeoutException or UnauthorizedAccessException or NotSupportedException;

private void ThrowIfDisposed()
{
Expand Down
2 changes: 1 addition & 1 deletion CopperPad/ControllerHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ private async Task ReadLoopAsync()
catch (OperationCanceledException)
{
}
catch (Exception ex) when (ex is IOException or InvalidOperationException or TimeoutException or UnauthorizedAccessException)
catch (Exception ex) when (ex is IOException or InvalidOperationException or TimeoutException or UnauthorizedAccessException or NotSupportedException)
{
var diagnostic = "HID read failed: " + ex.Message;
Info = Info with { IsConnected = false, Diagnostic = diagnostic };
Expand Down
4 changes: 2 additions & 2 deletions CopperPad/HidSharpDeviceProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ private static HidDeviceDescriptor CreateDescriptor(HidDevice device)
.SelectMany(report => report.GetAllUsages())
.Any(IsGameControllerUsage);
}
catch (Exception ex) when (ex is IOException or InvalidOperationException or ArgumentException)
catch (Exception ex) when (ex is IOException or InvalidOperationException or ArgumentException or NotSupportedException)
{
diagnostic = "Unable to parse HID report descriptor: " + ex.Message;
}
Expand Down Expand Up @@ -99,7 +99,7 @@ private static string SafeString(Func<string> getter, string? fallback, string d
var value = getter();
return string.IsNullOrWhiteSpace(value) ? fallback ?? defaultValue : value;
}
catch (Exception ex) when (ex is IOException or InvalidOperationException)
catch (Exception ex) when (ex is IOException or InvalidOperationException or NotSupportedException or UnauthorizedAccessException)
{
return string.IsNullOrWhiteSpace(fallback) ? defaultValue : fallback;
}
Expand Down
Loading