Exemple #1
0
        /// <summary>
        /// Scan for devices that are not yet connected.
        /// </summary>
        /// <exception cref="System.Exception">Throws exception when trying to start scan when a scan is already running.</exception>
        /// <param name="callback"></param>
        /// <returns>Bool wheter scanning has started</returns>
        public static bool StartScanning(Action <BLEScanResult> callback)
        {
            var uniqueGuids = new List <Guid>();

            //Start scanning when adapter is powered on.
            if (CrossBleAdapter.Current.Status == AdapterStatus.PoweredOn)
            {
                //Trigger event and add to devices list
                Console.WriteLine("Started scanning");
                _currentScan = CrossBleAdapter.Current.Scan().Subscribe(result =>
                {
                    if (result.Device != null && !string.IsNullOrEmpty(result.Device.Name) && !uniqueGuids.Contains(result.Device.Uuid))
                    {
                        //Set device
                        BLEDevice device         = GetDevice(result.Device);
                        BLEScanResult scanResult = new BLEScanResult(device, result.Rssi, result.AdvertisementData);
                        if (device != null)
                        {
                            device.NeedsAuthentication = true;
                            callback(scanResult);
                        }
                        uniqueGuids.Add(result.Device.Uuid);
                    }
                });
                return(true);
            }
            return(false);
        }
        public async void WhenDeviceFound(BLEScanResult result)
        {
            Device.BeginInvokeOnMainThread(delegate {
                StatusText.Text = "Dispositivo Encontrado.";
            });

            Console.WriteLine("Device found!");

            BLEDevice          device = result.Device;
            int                Rssi   = result.Rssi;
            IAdvertisementData data   = result.AdvertisementData;

            await Task.Delay(1500);

            Windesheart.StopScanning();
            try
            {
                device.Connect(OnConnectionFinished);
            }
            catch (Exception e1)
            {
                Console.WriteLine("ERRO - - - -" + e1);
            }
        }