Compare commits

..
1 Commits
Author SHA1 Message Date
suffian b22b0df6ed Bluetooth check, avoid crashing 2026-10-14 07:24:06 +08:00
6 changed files with 118 additions and 9 deletions
+33 -1
View File
@@ -84,6 +84,34 @@ public sealed class BleManager : IBleService
// ──────────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────────
// SCANNING // SCANNING
// ──────────────────────────────────────────────────────────────────────── // ────────────────────────────────────────────────────────────────────────
/// <summary>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.</summary>
public async Task<BluetoothAvailability> 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<BleDeviceInfo> StartScan() public IObservable<BleDeviceInfo> StartScan()
{ {
var seen = new Dictionary<ulong, string>(); var seen = new Dictionary<ulong, string>();
@@ -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(); return _scanSubject.AsObservable();
} }
+8
View File
@@ -6,6 +6,10 @@ namespace TuneBoss.Core.BLE;
/// <summary> /// <summary>
/// Represents a discovered BLE device before connection. /// Represents a discovered BLE device before connection.
/// </summary> /// </summary>
/// <summary>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).</summary>
public readonly record struct BluetoothAvailability(bool IsReady, string Message);
public sealed record BleDeviceInfo( public sealed record BleDeviceInfo(
ulong Address, ulong Address,
string Name, string Name,
@@ -69,6 +73,10 @@ public interface IBleService : IDisposable
// ── Scanning ───────────────────────────────────────────────────────────── // ── Scanning ─────────────────────────────────────────────────────────────
/// <summary>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.</summary>
Task<BluetoothAvailability> CheckBluetoothAsync();
/// <summary>Starts BLE advertisement scanning. Emits discovered devices.</summary> /// <summary>Starts BLE advertisement scanning. Emits discovered devices.</summary>
IObservable<BleDeviceInfo> StartScan(); IObservable<BleDeviceInfo> StartScan();
+3
View File
@@ -41,6 +41,9 @@ public sealed class SimBleService : IBleService
public IObservable<BleConnectionState> ConnectionStateChanged => _state.AsObservable(); public IObservable<BleConnectionState> ConnectionStateChanged => _state.AsObservable();
// ── Scan ────────────────────────────────────────────────────────────────── // ── Scan ──────────────────────────────────────────────────────────────────
public Task<BluetoothAvailability> CheckBluetoothAsync() =>
Task.FromResult(new BluetoothAvailability(true, string.Empty));
public IObservable<BleDeviceInfo> StartScan() => Observable.Create<BleDeviceInfo>(o => public IObservable<BleDeviceInfo> StartScan() => Observable.Create<BleDeviceInfo>(o =>
{ {
o.OnNext(new BleDeviceInfo(0xAABBCCDDEEFF, "B_SIM-PG1", -42)); o.OnNext(new BleDeviceInfo(0xAABBCCDDEEFF, "B_SIM-PG1", -42));
+47
View File
@@ -16,11 +16,48 @@ public partial class App : Application
public App() 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() _host = Host.CreateDefaultBuilder()
.ConfigureServices(ConfigureServices) .ConfigureServices(ConfigureServices)
.Build(); .Build();
} }
/// <summary>Appends an exception to %APPDATA%\TuneBoss\crash.log and shows a dialog.
/// Never throws — logging a crash must not itself crash.</summary>
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) private static void ConfigureServices(IServiceCollection services)
{ {
// --sim on the command line swaps in the fake ECU. // --sim on the command line swaps in the fake ECU.
@@ -61,6 +98,8 @@ public partial class App : Application
} }
protected override async void OnStartup(StartupEventArgs e) protected override async void OnStartup(StartupEventArgs e)
{
try
{ {
await _host.StartAsync(); await _host.StartAsync();
Wpf.Ui.Appearance.ApplicationThemeManager.Apply( Wpf.Ui.Appearance.ApplicationThemeManager.Apply(
@@ -69,6 +108,14 @@ public partial class App : Application
mainWindow.Show(); mainWindow.Show();
base.OnStartup(e); 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) protected override async void OnExit(ExitEventArgs e)
{ {
+18 -1
View File
@@ -82,6 +82,23 @@ public partial class ConnectViewModel : ObservableObject, IDisposable
}); });
} }
/// <summary>
/// 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.
/// </summary>
public async Task EnsureBluetoothThenScanAsync()
{
if (IsScanning) return;
var bt = await _ble.CheckBluetoothAsync();
if (!bt.IsReady)
{
SetStatus(bt.Message);
return;
}
StartScan();
}
[RelayCommand] [RelayCommand]
public void StartScan() public void StartScan()
{ {
@@ -119,7 +136,7 @@ public partial class ConnectViewModel : ObservableObject, IDisposable
} }
else else
{ {
StartScan(); _ = EnsureBluetoothThenScanAsync();
} }
} }
+3 -1
View File
@@ -9,6 +9,8 @@ public partial class ConnectView : UserControl
{ {
DataContext = vm; DataContext = vm;
InitializeComponent(); 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();
} }
} }