protected override Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, bool allowDuplicatesKey, CancellationToken scanCancellationToken)
        {
            var hasFilter = serviceUuids?.Any() ?? false;

            DiscoveredDevices.Clear();
            _BleWatcher = new BluetoothLEAdvertisementWatcher();
            _BleWatcher.ScanningMode = BluetoothLEScanningMode.Active;
            _prevScannedDevices      = new List <ulong>();
            Trace.Message("Starting a scan for devices.");
            if (hasFilter)
            {
                //adds filter to native scanner if serviceUuids are specified
                foreach (var uuid in serviceUuids)
                {
                    _BleWatcher.AdvertisementFilter.Advertisement.ServiceUuids.Add(uuid);
                }
                Trace.Message($"ScanFilters: {string.Join(", ", serviceUuids)}");
            }
            //don't allow duplicates except for testing, results in multiple versions
            //of the same device being found
            if (allowDuplicatesKey)
            {
                _BleWatcher.Received += DeviceFoundAsyncDuplicate;
            }
            else
            {
                _BleWatcher.Received += DeviceFoundAsync;
            }
            _BleWatcher.Start();
            return(Task.FromResult(true));
        }
        private void btnWatcher_Click(object sender, RoutedEventArgs e)
        {
            if (_fWatcherStarted == false)
            {
                _publisher.Start();

                if (_publisher.Status != WiFiDirectAdvertisementPublisherStatus.Started)
                {
                    rootPage.NotifyUser("Failed to start advertisement.", NotifyType.ErrorMessage);
                    return;
                }

                DiscoveredDevices.Clear();
                rootPage.NotifyUser("Finding Devices...", NotifyType.StatusMessage);

                String deviceSelector = WiFiDirectDevice.GetDeviceSelector(
                    Utils.GetSelectedItemTag <WiFiDirectDeviceSelectorType>(cmbDeviceSelector));

                _deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector, new string[] { "System.Devices.WiFiDirect.InformationElements" });

                _deviceWatcher.Added   += OnDeviceAdded;
                _deviceWatcher.Removed += OnDeviceRemoved;
                _deviceWatcher.Updated += OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
                _deviceWatcher.Stopped += OnStopped;

                _deviceWatcher.Start();

                btnWatcher.Content = "Stop Watcher";
                _fWatcherStarted   = true;
            }
            else
            {
                _publisher.Stop();

                btnWatcher.Content = "Start Watcher";
                _fWatcherStarted   = false;

                _deviceWatcher.Added   -= OnDeviceAdded;
                _deviceWatcher.Removed -= OnDeviceRemoved;
                _deviceWatcher.Updated -= OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted -= OnEnumerationCompleted;
                _deviceWatcher.Stopped -= OnStopped;

                _deviceWatcher.Stop();

                rootPage.NotifyUser("Device watcher stopped.", NotifyType.StatusMessage);
            }
        }
Exemple #3
0
        protected override Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, bool allowDuplicatesKey, CancellationToken scanCancellationToken)
        {
            // clear out the list
            DiscoveredDevices.Clear();

            if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
            {
                StartScanningOld(serviceUuids);
            }
            else
            {
                StartScanningNew(serviceUuids);
            }

            return(Task.FromResult(true));
        }
Exemple #4
0
        protected override async Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, CancellationToken scanCancellationToken)
        {
            // Wait for the PoweredOn state
            await WaitForState(CBCentralManagerState.PoweredOn, scanCancellationToken).ConfigureAwait(false);

            Trace.Message("Adapter: Starting a scan for devices.");

            CBUUID[] serviceCbuuids = null;
            if (serviceUuids != null && serviceUuids.Any())
            {
                serviceCbuuids = serviceUuids.Select(u => CBUUID.FromString(u.ToString())).ToArray();
                Trace.Message("Adapter: Scanning for " + serviceCbuuids.First());
            }

            DiscoveredDevices.Clear();
            _centralManager.ScanForPeripherals(serviceCbuuids);
        }
        protected override async Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, bool allowDuplicatesKey, CancellationToken scanCancellationToken)
        {
            // Wait for the PoweredOn state
            await WaitForState(CBCentralManagerState.PoweredOn, scanCancellationToken).ConfigureAwait(false);

            if (scanCancellationToken.IsCancellationRequested)
            {
                throw new TaskCanceledException("StartScanningForDevicesNativeAsync cancelled");
            }

            Trace.Message("Adapter: Starting a scan for devices.");

            CBUUID[] serviceCbuuids = null;
            if (serviceUuids != null && serviceUuids.Any())
            {
                serviceCbuuids = serviceUuids.Select(u => CBUUID.FromString(u.ToString())).ToArray();
                Trace.Message("Adapter: Scanning for " + serviceCbuuids.First());
            }

            DiscoveredDevices.Clear();
            _centralManager.ScanForPeripherals(serviceCbuuids, new PeripheralScanningOptions {
                AllowDuplicatesKey = allowDuplicatesKey
            });
        }
Exemple #6
0
        protected override Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, CancellationToken scanCancellationToken)
        {
            // clear out the list
            DiscoveredDevices.Clear();

            if (serviceUuids == null || !serviceUuids.Any())
            {
                if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
                {
                    Trace.Message("Adapter < 21: Starting a scan for devices.");
                    //without filter
#pragma warning disable 618
                    _bluetoothAdapter.StartLeScan(_api18ScanCallback);
#pragma warning restore 618
                }
                else
                {
                    Trace.Message("Adapter >= 21: Starting a scan for devices.");
                    if (_bluetoothAdapter.BluetoothLeScanner != null)
                    {
                        _bluetoothAdapter.BluetoothLeScanner.StartScan(_api21ScanCallback);
                    }
                    else
                    {
                        Trace.Message("Adapter >= 21: Scan failed. Bluetooth is probably off");
                    }
                }
            }
            else
            {
                if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop)
                {
                    var uuids = serviceUuids.Select(u => UUID.FromString(u.ToString())).ToArray();
                    Trace.Message("Adapter < 21: Starting a scan for devices.");
#pragma warning disable 618
                    _bluetoothAdapter.StartLeScan(uuids, _api18ScanCallback);
#pragma warning restore 618
                }
                else
                {
                    Trace.Message("Adapter >=21: Starting a scan for devices with service Id {0}.", serviceUuids.First());

                    var scanFilters = new List <ScanFilter>();
                    foreach (var serviceUuid in serviceUuids)
                    {
                        var sfb = new ScanFilter.Builder();
                        sfb.SetServiceUuid(ParcelUuid.FromString(serviceUuid.ToString()));
                        scanFilters.Add(sfb.Build());
                    }

                    var ssb = new ScanSettings.Builder();
                    //ssb.SetCallbackType(ScanCallbackType.AllMatches);

                    if (_bluetoothAdapter.BluetoothLeScanner != null)
                    {
                        _bluetoothAdapter.BluetoothLeScanner.StartScan(scanFilters, ssb.Build(), _api21ScanCallback);
                    }
                    else
                    {
                        Trace.Message("Adapter >= 21: Scan failed. Bluetooth is probably off");
                    }
                }
            }

            return(Task.FromResult(true));
        }
Exemple #7
0
        public Adapter()
        {
            var appContext = Application.Context;

            // get a reference to the bluetooth system service
            _manager = (BluetoothManager)appContext.GetSystemService("bluetooth");


            _adapter = _manager.Adapter;

            IsBluetoothEnabled = _adapter.State == State.On;


            _gattCallback = new GattCallback(this);


            _gattCallback.DeviceConnected += (sender, e) =>
            {
                if (!IsScanning)
                {
                    DisconnectDevice(e.Device);
                    return;
                }
                cancelScan = true;

//				if (e.Device.State != DeviceState.Connected)
                if (!ContaisDevice(_connectedDevices, e.Device))
                {
                    _connectedDevices.Add(e.Device);
                    DeviceConnected(this, e);
                }
            };

            _gattCallback.DeviceDisconnected += (sender, e) =>
            {
                // TODO: remove the disconnected device from the _connectedDevices list
                // i don't think this will actually work, because i'm created a new underlying device here.
                //if(this._connectedDevices.Contains(
                var device = e.Device;
                foreach (var item in _connectedDevices)
                {
                    if (item.DeviceGUID == e.Device.DeviceGUID)
                    {
                        device = item;
                    }
                }

//				if (e.Device.State != DeviceState.Connected) {
                if (e.Device.DeviceGUID == BLEManager.SharedInstance.SelectedDevice.DeviceGUID)
                {
                    _connectedDevices.Remove(device);
                    DeviceDisconnected(this, e);
                    StopScanningForDevices();
                    DiscoveredDevices.Clear();
                }
            };

            MessagingCenter.Subscribe <AndroidBluetoothStatusMessage>(this, DroidConstant.DEVICE_BLUETOOTH_ONOFF_MESSAGE,
                                                                      sender =>
            {
                var msg            = sender;
                IsBluetoothEnabled = msg.IsEnabled;
                BluetoothStateChanged(this, null);
            });
        }