public AdapterViewModel(ICentralManager central, INavigationService navigator, IUserDialogs 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.Create( () => { var poweredOn = central.Status == AccessState.Available; if (!central.TrySetAdapterState(!poweredOn)) { 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; } } ); }
public AdapterViewModel(ICentralManager central, INavigationService navigationService, IUserDialogs dialogs) { this.SelectPeripheral = ReactiveCommand.CreateFromTask <ScanResultViewModel>( x => navigationService.Navigate( "Peripheral", ("Peripheral", x.Peripheral) ) ); this.OpenSettings = ReactiveCommand.Create(() => { if (central.Features.HasFlag(BleFeatures.OpenSettings)) { central.OpenSettings(); } else { dialogs.Alert("Cannot open bluetooth settings"); } }); this.ToggleAdapterState = ReactiveCommand.Create( () => { if (central.CanControlAdapterState()) { var poweredOn = central.Status == AccessState.Available; central.SetAdapterState(!poweredOn); } else { dialogs.Alert("Cannot change bluetooth adapter state"); } } ); this.ScanToggle = ReactiveCommand.Create( () => { if (this.IsScanning) { this.scan?.Dispose(); } else { this.Peripherals.Clear(); this.scan = central .Scan() .Buffer(TimeSpan.FromSeconds(1)) .Synchronize() .SubOnMainThread( results => { var list = new List <ScanResultViewModel>(); foreach (var result in results) { var dev = this.Peripherals.FirstOrDefault(x => x.Uuid.Equals(result.Peripheral.Uuid)); if (dev != null) { dev.TrySet(result); } else { dev = new ScanResultViewModel(); dev.TrySet(result); list.Add(dev); } } if (list.Any()) { this.Peripherals.AddRange(list); } }, ex => dialogs.Alert(ex.ToString(), "ERROR") ) .DisposeWith(this.DeactivateWith); } } ); }