Bluetooth.Android.cs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. {
  26. Devices.RemoveRange(stale);
  27. Changed?.Invoke(this, EventArgs.Empty);
  28. }
  29. Task.Delay(500);
  30. }
  31. });
  32. }
  33. public static async Task<bool> IsPermitted<TPermission>() where TPermission : Permissions.BasePermission, new()
  34. {
  35. try
  36. {
  37. PermissionStatus status = await Permissions.CheckStatusAsync<TPermission>();
  38. if (status == PermissionStatus.Granted)
  39. return true;
  40. var request = await Permissions.RequestAsync<TPermission>();
  41. return request == PermissionStatus.Granted;
  42. }
  43. catch (TaskCanceledException ex)
  44. {
  45. return false;
  46. }
  47. }
  48. public async Task<bool> IsAvailable()
  49. {
  50. if (await IsPermitted<Permissions.Bluetooth>())
  51. return _scanner != null;
  52. return false;
  53. }
  54. BluetoothScanManager? _callback;
  55. public async Task<bool> StartScanningAsync(Guid configServiceId)
  56. {
  57. if (await IsAvailable())
  58. {
  59. _callback = new BluetoothScanManager((d) => DoDeviceFound(d, configServiceId), ScanStopped);
  60. _scanner!.StartScan(_callback);
  61. return true;
  62. }
  63. return false;
  64. }
  65. public async Task<bool> StopScanningAsync()
  66. {
  67. if (await IsAvailable())
  68. {
  69. if (_callback != null)
  70. {
  71. _scanner!.StopScan(_callback);
  72. return true;
  73. }
  74. }
  75. return false;
  76. }
  77. private void DoDeviceFound(ScanResult device, Guid configServiceId)
  78. {
  79. var isTarget = device.ScanRecord?.ServiceUuids?
  80. .Any(x=>string.Equals(x.ToString(),configServiceId.ToString(), StringComparison.OrdinalIgnoreCase))
  81. ?? false;
  82. if (isTarget)
  83. {
  84. var abd = Devices.FirstOrDefault(x => x.ID == device.Device?.Address);
  85. if (abd == null)
  86. {
  87. if (isTarget)
  88. {
  89. var services = device.ScanRecord?.ServiceUuids?
  90. .Select(x => Guid.Parse(x.ToString()))
  91. .Where(x => !x.ToString().ToUpper().EndsWith("-0000-1000-8000-00805F9B34FB") &&
  92. configServiceId != x)
  93. .ToArray() ?? [];
  94. if (services.Any())
  95. {
  96. abd = new Android_BluetoothDevice(device, services, DateTime.Now);
  97. Devices.Add(abd);
  98. Changed?.Invoke(this, EventArgs.Empty);
  99. }
  100. }
  101. }
  102. else
  103. abd.LastSeen = DateTime.Now;
  104. }
  105. }
  106. private void ScanStopped()
  107. {
  108. _callback = null;
  109. }
  110. public async Task<IConnectedBluetoothDevice?> Connect(IBluetoothDevice device)
  111. {
  112. if (device is Android_BluetoothDevice d && d.Scan.Device is BluetoothDevice bd)
  113. {
  114. var result = new Android_ConnectedBluetoothDevice(bd);
  115. if (await result.ConnectAsync())
  116. {
  117. await result.DiscoverServicesAsync();
  118. return result;
  119. }
  120. }
  121. return null;
  122. }
  123. public async Task<bool> Disconnect(IConnectedBluetoothDevice device)
  124. {
  125. if (device is Android_ConnectedBluetoothDevice d)
  126. d.Dispose();
  127. return await Task.FromResult(true);
  128. }
  129. }