diff --git a/TuneBoss.Core/BLE/BleManager.cs b/TuneBoss.Core/BLE/BleManager.cs index 8931ed9..7b3aa5f 100644 --- a/TuneBoss.Core/BLE/BleManager.cs +++ b/TuneBoss.Core/BLE/BleManager.cs @@ -84,6 +84,34 @@ public sealed class BleManager : IBleService // ──────────────────────────────────────────────────────────────────────── // SCANNING // ──────────────────────────────────────────────────────────────────────── + + /// Checks that a Bluetooth adapter exists, supports LE, and its radio is on. + /// Never throws — any failure comes back as IsReady=false with a reason. + public async Task CheckBluetoothAsync() + { + try + { + var adapter = await BluetoothAdapter.GetDefaultAsync(); + if (adapter == null) + return new BluetoothAvailability(false, "No Bluetooth adapter found on this PC."); + if (!adapter.IsLowEnergySupported) + return new BluetoothAvailability(false, "This PC's Bluetooth does not support Bluetooth LE."); + + var radio = await adapter.GetRadioAsync(); + if (radio == null) + return new BluetoothAvailability(false, "Could not access the Bluetooth radio."); + if (radio.State != Windows.Devices.Radios.RadioState.On) + return new BluetoothAvailability(false, + "Bluetooth is turned off. Please turn it on, then press Scan."); + + return new BluetoothAvailability(true, string.Empty); + } + catch (Exception ex) + { + return new BluetoothAvailability(false, $"Bluetooth is unavailable: {ex.Message}"); + } + } + public IObservable StartScan() { var seen = new Dictionary(); @@ -117,7 +145,11 @@ public sealed class BleManager : IBleService } }; - _watcher.Start(); + // Guard the radio-off / adapter-missing case so a scan start can never crash the + // app. Callers should CheckBluetoothAsync() first, but this is the safety net. + try { _watcher.Start(); } + catch (Exception) { _watcher = null; } + return _scanSubject.AsObservable(); } diff --git a/TuneBoss.Core/BLE/IBleService.cs b/TuneBoss.Core/BLE/IBleService.cs index 195585a..68491af 100644 --- a/TuneBoss.Core/BLE/IBleService.cs +++ b/TuneBoss.Core/BLE/IBleService.cs @@ -6,6 +6,10 @@ namespace TuneBoss.Core.BLE; /// /// Represents a discovered BLE device before connection. /// +/// Result of a Bluetooth-adapter check: whether BLE is ready to scan, and a +/// human-readable reason when it isn't (no adapter / no BLE support / radio off). +public readonly record struct BluetoothAvailability(bool IsReady, string Message); + public sealed record BleDeviceInfo( ulong Address, string Name, @@ -69,6 +73,10 @@ public interface IBleService : IDisposable // ── Scanning ───────────────────────────────────────────────────────────── + /// Whether a Bluetooth adapter is present and its radio is on. Call this + /// before scanning so a radio that's off gives a friendly message instead of a crash. + Task CheckBluetoothAsync(); + /// Starts BLE advertisement scanning. Emits discovered devices. IObservable StartScan(); diff --git a/TuneBoss.Core/BLE/SimBleService.cs b/TuneBoss.Core/BLE/SimBleService.cs index 5b3aff7..c5bb422 100644 --- a/TuneBoss.Core/BLE/SimBleService.cs +++ b/TuneBoss.Core/BLE/SimBleService.cs @@ -41,6 +41,9 @@ public sealed class SimBleService : IBleService public IObservable ConnectionStateChanged => _state.AsObservable(); // ── Scan ────────────────────────────────────────────────────────────────── + public Task CheckBluetoothAsync() => + Task.FromResult(new BluetoothAvailability(true, string.Empty)); + public IObservable StartScan() => Observable.Create(o => { o.OnNext(new BleDeviceInfo(0xAABBCCDDEEFF, "B_SIM-PG1", -42)); diff --git a/TuneBossPC/App.xaml.cs b/TuneBossPC/App.xaml.cs index 88685db..f27713d 100644 --- a/TuneBossPC/App.xaml.cs +++ b/TuneBossPC/App.xaml.cs @@ -16,11 +16,48 @@ public partial class App : Application public App() { + // Catch ANY unhandled exception so a startup failure can't die silently — it gets + // written to %APPDATA%\TuneBoss\crash.log and shown in a dialog. (ClickOnce installs + // that crash on launch with no message otherwise leave nothing to go on.) + DispatcherUnhandledException += (_, e) => + { + LogCrash("UI thread", e.Exception); + e.Handled = true; // already surfaced; keep running if the UI thread can + }; + AppDomain.CurrentDomain.UnhandledException += (_, e) => + LogCrash("AppDomain", e.ExceptionObject as Exception); + System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (_, e) => + { + LogCrash("Background task", e.Exception); + e.SetObserved(); + }; + _host = Host.CreateDefaultBuilder() .ConfigureServices(ConfigureServices) .Build(); } + /// Appends an exception to %APPDATA%\TuneBoss\crash.log and shows a dialog. + /// Never throws — logging a crash must not itself crash. + private static void LogCrash(string source, Exception? ex) + { + try + { + var dir = System.IO.Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TuneBoss"); + System.IO.Directory.CreateDirectory(dir); + var path = System.IO.Path.Combine(dir, "crash.log"); + System.IO.File.AppendAllText(path, + $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ({source})\r\n{ex}\r\n\r\n"); + + MessageBox.Show( + $"TuneBoss PC hit an error.\n\nA log was saved to:\n{path}\n\n" + + $"{ex?.GetType().Name}: {ex?.Message}", + "TuneBoss PC — Error", MessageBoxButton.OK, MessageBoxImage.Error); + } + catch { /* logging must never throw */ } + } + private static void ConfigureServices(IServiceCollection services) { // --sim on the command line swaps in the fake ECU. @@ -62,12 +99,22 @@ public partial class App : Application protected override async void OnStartup(StartupEventArgs e) { - await _host.StartAsync(); - Wpf.Ui.Appearance.ApplicationThemeManager.Apply( - Wpf.Ui.Appearance.ApplicationTheme.Dark); - var mainWindow = _host.Services.GetRequiredService(); - mainWindow.Show(); - base.OnStartup(e); + try + { + await _host.StartAsync(); + Wpf.Ui.Appearance.ApplicationThemeManager.Apply( + Wpf.Ui.Appearance.ApplicationTheme.Dark); + var mainWindow = _host.Services.GetRequiredService(); + mainWindow.Show(); + base.OnStartup(e); + } + catch (Exception ex) + { + // Service construction (BLE/WinRT, settings, etc.), theme, or window build + // failed — log it and exit cleanly instead of vanishing. + LogCrash("Startup", ex); + Shutdown(-1); + } } protected override async void OnExit(ExitEventArgs e) diff --git a/TuneBossPC/ViewModels/ConnectViewModel.cs b/TuneBossPC/ViewModels/ConnectViewModel.cs index 9a3a52c..0d65d39 100644 --- a/TuneBossPC/ViewModels/ConnectViewModel.cs +++ b/TuneBossPC/ViewModels/ConnectViewModel.cs @@ -82,6 +82,23 @@ public partial class ConnectViewModel : ObservableObject, IDisposable }); } + /// + /// Verifies Bluetooth is on before scanning. If the radio is off / missing, shows a + /// friendly message instead of scanning (which used to throw and crash the app on + /// launch). Called by the auto-scan on page load and by the Scan button. + /// + public async Task EnsureBluetoothThenScanAsync() + { + if (IsScanning) return; + var bt = await _ble.CheckBluetoothAsync(); + if (!bt.IsReady) + { + SetStatus(bt.Message); + return; + } + StartScan(); + } + [RelayCommand] public void StartScan() { @@ -119,7 +136,7 @@ public partial class ConnectViewModel : ObservableObject, IDisposable } else { - StartScan(); + _ = EnsureBluetoothThenScanAsync(); } } diff --git a/TuneBossPC/Views/ConnectView.xaml.cs b/TuneBossPC/Views/ConnectView.xaml.cs index 9ffca46..61fd737 100644 --- a/TuneBossPC/Views/ConnectView.xaml.cs +++ b/TuneBossPC/Views/ConnectView.xaml.cs @@ -9,6 +9,8 @@ public partial class ConnectView : UserControl { DataContext = vm; InitializeComponent(); - vm.StartScan(); + // Auto-scan on load, but check Bluetooth first. Calling scan synchronously in the + // ctor used to throw (and silently crash the app at launch) when the radio was off. + Loaded += async (_, _) => await vm.EnsureBluetoothThenScanAsync(); } }