Desktop_Bluetooth.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using BluetoothLENet;
  2. using InABox.Core;
  3. namespace InABox.Avalonia.Platform.Desktop;
  4. public class Desktop_Bluetooth : IBluetooth, IDisposable
  5. {
  6. public Logger? Logger { get; set; }
  7. private BLE _adapter;
  8. public Action<IBluetoothDevice>? DeviceFound { get; set; }
  9. public CoreObservableCollection<IBluetoothDevice> Devices { get; } = new();
  10. public event EventHandler? Changed;
  11. public Desktop_Bluetooth()
  12. {
  13. Devices.CollectionChanged += (_,_) => Changed?.Invoke(this, EventArgs.Empty);
  14. _adapter = new BLE();
  15. _adapter.Changed += (_,_) =>
  16. {
  17. var found = _adapter.Devices.Select(x => x.MacAddress).ToArray();
  18. var cache = Devices.OfType<Desktop_BluetoothDevice>().Select(x => x.ID).ToArray();
  19. if (found.Except(cache).Any() || cache.Except(found).Any())
  20. {
  21. var devices = _adapter.Devices
  22. .ToArray()
  23. .Select(x => new Desktop_BluetoothDevice(x));
  24. Devices.ReplaceRange(devices);
  25. }
  26. };
  27. }
  28. public async Task<bool> IsAvailable()
  29. {
  30. return await Task.FromResult(true);
  31. }
  32. public async Task<bool> StartScanningAsync(Guid configServiceId)
  33. {
  34. if (await IsAvailable())
  35. return await _adapter.StartScanningAsync(configServiceId);
  36. return false;
  37. }
  38. public async Task<bool> StopScanningAsync()
  39. {
  40. if (await IsAvailable())
  41. return await _adapter.StopScanningAsync();
  42. return false;
  43. }
  44. public async Task<IConnectedBluetoothDevice?> Connect(IBluetoothDevice device)
  45. {
  46. if (await IsAvailable())
  47. {
  48. if (device is Desktop_BluetoothDevice d)
  49. {
  50. var result = await _adapter.Connect(d.Device);
  51. if (result == ConnectDeviceResult.Ok)
  52. return new Desktop_ConnectedBluetoothDevice(d.Device);
  53. }
  54. }
  55. return null;
  56. }
  57. public async Task<bool> Disconnect(IConnectedBluetoothDevice device)
  58. {
  59. if (await IsAvailable())
  60. {
  61. if (device is Desktop_BluetoothDevice { Device: not null } d)
  62. {
  63. _adapter.Disconnect(d.Device);
  64. }
  65. }
  66. return true;
  67. }
  68. public void Dispose()
  69. {
  70. foreach (var device in Devices)
  71. device.Dispose();
  72. Devices.Clear();
  73. }
  74. }