示例#1
0
 /// <summary>
 /// Scan for heart rate sensors.  Note that a lot of heart rate sensors do not advertise their service UUID
 /// </summary>
 /// <param name="adapter"></param>
 /// <returns></returns>
 public static IObservable <IScanResult> ScanForHeartRateSensors(this ICentralManager centralManager) => centralManager.Scan(new ScanConfig
 {
     ServiceUuids =
     {
         HeartRateServiceUuid
     }
 });
示例#2
0
        public CentralExtensionsViewModel(ICentralManager centralManager,
                                          IUserDialogs dialogs)
        {
            this.Tasks = new List <TaskViewModel>
            {
                new TaskViewModel(
                    "Scan Find Peripheral",
                    ct => centralManager
                    .ScanUntilPeripheralFound(this.PeripheralName)
                    .ToTask(ct),

                    this.WhenAny(
                        x => x.PeripheralName,
                        x => !x.GetValue().IsEmpty()
                        )
                    ),
                new TaskViewModel(
                    "Scan For Unique Peripherals",
                    ct => centralManager
                    .ScanForUniquePeripherals()
                    .ToTask(ct)
                    ),
                new TaskViewModel(
                    "Scan Interval",
                    ct => centralManager
                    .ScanInterval(
                        TimeSpan.FromSeconds(10),
                        TimeSpan.FromSeconds(10)
                        )
                    .ToTask(ct)
                    )
            };
        }
示例#3
0
        public AccessViewModel(IJobManager jobs,
                               INotificationManager notifications = null,
                               ISpeechRecognizer speech = null,
                               IGeofenceManager geofences = null,
                               IGpsManager gps = null,
                               ICentralManager bluetooth = null,
                               IBeaconManager beacons = null)
        {
            this.Append("Jobs", AccessState.Unknown, () => jobs.RequestAccess());

            if (notifications != null)
                this.Append("Notifications", AccessState.Unknown, () => notifications.RequestAccess());

            if (speech != null)
                this.Append("Speech", AccessState.Unknown, () => speech.RequestAccess().ToTask(CancellationToken.None));

            if (gps != null)
                this.Append("GPS", gps.Status, () => gps.RequestAccess(true));

            if (geofences != null)
                this.Append("Geofences", geofences.Status, () => geofences.RequestAccess());

            if (bluetooth != null)
                this.Append("BluetoothLE Central", bluetooth.Status, () => bluetooth.RequestAccess().ToTask(CancellationToken.None));

            if (beacons != null)
                this.Append("iBeacons", beacons.Status, () => beacons.RequestAccess(true));
        }
示例#4
0
 public BeaconManager(ICentralManager centralManager,
                      IMessageBus messageBus,
                      IRepository repository) : base(repository)
 {
     this.centralManager = centralManager;
     this.messageBus     = messageBus;
 }
示例#5
0
 /// <summary>
 /// This method wraps the traditional scan, but waits for the centralManager to be ready before initiating scan
 /// </summary>
 /// <param name="centralManager">The centralManager to scan with</param>
 /// <param name="restart">Stops any current scan running</param>
 /// <param name="config">ScanConfig parameters you would like to use</param>
 /// <returns></returns>
 public static IObservable <IScanResult> Scan(this ICentralManager centralManager, ScanConfig?config = null, bool restart = false)
 {
     if (restart && centralManager.IsScanning)
     {
         centralManager.StopScan(); // need a pause to wait for scan to end
     }
     return(centralManager.Scan(config));
 }
示例#6
0
 /// <summary>
 /// This will scan until the peripheral a specific peripheral is found, then cancel the scan
 /// </summary>
 /// <param name="centralManager"></param>
 /// <param name="peripheralName"></param>
 /// <param name="includeLocalName"></param>
 /// <returns></returns>
 public static IObservable <IPeripheral> ScanUntilPeripheralFound(this ICentralManager centralManager, string peripheralName, bool includeLocalName = true) => centralManager
 .Scan()
 .Where(x =>
        x.Peripheral.Name?.Equals(peripheralName, StringComparison.OrdinalIgnoreCase) ?? false ||
        (includeLocalName && (x.AdvertisementData?.LocalName?.Equals(peripheralName, StringComparison.InvariantCultureIgnoreCase) ?? false))
        )
 .Take(1)
 .Select(x => x.Peripheral);
        public PeripheralViewModel(ICentralManager centralManager)
        {
            _centralManager         = centralManager;
            PairToDeviceCommand     = new DelegateCommand(PairToDevice);
            ConnectionToggleCommand = new DelegateCommand(ConnectionToggle);

            SelectCharacteristicsCommand = new DelegateCommand <GattCharacteristicViewModel>(ReadCharacteristics);
        }
示例#8
0
        public static bool?TryOpenSettings(this ICentralManager centralManager)
        {
            if (centralManager is ICanOpenAdapterSettings settings)
            {
                return(settings.OpenSettings());
            }

            return(null);
        }
示例#9
0
 public static bool TrySetAdapterState(this ICentralManager centralManager, bool enable)
 {
     if (centralManager is ICanControlAdapterState state)
     {
         state.SetAdapterState(enable);
         return(true);
     }
     return(false);
 }
示例#10
0
 public ConnectedPeripheralsViewModel(ICentralManager centralManager)
 {
     this.Load = ReactiveCommand.CreateFromTask(async() =>
     {
         var peripherals = await centralManager.GetConnectedPeripherals();
         //peripherals.Select(x => x
         // TODO: get TBD connected devices too
     });
 }
示例#11
0
        public static AccessState TryOpenSettings(this ICentralManager centralManager)
        {
            if (centralManager is ICanOpenAdapterSettings settings)
            {
                return(settings.OpenSettings() ? AccessState.Available : AccessState.Denied);
            }

            return(AccessState.NotSupported);
        }
示例#12
0
        public AccessViewModel(IJobManager jobs,
                               INotificationManager notifications = null,
                               ISpeechRecognizer speech           = null,
                               IGeofenceManager geofences         = null,
                               IGpsManager gps           = null,
                               ICentralManager bluetooth = null,
                               IBeaconManager beacons    = null,
                               IPushManager push         = null,
                               INfcManager nfc           = null)
        {
            this.Append("Jobs", AccessState.Unknown, () => jobs.RequestAccess());

            if (notifications != null)
            {
                this.Append("Notifications", AccessState.Unknown, () => notifications.RequestAccess());
            }

            if (speech != null)
            {
                this.Append("Speech", AccessState.Unknown, () => speech.RequestAccess());
            }

            if (gps != null)
            {
                this.Append("GPS (Background)", gps.GetCurrentStatus(true), () => gps.RequestAccess(true));
            }

            if (geofences != null)
            {
                this.Append("Geofences", geofences.Status, () => geofences.RequestAccess());
            }

            if (bluetooth != null)
            {
                this.Append("BluetoothLE Central", bluetooth.Status, () => bluetooth.RequestAccess().ToTask(CancellationToken.None));
            }

            if (beacons != null)
            {
                this.Append("iBeacons (Monitoring)", beacons.GetCurrentStatus(true), () => beacons.RequestAccess(true));
            }

            if (push != null)
            {
                this.Append("Push", AccessState.Unknown, async() =>
                {
                    var status = await push.RequestAccess();
                    return(status.Status);
                });
            }

            if (nfc != null)
            {
                this.Append("NFC", AccessState.Unknown, () => nfc.RequestAccess().ToTask(CancellationToken.None));
            }
        }
示例#13
0
 public static IObservable <Beacon> ScanForBeacons(this ICentralManager centralManager, bool forMonitoring = false) => centralManager
 .Scan(new ScanConfig
 {
     //AndroidUseScanBatching = true,
     ScanType = forMonitoring
             ? BleScanType.LowPowered
             : BleScanType.Balanced
 })
 .Where(x => x.IsBeacon())
 .Select(x => x.AdvertisementData.ManufacturerData.Data.Parse(x.Rssi));
示例#14
0
        public BackgroundTask(ICentralManager centralManager, IRepository repository)
        {
            this.syncLock       = new object();
            this.centralManager = centralManager;
            this.repository     = repository;

            //this.repository.Added += (sender, args) => { };
            //this.repository.Removed += (sender, args) => { };
            //this.repository.Cleared += (sender, args) => { };
        }
示例#15
0
 public BackgroundTask(ICentralManager centralManager,
                       IBeaconManager beaconManager,
                       IRepository repository,
                       IBeaconDelegate beaconDelegate)
 {
     this.centralManager = centralManager;
     this.beaconManager  = beaconManager;
     this.repository     = repository;
     this.beaconDelegate = beaconDelegate;
     this.states         = new Dictionary <string, BeaconRegionStatus>();
 }
示例#16
0
 public BackgroundTask(ICentralManager centralManager,
                       IBeaconManager beaconManager,
                       IMessageBus messageBus,
                       IBeaconDelegate beaconDelegate)
 {
     this.centralManager = centralManager;
     this.beaconManager  = beaconManager;
     this.messageBus     = messageBus;
     this.beaconDelegate = beaconDelegate;
     this.states         = new Dictionary <string, BeaconRegionStatus>();
 }
示例#17
0
        public AdapterViewModel(ICentralManager central, INavigationService navigator)
        {
            _centralManager     = central;
            _navigator          = navigator;
            OpenSettingsCommand = new DelegateCommand(OpenSettings);
            ScanToggleCommand   = new DelegateCommand(ScanToggleAsync);

            Peripherals = new ObservableList <PeripheralItemViewModel>();

            SelectPeripheralCommand = new DelegateCommand <PeripheralItemViewModel>(SelectPeripheral);
        }
示例#18
0
 public BeaconManager(ICentralManager centralManager, IRepository repository) : base(repository)
 {
     this.centralManager = centralManager;
     //this.monitorSubject = new Subject<BeaconRegionStatusChanged>();
     this.regionStates = new Dictionary <string, BeaconRegionStatus>();
     repository
     .GetAll <BeaconRegion>()
     .ContinueWith(x =>
     {
         foreach (var region in x.Result)
         {
             this.SetRegion(region);
         }
     });
 }
        public CentralExtensionsViewModel(ICentralManager centralManager)
        {
            //centralManager.ScanInterval
            //centralManager.ScanForUniquePeripherals

            this.Tasks = new List <TaskViewModel>
            {
                new TaskViewModel(
                    "Scan Find Peripheral",
                    ct => centralManager
                    .ScanUntilPeripheralFound(this.DeviceName)
                    .ToTask(ct),

                    this.WhenAny(
                        x => x.DeviceName,
                        x => !x.GetValue().IsEmpty()
                        )
                    )
            };
        }
示例#20
0
 /// <summary>
 /// Scans only for distinct peripherals instead of repeating each peripheral scan response - this will only give you peripherals, not RSSI or ad packets
 /// </summary>
 /// <param name="centralManager"></param>
 /// <param name="config"></param>
 /// <returns></returns>
 public static IObservable <IPeripheral> ScanForUniquePeripherals(this ICentralManager centralManager, ScanConfig?config = null) => centralManager
 .Scan(config)
 .Distinct(x => x.Peripheral.Uuid)
 .Select(x => x.Peripheral);
示例#21
0
 /// <summary>
 /// This will scan until the peripheral a specific peripheral is found, then cancel the scan
 /// </summary>
 /// <param name="centralManager"></param>
 /// <param name="peripheralUuid"></param>
 /// <returns></returns>
 public static IObservable <IPeripheral> ScanUntilPeripheralFound(this ICentralManager centralManager, Guid peripheralUuid) => centralManager
 .Scan()
 .Where(x => x.Peripheral.Uuid.Equals(peripheralUuid))
 .Take(1)
 .Select(x => x.Peripheral);
示例#22
0
 public static bool CanViewPairedPeripherals(this ICentralManager centralManager) => centralManager is ICanSeePairedPeripherals;
示例#23
0
        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;
                }
            }
                );
        }
示例#24
0
 public static bool CanControlAdapterState(this ICentralManager centralManager) => centralManager is ICanControlAdapterState;
示例#25
0
 public static bool CanOpenSettings(this ICentralManager centralManager) => centralManager is ICanOpenAdapterSettings;
示例#26
0
        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);
                }
            }
                );
        }
示例#27
0
 public static IObservable <Beacon> ScanForBeacons(this ICentralManager centralManager) => centralManager
 .Scan()
 .Where(x => x.IsBeacon())
 .Select(x => x.ToBeacon());
示例#28
0
 public CharacteristicTests(ITestOutputHelper output)
 {
     this.output  = output;
     this.manager = ShinyHost.Resolve <ICentralManager>();
 }
示例#29
0
 /// <summary>
 /// Runs BLE scan for a set timespan then pauses for configured timespan before starting again
 /// </summary>
 /// <param name="centralManager"></param>
 /// <param name="scanTime"></param>
 /// <param name="scanPauseTime"></param>
 /// <param name="config"></param>
 /// <returns></returns>
 public static IObservable <IScanResult> ScanInterval(this ICentralManager centralManager,
                                                      TimeSpan scanTime,
                                                      TimeSpan scanPauseTime,
                                                      ScanConfig?config = null) => Observable.Create <IScanResult>(ob =>
示例#30
0
        public PerformanceViewModel(ICentralManager centralManager, BleCentralConfiguration configuration)
        {
            this.centralManager = centralManager;

            if (this.IsAndroid)
            {
                this.AndroidUseInternalSyncQueue = configuration.AndroidUseInternalSyncQueue;
                this.AndroidUseMainThread        = configuration.AndroidShouldInvokeOnMainThread;

                this.WhenAnyValue(x => x.AndroidUseMainThread)
                .Skip(1)
                .Subscribe(x => configuration.AndroidShouldInvokeOnMainThread = x);

                this.WhenAnyValue(x => x.AndroidUseInternalSyncQueue)
                .Skip(1)
                .Subscribe(x => configuration.AndroidUseInternalSyncQueue = x);
            }

            this.WhenAnyValue(x => x.IsRunning)
            .Skip(1)
            .Subscribe(x =>
            {
                if (!x)
                {
                    this.speedSub?.Dispose();
                }
                else
                {
                    this.speedSub = Observable.Interval(TimeSpan.FromSeconds(2)).Subscribe(_ =>
                    {
                        this.Speed = (this.bytes / 2).Bytes().Humanize("0.0");
                        Interlocked.Exchange(ref this.bytes, 0);
                    });
                }
            });

            this.Permissions = ReactiveCommand.CreateFromTask(async() =>
                                                              this.Status = await this.centralManager.RequestAccess().ToTask()
                                                              );
            this.WriteTest = this.DoWrite(true);
            this.WriteWithoutResponseTest = this.DoWrite(false);
            this.ReadTest = this.DoWork("Read", async(ch, ct) =>
            {
                var read = await ch.Read().ToTask(ct);
                return(read.Data?.Length ?? 0);
            });

            this.NotifyTest = ReactiveCommand.CreateFromTask(
                async() =>
            {
                this.IsRunning = true;
                this.Errors    = 0;
                this.Packets   = 0;

                var characteristic = await this.SetupCharacteristic(this.cancelSrc.Token);
                this.Info          = "Running Notify Test";

                this.notifySub = characteristic
                                 .Notify(true)
                                 .Where(x => x.Type == CharacteristicResultType.Notification)
                                 .Subscribe(x =>
                {
                    Interlocked.Add(ref this.bytes, x.Data?.Length ?? 0);
                    this.Packets++;
                });
            },
                this.CanRun()
                );

            this.Stop = ReactiveCommand.Create(
                () =>
            {
                this.IsRunning = false;
                this.peripheral?.CancelConnection();
                this.Info = "Test Stopped";
                this.cancelSrc?.Cancel();
                this.notifySub?.Dispose();
                this.notifySub = null;
            },
                this.WhenAny(
                    x => x.IsRunning,
                    x => x.GetValue()
                    )
                );
        }