Bluetooth.Android.cs 4.5 KB

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