Bluetooth.Android.cs 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. using Android.Bluetooth;
  2. using Android.Bluetooth.LE;
  3. using Android.Content;
  4. using InABox.Core;
  5. using Microsoft.Maui.ApplicationModel;
  6. namespace InABox.Avalonia.Platform.Android;
  7. public class Android_Bluetooth : IBluetooth
  8. {
  9. public Logger? Logger { get; set; }
  10. public CoreObservableCollection<IBluetoothDevice> Devices { get; private set; } = new CoreObservableCollection<IBluetoothDevice>();
  11. private readonly BluetoothLeScanner? _scanner;
  12. public event EventHandler? Changed;
  13. public Android_Bluetooth()
  14. {
  15. var _manager = Application.Context.GetSystemService(Context.BluetoothService) as BluetoothManager;
  16. var _adapter = _manager?.Adapter;
  17. _scanner = _adapter?.BluetoothLeScanner;
  18. Task.Run(() =>
  19. {
  20. while (true)
  21. {
  22. var stale = Devices.ToArray().Where(x => (x == null) || (x.LastSeen < DateTime.Now.Subtract(new TimeSpan(0, 0, 5))))
  23. .ToArray();
  24. if (stale.Any())
  25. Devices.RemoveRange(stale);
  26. Task.Delay(500);
  27. }
  28. });
  29. }
  30. public static async Task<bool> IsPermitted<TPermission>() where TPermission : Permissions.BasePermission, new()
  31. {
  32. try
  33. {
  34. PermissionStatus status = await Permissions.CheckStatusAsync<TPermission>();
  35. if (status == PermissionStatus.Granted)
  36. return true;
  37. var request = await Permissions.RequestAsync<TPermission>();
  38. return request == PermissionStatus.Granted;
  39. }
  40. catch (TaskCanceledException ex)
  41. {
  42. return false;
  43. }
  44. }
  45. public async Task<bool> IsAvailable()
  46. {
  47. if (await IsPermitted<Permissions.Bluetooth>())
  48. return _scanner != null;
  49. return false;
  50. }
  51. BluetoothScanManager? _callback;
  52. public async Task<bool> StartScanningAsync(Guid configServiceId)
  53. {
  54. if (await IsAvailable())
  55. {
  56. _callback = new BluetoothScanManager((d) => DoDeviceFound(d, configServiceId), ScanStopped);
  57. _scanner!.StartScan(_callback);
  58. return true;
  59. }
  60. return false;
  61. }
  62. public async Task<bool> StopScanningAsync()
  63. {
  64. if (await IsAvailable())
  65. {
  66. if (_callback != null)
  67. {
  68. _scanner!.StopScan(_callback);
  69. return true;
  70. }
  71. }
  72. return false;
  73. }
  74. private void DoDeviceFound(ScanResult device, Guid configServiceId)
  75. {
  76. var abd = Devices.FirstOrDefault(x => x.ID == device.Device?.Address);
  77. if (abd == null)
  78. {
  79. var services = device.ScanRecord?.ServiceUuids?
  80. .Select(x => Guid.Parse(x.ToString()))
  81. .Where(x => !x.ToString().ToUpper().EndsWith("-0000-1000-8000-00805F9B34FB") && configServiceId != x)
  82. .ToArray() ?? [];
  83. abd = new Android_BluetoothDevice(device, services, DateTime.Now);
  84. Devices.Add(abd);
  85. }
  86. else
  87. abd.LastSeen = DateTime.Now;
  88. }
  89. private void ScanStopped()
  90. {
  91. _callback = null;
  92. }
  93. public async Task<IConnectedBluetoothDevice?> Connect(IBluetoothDevice device)
  94. {
  95. if (device is Android_BluetoothDevice d && d.Scan.Device is BluetoothDevice bd)
  96. {
  97. var result = new Android_ConnectedBluetoothDevice(bd);
  98. if (await result.ConnectAsync())
  99. {
  100. await result.DiscoverServicesAsync();
  101. return result;
  102. }
  103. }
  104. return null;
  105. }
  106. public async Task<bool> Disconnect(IConnectedBluetoothDevice device)
  107. {
  108. if (device is Android_ConnectedBluetoothDevice d)
  109. d.Dispose();
  110. return await Task.FromResult(true);
  111. }
  112. }