Bluetooth check, avoid crashing

This commit is contained in:
2026-10-14 07:24:06 +08:00
parent 1ec485701a
commit b22b0df6ed
6 changed files with 118 additions and 9 deletions
+33 -1
View File
@@ -84,6 +84,34 @@ public sealed class BleManager : IBleService
// ────────────────────────────────────────────────────────────────────────
// 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()
{
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();
}