Bluetooth.Android.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using InABox.Avalonia.Platform;
  2. using InABox.Core;
  3. using Microsoft.Maui.ApplicationModel;
  4. using Plugin.BLE;
  5. using Plugin.BLE.Abstractions;
  6. using Plugin.BLE.Abstractions.Contracts;
  7. namespace InABox.Avalonia.Platform.Android;
  8. public class Android_Bluetooth : IBluetooth
  9. {
  10. public Logger? Logger { get; set; }
  11. public async Task<bool> IsAvailable()
  12. {
  13. try
  14. {
  15. PermissionStatus status = await Permissions.CheckStatusAsync<Permissions.Bluetooth>();
  16. if (status != PermissionStatus.Granted)
  17. status = await Permissions.RequestAsync<Permissions.Bluetooth>();
  18. return status == PermissionStatus.Granted;
  19. }
  20. catch (Exception e)
  21. {
  22. Console.WriteLine(e);
  23. }
  24. return false;
  25. }
  26. public async Task<bool> WriteAsync(string macaddress, Guid serviceid, Guid characteristicid, byte[] data)
  27. {
  28. if (await IsAvailable() != true)
  29. return false;
  30. IDevice? _device = null;
  31. var adapter = CrossBluetoothLE.Current.Adapter;
  32. adapter.DeviceDiscovered += (s, e) => _device = e.Device;
  33. try
  34. {
  35. var options = new ScanFilterOptions();
  36. options.DeviceAddresses = [macaddress];
  37. options.ServiceUuids = [serviceid];
  38. await adapter.StartScanningForDevicesAsync(options, x=> true, false);
  39. }
  40. catch (Exception e)
  41. {
  42. Console.WriteLine(e);
  43. Logger?.Error(e.Message);
  44. }
  45. if (_device != null)
  46. {
  47. try
  48. {
  49. //await adapter.StopScanningForDevicesAsync();
  50. //ConnectParameters connectParameters = new ConnectParameters(true, true);
  51. await adapter.ConnectToDeviceAsync(_device);
  52. try
  53. {
  54. var service = await _device.GetServiceAsync(serviceid);
  55. var characteristic = await service.GetCharacteristicAsync(characteristicid);
  56. var bytes = await characteristic.ReadAsync();
  57. await characteristic.WriteAsync(data);
  58. }
  59. catch (Exception e)
  60. {
  61. Logger?.Error(e.Message);
  62. return false;
  63. }
  64. await adapter.DisconnectDeviceAsync(_device);
  65. return true;
  66. }
  67. catch (Exception e)
  68. {
  69. Logger?.Error(e.Message);
  70. return false;
  71. }
  72. }
  73. return false;
  74. }
  75. }