using InABox.Avalonia.Platform; using InABox.Core; using Microsoft.Maui.ApplicationModel; using Plugin.BLE; using Plugin.BLE.Abstractions; using Plugin.BLE.Abstractions.Contracts; namespace InABox.Avalonia.Platform.Android; public class Android_Bluetooth : IBluetooth { public Logger? Logger { get; set; } public async Task IsAvailable() { try { PermissionStatus status = await Permissions.CheckStatusAsync(); if (status != PermissionStatus.Granted) status = await Permissions.RequestAsync(); return status == PermissionStatus.Granted; } catch (Exception e) { Console.WriteLine(e); } return false; } public async Task WriteAsync(string macaddress, Guid serviceid, Guid characteristicid, byte[] data) { if (await IsAvailable() != true) return false; IDevice? _device = null; var adapter = CrossBluetoothLE.Current.Adapter; adapter.DeviceDiscovered += (s, e) => _device = e.Device; try { var options = new ScanFilterOptions(); options.DeviceAddresses = [macaddress]; options.ServiceUuids = [serviceid]; await adapter.StartScanningForDevicesAsync(options, x=> true, false); } catch (Exception e) { Console.WriteLine(e); Logger?.Error(e.Message); } if (_device != null) { try { //await adapter.StopScanningForDevicesAsync(); //ConnectParameters connectParameters = new ConnectParameters(true, true); await adapter.ConnectToDeviceAsync(_device); try { var service = await _device.GetServiceAsync(serviceid); var characteristic = await service.GetCharacteristicAsync(characteristicid); var bytes = await characteristic.ReadAsync(); await characteristic.WriteAsync(data); } catch (Exception e) { Logger?.Error(e.Message); return false; } await adapter.DisconnectDeviceAsync(_device); return true; } catch (Exception e) { Logger?.Error(e.Message); return false; } } return false; } }