Bluetooth.Android.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using System.Collections.ObjectModel;
  2. using Android.Bluetooth;
  3. using Android.Bluetooth.LE;
  4. using Android.Content;
  5. using Android.OS;
  6. using Android.Text.Style;
  7. using FluentResults;
  8. using InABox.Core;
  9. using Microsoft.Maui.ApplicationModel;
  10. namespace InABox.Avalonia.Platform.Android;
  11. public class Android_BluetoothDevice(ScanResult scan) : IBluetoothDevice, IDisposable
  12. {
  13. public ScanResult Scan { get; } = scan;
  14. public string ID { get; } = scan.Device?.Address ?? string.Empty;
  15. public string Name { get; } = scan.ScanRecord?.DeviceName ?? "Unknown Device";
  16. public void Dispose()
  17. {
  18. Scan.Dispose();
  19. }
  20. }
  21. public class Android_ConnectedBluetoothDevice(BluetoothDevice device) : BluetoothGattCallback,IConnectedBluetoothDevice
  22. {
  23. private BluetoothDevice _device = device;
  24. public string ID { get; } = device?.Address ?? string.Empty;
  25. public string Name { get; } = device?.Name ?? "Unknown Device";
  26. private BluetoothGatt? _bluetoothGatt;
  27. private TaskCompletionSource<bool> _connectionTaskCompletionSource;
  28. private TaskCompletionSource<bool> _serviceDiscoveryTaskCompletionSource;
  29. private TaskCompletionSource<byte[]> _readTaskCompletionSource;
  30. private TaskCompletionSource<bool> _writeTaskCompletionSource;
  31. public async Task<bool> ConnectAsync()
  32. {
  33. _connectionTaskCompletionSource = new TaskCompletionSource<bool>();
  34. _bluetoothGatt = _device.ConnectGatt(Application.Context, false, this);
  35. return await _connectionTaskCompletionSource.Task;
  36. }
  37. public override void OnConnectionStateChange(BluetoothGatt? gatt, GattStatus status, ProfileState newState)
  38. {
  39. base.OnConnectionStateChange(gatt, status, newState);
  40. if (newState == ProfileState.Connected && status == GattStatus.Success)
  41. {
  42. Console.WriteLine("Connected to GATT server.");
  43. _connectionTaskCompletionSource?.TrySetResult(true);
  44. }
  45. else
  46. {
  47. Console.WriteLine("Failed to connect or disconnected.");
  48. _connectionTaskCompletionSource?.TrySetResult(false);
  49. Dispose();
  50. }
  51. }
  52. public async Task<bool> DiscoverServicesAsync()
  53. {
  54. _serviceDiscoveryTaskCompletionSource = new TaskCompletionSource<bool>();
  55. _bluetoothGatt?.DiscoverServices();
  56. return await _serviceDiscoveryTaskCompletionSource.Task;
  57. }
  58. public override void OnServicesDiscovered(BluetoothGatt? gatt, GattStatus status)
  59. {
  60. base.OnServicesDiscovered(gatt, status);
  61. if (status == GattStatus.Success)
  62. {
  63. Console.WriteLine("Services discovered.");
  64. _serviceDiscoveryTaskCompletionSource?.TrySetResult(true);
  65. }
  66. else
  67. {
  68. Console.WriteLine("Service discovery failed.");
  69. _serviceDiscoveryTaskCompletionSource?.TrySetResult(false);
  70. }
  71. }
  72. public async Task<byte[]?> ReadAsync(Guid serviceid, Guid characteristicid)
  73. {
  74. byte[]? result = null;
  75. if (_bluetoothGatt != null)
  76. {
  77. var service = _bluetoothGatt.GetService(Java.Util.UUID.FromString(serviceid.ToString()));
  78. if (service != null)
  79. {
  80. var characteristic = service.GetCharacteristic(Java.Util.UUID.FromString(characteristicid.ToString()));
  81. if (characteristic != null)
  82. result = await ReadCharacteristicAsync(characteristic);
  83. }
  84. }
  85. return result;
  86. }
  87. private async Task<byte[]?> ReadCharacteristicAsync(BluetoothGattCharacteristic characteristic)
  88. {
  89. if (_bluetoothGatt != null)
  90. {
  91. _readTaskCompletionSource = new TaskCompletionSource<byte[]>();
  92. if (!_bluetoothGatt.ReadCharacteristic(characteristic))
  93. {
  94. _readTaskCompletionSource.TrySetException(
  95. new InvalidOperationException("Failed to initiate characteristic read."));
  96. }
  97. return await _readTaskCompletionSource.Task;
  98. }
  99. return null;
  100. }
  101. public override void OnCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] data, GattStatus status)
  102. {
  103. base.OnCharacteristicRead(gatt, characteristic, data, status);
  104. if (status == GattStatus.Success)
  105. {
  106. Console.WriteLine("Characteristic read successfully.");
  107. _readTaskCompletionSource?.TrySetResult(data);
  108. }
  109. else
  110. {
  111. Console.WriteLine("Failed to read characteristic.");
  112. _readTaskCompletionSource?.TrySetException(new InvalidOperationException("Characteristic read failed."));
  113. }
  114. }
  115. public async Task<bool> WriteAsync(Guid serviceid, Guid characteristicid, byte[] data)
  116. {
  117. var result = false;
  118. if (_bluetoothGatt != null)
  119. {
  120. var service = _bluetoothGatt.GetService(Java.Util.UUID.FromString(serviceid.ToString()));
  121. if (service != null)
  122. {
  123. var characteristic = service.GetCharacteristic(Java.Util.UUID.FromString(characteristicid.ToString()));
  124. if (characteristic != null)
  125. result = await WriteCharacteristicAsync(characteristic, data);
  126. }
  127. }
  128. return result;
  129. }
  130. private async Task<bool> WriteCharacteristicAsync(BluetoothGattCharacteristic characteristic, byte[] data)
  131. {
  132. bool result = false;
  133. if (_bluetoothGatt != null)
  134. {
  135. _writeTaskCompletionSource = new TaskCompletionSource<bool>();
  136. _bluetoothGatt.WriteCharacteristic(characteristic, data, 2);
  137. result = await _writeTaskCompletionSource.Task;
  138. }
  139. return result;
  140. }
  141. public override void OnCharacteristicWrite(BluetoothGatt? gatt, BluetoothGattCharacteristic? characteristic, GattStatus status)
  142. {
  143. base.OnCharacteristicWrite(gatt, characteristic, status);
  144. if (status == GattStatus.Success)
  145. {
  146. Console.WriteLine("Characteristic written successfully.");
  147. _writeTaskCompletionSource?.TrySetResult(true);
  148. }
  149. else
  150. {
  151. Console.WriteLine("Failed to write characteristic.");
  152. _writeTaskCompletionSource?.TrySetException(new InvalidOperationException("Characteristic write failed."));
  153. }
  154. }
  155. public void Dispose()
  156. {
  157. try
  158. {
  159. _bluetoothGatt?.Disconnect();
  160. _bluetoothGatt?.Close();
  161. }
  162. catch (Exception ex)
  163. {
  164. Console.WriteLine($"Error during disposal: {ex.Message}");
  165. }
  166. finally
  167. {
  168. _bluetoothGatt = null;
  169. }
  170. Console.WriteLine("Resources released.");
  171. }
  172. }
  173. public class BluetoothScanManager : ScanCallback
  174. {
  175. private readonly Action<ScanResult> _onDeviceFound;
  176. private readonly Action _onScanStopped;
  177. public BluetoothScanManager(Action<ScanResult> onDeviceFound, Action onScanStopped)
  178. {
  179. _onDeviceFound = onDeviceFound;
  180. _onScanStopped = onScanStopped;
  181. }
  182. public override void OnScanResult(ScanCallbackType callbackType, ScanResult result)
  183. {
  184. base.OnScanResult(callbackType, result);
  185. _onDeviceFound?.Invoke(result);
  186. }
  187. public override void OnScanFailed(ScanFailure errorCode)
  188. {
  189. base.OnScanFailed(errorCode);
  190. _onScanStopped?.Invoke();
  191. throw new Exception($"Scan failed with error code: {errorCode}");
  192. }
  193. }
  194. public class Android_Bluetooth : IBluetooth
  195. {
  196. public Logger? Logger { get; set; }
  197. public CoreObservableCollection<IBluetoothDevice> Devices { get; private set; } = new CoreObservableCollection<IBluetoothDevice>();
  198. private readonly BluetoothLeScanner? _scanner;
  199. public event EventHandler? Changed;
  200. public Android_Bluetooth()
  201. {
  202. var _manager = Application.Context.GetSystemService(Context.BluetoothService) as BluetoothManager;
  203. var _adapter = _manager?.Adapter;
  204. _scanner = _adapter?.BluetoothLeScanner;
  205. }
  206. public static async Task<bool> IsPermitted<TPermission>() where TPermission : Permissions.BasePermission, new()
  207. {
  208. try
  209. {
  210. PermissionStatus status = await Permissions.CheckStatusAsync<TPermission>();
  211. if (status == PermissionStatus.Granted)
  212. return true;
  213. var request = await Permissions.RequestAsync<TPermission>();
  214. return request == PermissionStatus.Granted;
  215. }
  216. catch (TaskCanceledException ex)
  217. {
  218. return false;
  219. }
  220. }
  221. public async Task<bool> IsAvailable()
  222. {
  223. if (await IsPermitted<Permissions.Bluetooth>())
  224. return _scanner != null;
  225. return false;
  226. }
  227. BluetoothScanManager? _callback;
  228. public async Task<bool> StartScanningAsync(Guid serviceid)
  229. {
  230. if (await IsAvailable())
  231. {
  232. _callback = new BluetoothScanManager((d) => DoDeviceFound(d, serviceid), ScanStopped);
  233. _scanner!.StartScan(_callback);
  234. return true;
  235. }
  236. return false;
  237. }
  238. public async Task<bool> StopScanningAsync()
  239. {
  240. if (await IsAvailable())
  241. {
  242. if (_callback != null)
  243. {
  244. _scanner!.StopScan(_callback);
  245. return true;
  246. }
  247. }
  248. return false;
  249. }
  250. private void DoDeviceFound(ScanResult device, Guid serviceid)
  251. {
  252. bool bMatch = true;
  253. bMatch = false;
  254. if (device.ScanRecord?.ServiceUuids?.Any() == true)
  255. {
  256. foreach (var uuid in device.ScanRecord.ServiceUuids)
  257. {
  258. if (Guid.TryParse(uuid.ToString(), out Guid guid))
  259. bMatch = bMatch || Guid.Equals(serviceid,guid);
  260. }
  261. }
  262. if (bMatch && !Devices.Any(x => x.ID == device.Device?.Address))
  263. {
  264. var abd = new Android_BluetoothDevice(device);
  265. Devices.Add(abd);
  266. }
  267. }
  268. private void ScanStopped()
  269. {
  270. _callback = null;
  271. }
  272. public async Task<IConnectedBluetoothDevice?> Connect(IBluetoothDevice device)
  273. {
  274. if (device is Android_BluetoothDevice d && d.Scan.Device is BluetoothDevice bd)
  275. {
  276. var result = new Android_ConnectedBluetoothDevice(bd);
  277. if (await result.ConnectAsync())
  278. {
  279. await result.DiscoverServicesAsync();
  280. return result;
  281. }
  282. }
  283. return null;
  284. }
  285. public async Task<bool> Disconnect(IConnectedBluetoothDevice device)
  286. {
  287. if (device is Android_ConnectedBluetoothDevice d)
  288. d.Dispose();
  289. return await Task.FromResult(true);
  290. }
  291. }