/// <summary> /// Инициализация Bluetooth-модуля /// </summary> /// <returns></returns> public BLE_Status BLE_Init() { BluetoothClient _bluetoothClient = BluetoothClient.Instance; _bluetoothClient.Initialize(); if (_bluetoothClient.Adapter == null) { return(BLE_Status.BT_NotAwailable); //Bluetooth не поддерживается на этом устройстве } if (_bluetoothClient.Adapter.IsEnabled == false) { return(BLE_Status.BT_IsSwitchOff); //Bluetooth выключен } if (_bluetoothClient.IsBLEEnabled == false) { return(BLE_Status.BLE_NotAwailable); //Bluetooth Low Energy не поддерживается на этом устройстве } if (_bluetoothClient.IsInitialized == false) { return(BLE_Status.NotConnect); //Bluetooth Уже инициализирован } Status = BLE_Status.NotConnect; _scanner = new BluetoothDeviceScanner(_bluetoothClient.Adapter, (BluetoothDevice dev) => { if (DeviceList.All(d => !d.Address.Equals(dev.Address, StringComparison.OrdinalIgnoreCase))) { if (dev.Name != null) { DeviceList.Add(dev); onDeviceFound?.Invoke(new BLE_Device_Info() { Name = dev.Name, Address = dev.Address }); } } }); return(BLE_Status.NotConnect); }
/// <summary> /// Подключение к девайсу /// </summary> /// <param name="action"></param> public void Connect(Action <bool> action) { //Callback hell! _connectionHandler = BluetoothClient.Instance.ConnectionHandler; if (_connectionHandler.IsConnected) { return; } var client = BluetoothClient.Instance; _connectionHandler.Connect(device, (ProfileState profileState) => { switch (profileState) { case ProfileState.Connected: {//Подключились _connectionHandler.DiscoverServices(status => { if (status == GattStatus.Success) {//Получен список сервисов _characteristic = GetCharacteristic(GetServices()); var notify = new DeviceNotifyingHandler(_connectionHandler.GattValue, GattClientObserver.Instance); notify.Subscribe(_characteristic, (bool notifyStatus) => { if (notifyStatus == true) {//Нотификация пройдена _writingHandler = new DeviceWritingHandler(_connectionHandler.GattValue, GattClientObserver.Instance); _writingHandler.ClearAllReadEvents(); _writingHandler.ReceivedReadResponce += _writingHandler_ReceivedReadResponce; Status = BLE_Status.Connect; RxPacks.Clear(); action?.Invoke(true); } else {//Если нотификация не пройдена, то делать нам тут нечего и мы отключаемся от девайса action?.Invoke(false); } notify.Dispose();//при любом результате выходим так }); } else { action?.Invoke(false); } }); break; } case ProfileState.Disconnected: { Status = BLE_Status.NotConnect; action?.Invoke(false); break; } default: { action?.Invoke(false); break; } } }); //==================================== IEnumerable <BluetoothGattService> GetServices() { var filterUuid = new[] { UUID.FromString("00001800-0000-1000-8000-00805F9B34FB"), UUID.FromString("00001801-0000-1000-8000-00805F9B34FB"), UUID.FromString("7905F431-B5CE-4E99-A40F-4B1E122D00D0") }; return(_connectionHandler?.GetServiceList().Where(s => filterUuid.All(uuid => !uuid.Equals(s.Uuid)))); } BluetoothGattCharacteristic GetCharacteristic(IEnumerable <BluetoothGattService> serviceList) { var uuid = UUID.FromString("49535343-1e4d-4bd9-ba61-23c647249616"); var service = serviceList.First(s => s.Characteristics.Any(ch => ch.Uuid.Equals(uuid))); return(service.Characteristics.First(ch => ch.Uuid.Equals(uuid))); } //==================================== }