async Task SetAdapter() { var poweredOn = _centralManager.Status == AccessState.Available; if (!poweredOn && !_centralManager.TrySetAdapterState(true)) { await App.Current.MainPage.DisplayAlert("Cannot change bluetooth adapter state", "", "Ok"); } if (poweredOn) { GetConnectedDevices(); } }
public AdapterViewModel(IBleManager central, INavigationService navigator, IDialogs dialogs) { this.CanControlAdapterState = central.CanControlAdapterState(); this.WhenAnyValue(x => x.SelectedPeripheral) .Skip(1) .Where(x => x != null) .SubOnMainThread(x => navigator.Navigate("Peripheral", ("Peripheral", x.Peripheral))); this.ToggleAdapterState = ReactiveCommand.CreateFromTask( async() => { var poweredOn = central.Status == AccessState.Available; if (!central.TrySetAdapterState(!poweredOn)) { await dialogs.Alert("Cannot change bluetooth adapter state"); } } ); this.ScanToggle = ReactiveCommand.Create( () => { if (this.IsScanning) { this.IsScanning = false; this.scan?.Dispose(); } else { this.Peripherals.Clear(); this.scan = central .Scan() .Buffer(TimeSpan.FromSeconds(1)) .Synchronize() .SubOnMainThread( results => { var list = new List <PeripheralItemViewModel>(); foreach (var result in results) { var peripheral = this.Peripherals.FirstOrDefault(x => x.Equals(result.Peripheral)); if (peripheral == null) { peripheral = list.FirstOrDefault(x => x.Equals(result.Peripheral)); } if (peripheral != null) { peripheral.Update(result); } else { peripheral = new PeripheralItemViewModel(result.Peripheral); peripheral.Update(result); list.Add(peripheral); } } if (list.Any()) { this.Peripherals.AddRange(list); } }, ex => dialogs.Alert(ex.ToString(), "ERROR") ) .DisposeWith(this.DeactivateWith); this.IsScanning = true; } } ); }