Esempio n. 1
0
        public async Task StartScanning()
        {
            await WaitForState(CBCentralManagerState.PoweredOn);

            _centralManager.ScanForPeripherals(peripheralUuids: null);
            RaiseScanningStateChanged(true);
            await Task.Delay(10 *1000);

            _centralManager.StopScan();
            RaiseScanningStateChanged(false);
        }
Esempio n. 2
0
        public async void StartScanningForDevices(Guid serviceUuid)
        {
            //
            // Wait for the PoweredOn state
            //
            await WaitForState(CBCentralManagerState.PoweredOn);

            Debug.WriteLine("Adapter: Starting a scan for devices.");

            CBUUID[] serviceUuids = null; // TODO: convert to list so multiple Uuids can be detected
            if (serviceUuid != Guid.Empty)
            {
                var suuid = CBUUID.FromString(serviceUuid.ToString());
                serviceUuids = new[] { suuid };
                Debug.WriteLine("Adapter: Scanning for " + suuid);
            }

            // clear out the list
            _discoveredDevices = new List <IDevice>();

            // start scanning
            _isScanning = true;

            _central.ScanForPeripherals(serviceUuids);


            // in 20 seconds, stop the scan
            //	await Task.Delay (20000, source.Token);

            cancelScan = false;

            for (var i = 0; i < 20; i++)
            {
                if (!cancelScan)
                {
                    await Task.Delay(1000);
                }
                else
                {
                    break;
                }
            }

            // if we're still scanning
            if (_isScanning)
            {
                Console.WriteLine("BluetoothLEManager: Scan timeout has elapsed.");
                _isScanning = false;
                _central.StopScan();
                ScanTimeoutElapsed(this, new EventArgs());
            }
        }
Esempio n. 3
0
        public Task <bool> ScanDevicesAsync(Action <ScanResult> scanCallback, CancellationToken token)
        {
            if (!IsBluetoothLESupported || !IsBluetoothOn || _centralManager.IsScanning)
            {
                return(Task.FromResult(false));
            }

            _scanCallback = scanCallback;
            _centralManager.ScanForPeripherals(null, new PeripheralScanningOptions {
                AllowDuplicatesKey = true
            });

            var tcs = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);

            token.Register(() =>
            {
                lock (_lock)
                {
                    _centralManager.StopScan();
                    _scanCallback = null;
                    tcs.SetResult(true);
                }
            });

            return(tcs.Task);
        }
Esempio n. 4
0
        /// <summary>
        /// Method subscribed to a CBMCentralManager's OnDiscoveredPeripheral Event
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        private void OnDiscoveredPeripheral(Object sender, CBDiscoveredPeripheralEventArgs e)
        {
            var peripheral = e.Peripheral;

            // Get advertised data and convert to dict
            var serviceDataDict = (NSDictionary)e.AdvertisementData[CBAdvertisement.DataServiceDataKey];
            // Get keys becase keys are NSobjects and are weird to decipher, if no keys then null
            var serviceDataKeys = serviceDataDict?.Keys;


            // If the previous ID matches or the peripheral has the desired content...
            if (TemperatureSensor.Instance.UUID == peripheral.Identifier.ToString() ||
                (serviceDataKeys != null &&
                 serviceDataKeys.Length == 2 &&
                 serviceDataKeys[0].Description == Constants.HEALTH_THERMOMETER &&
                 serviceDataKeys[1].Description == Constants.BATTERY))
            {
                // Extract data
                var temperature = serviceDataDict[serviceDataKeys[0]].Description;
                temperature = Regex.Replace(temperature, "[<>]", "");
                var battery = serviceDataDict[serviceDataKeys[1]].Description;
                battery = Regex.Replace(battery, "[<>]", "");

                // Stop the scan once found
                _centralManager.StopScan();
                _SetActivePeripheral(peripheral, temperature);
            }
        }
Esempio n. 5
0
        void UpdateScan()
        {
            if (_scanners.Count == 0)
            {
                _central.StopScan();
            }
            else
            {
                HashSet <ServiceUuid> services = null;

                if (!_scanners.Any(scn => scn.Services == null))
                {
                    // all scanners want only specific services, create a union over all
                    services = new HashSet <ServiceUuid>();
                    foreach (var scn in _scanners)
                    {
                        services.UnionWith(scn.Services);
                    }
                }

                _central.ScanForPeripherals(services?.Select(uuid => CBUUID.FromBytes(uuid.Uuid.ToByteArrayBE())).ToArray(), new PeripheralScanningOptions
                {
                    AllowDuplicatesKey = true,
                });
            }
        }
Esempio n. 6
0
        void UpdatedState(object sender, EventArgs e)
        {
            switch (manager.State)
            {
            case CBCentralManagerState.PoweredOn:
                State = "Scanning...";
                manager.ScanForPeripherals((CBUUID[])null);
                break;

            case CBCentralManagerState.PoweredOff:
            case CBCentralManagerState.Resetting:
            case CBCentralManagerState.Unauthorized:
            case CBCentralManagerState.Unknown:
            case CBCentralManagerState.Unsupported:
                State = "Waiting for Bluetooth PowerOn...";
                manager.StopScan();
                break;

            default:
                State = "<unknown state>";
                break;
            }

            OnSomethingHappened();
        }
        public void Stop()
        {
            Debug.WriteLine("BluetoothPacketProvider:Stop()");
            centralDelegate.OnAdvertisementPacketReceived -= ScanCallback_OnAdvertisementPacketReceived;

            central.StopScan();
            WatcherStopped?.Invoke(sender: this, e: new BTError(BTError.BluetoothError.Success));
        }
Esempio n. 8
0
        public async Task BeginScanningForDevices()
        {
            Console.WriteLine("Begin scanning");
            mDiscoveredDevices.Clear();
            isScanning = true;
            //mCentralManager.ScanForPeripherals (peripheralUuids: null);
            mCentralManager.ScanForPeripherals((CBUUID [])null);
            //mCentralManager.ScanForPeripherals (new[] { UUID });

            await Task.Delay(10000);

            if (isScanning)
            {
                mCentralManager.StopScan();
                ScanTimeoutElapsed(this, new EventArgs());
            }
        }
Esempio n. 9
0
 public void endEnumeration()
 {
     if (isScanning)
     {
         centralManager.StopScan();
         isScanning = false;
     }
 }
Esempio n. 10
0
 public void StopScanning()
 {
     Debug.WriteLine("StopScanning");
     if (_centralManager != null && _centralManager.IsScanning)
     {
         _centralManager.StopScan();
     }
     IsScanning = false;
 }
Esempio n. 11
0
        public IEnumerable <BluetoothDevice> ScanForDevices()
        {
            _devices       = new List <BluetoothDevice>();
            _nativeDevices = new List <CBPeripheral>();
            _manager?.ScanForPeripherals(CBUUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));
            _manager?.StopScan();

            return(_devices);
        }
Esempio n. 12
0
        internal static void StopScanning()
        {
            _scanCount--;

            if (_scanCount == 0 && _manager.IsScanning)
            {
                _manager.StopScan();
            }
        }
Esempio n. 13
0
 public virtual void UpdatedState(CBCentralManager central)
 {
     if (central.State == CBCentralManagerState.PoweredOn)
     {
         centralManager.ScanForPeripherals(peripheralUuids: null, options: (NSDictionary)null);
     }
     else
     {
         centralManager.StopScan();
     }
 }
Esempio n. 14
0
        public async Task <bool> Search()
        {
            if (manager.State == CBCentralManagerState.PoweredOn)
            {
                manager.ScanForPeripherals(new CBUUID[0]);
                await Task.Delay(15000);

                manager.StopScan();
                return(await Task.FromResult(false));
            }
            return(await Task.FromResult(true));
        }
Esempio n. 15
0
        public static void Connect(CBPeripheral peripheral)
        {
            if (BleClient.peripheral != null)
            {
                return;
            }

            BleClient.peripheral = peripheral;

            manager.StopScan();
            manager.ConnectPeripheral(peripheral);
        }
Esempio n. 16
0
        void ConnectedPeripheral(object sender, CBPeripheralEventArgs e)
        {
            Console.Error.WriteLine("Connected. Discovering services.");
            central.ConnectedPeripheral -= ConnectedPeripheral;
            central.StopScan();
            connectedCbPeripheral = e.Peripheral;

            connectedCbPeripheral.DiscoveredService             += DiscoveredService;
            connectedCbPeripheral.UpdatedCharacterteristicValue += UpdatedCharacterteristicValue;
            connectedCbPeripheral.WroteCharacteristicValue      += WroteCharacteristicValue;
            connectedCbPeripheral.DiscoverServices();
        }
Esempio n. 17
0
        public async Task <bool> ConnectAsync(RomeRemoteSystem system)
        {
            _tsc = new TaskCompletionSource <bool>();

            _manager.StopScan();
            myDel.Connected = (s) =>
            {
                _tsc.TrySetResult(true);
            };
            _manager.ConnectPeripheral((CBPeripheral)system.NativeObject);

            return(await _tsc.Task);
        }
        /// <summary>
        /// Begins the scanning for bluetooth LE devices. Automatically called after 10 seconds
        /// to prevent battery drain.
        /// </summary>
        /// <returns>The scanning for devices.</returns>
        public async void BeginScanningForDevices()
        {
            Console.WriteLine("BluetoothLEManager: Starting a scan for devices.");

            // clear out the list
            _discoveredDevices = new List <CBPeripheral> ();

            // start scanning
            IsScanning = true;
            _central.ScanForPeripherals((CBUUID[])null);

            // in 10 seconds, stop the scan
            await Task.Delay(10000);

            // if we're still scanning
            if (IsScanning)
            {
                Console.WriteLine("BluetoothLEManager: Scan timeout has elapsed.");
                _central.StopScan();
                ScanTimeoutElapsed(this, new EventArgs());
            }
        }
Esempio n. 19
0
        public void Stop()
        {
            if (_centralManager == null)
            {
                // not started
                return;
            }

            _centralManager.StopScan();

            _logger.LogDebug("Scanning - stopped.");
            Covi.Features.BluetoothTracing.TracingState.Instance.SetScanningState(false);
            _enabled = false;
        }
 public override void UpdatedState(CBCentralManager manager)
 {
     if (manager.State == CBCentralManagerState.PoweredOn)
     {
         CBUUID[] cbuuids = null;
         manager.ScanForPeripherals(cbuuids);
         var timer = new Timer(30000);
         timer.Elapsed += (sender, e) => manager.StopScan();
     }
     else
     {
         Console.WriteLine("Bluetooth is not available");
     }
 }
Esempio n. 21
0
        public async Task Stop()
        {
            _centralManager.StopScan();

            foreach (var beaconRegion in _listOfCLBeaconRegion)
            {
                _locationMgr.StopRangingBeacons(beaconRegion);
                _locationMgr.StopMonitoring(beaconRegion);
            }

            _listOfCLBeaconRegion.Clear();

            _locationMgr.DidRangeBeacons -= HandleDidRangeBeacons;
            _locationMgr.StopUpdatingLocation();
        }
Esempio n. 22
0
 override public void UpdatedState(CBCentralManager mgr)
 {
     if (mgr.State == CBCentralManagerState.PoweredOn)
     {
         //Passing in null scans for all peripherals. Peripherals can be targeted by using CBUIIDs
         CBUUID[] cbuuids = new[] { CBUUID.FromString("61353090-8231-49cc-b57a-886370740041") };
         mgr.ScanForPeripherals(cbuuids); //Initiates async calls of DiscoveredPeripheral
         //Timeout after 30 seconds
         var timer = new Timer(30 * 1000);
         timer.Elapsed += (sender, e) => mgr.StopScan();
     }
     else
     {
         //Invalid state -- Bluetooth powered down, unavailable, etc.
         System.Diagnostics.Debug.WriteLine("Bluetooth is not available");
     }
 }
Esempio n. 23
0
 /// <summary>
 /// Stop scanning for devices.
 /// </summary>
 public void StopScanningForDevices()
 {
     Debug.WriteLine("StopScanningForDevices");
     if (IsScanning && _scanCancellationToken != null)
     {
         try
         {
             _scanCancellationToken.Cancel();
         }
         catch (TaskCanceledException e)
         {
             // ignored
         }
     }
     IsScanning = false;
     _centralManager.StopScan();
 }
        public void ScanForBroadcasters(CBCentralManager mgr, UIButton Scanner)
        {
            //Passing in null scans for all peripherals. Peripherals can be targeted by using CBUIIDs
            mgr.ScanForPeripherals (cbuuids); //Initiates async calls of DiscoveredPeripheral

            Scanner.SetTitle("Started scan Scan", UIControlState.Normal);
            //Timeout after 30 seconds
            var timer = new Timer (30 * 1000);

            //mgr.StopScan ();

            timer.Elapsed += (sender, e) => {
                Console.WriteLine("Stopping scan");
                mgr.StopScan ();
                Console.WriteLine("Scan stopped");
                Scanner.SetTitle("Stopped Scan", UIControlState.Normal);
            };
        }
Esempio n. 25
0
 protected override void StopScan()
 {
     SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(() =>
     {
         try
         {
             _bluetoothCentralManager?.StopScan();
         }
         catch (Exception ex)
         {
             SensusServiceHelper.Get().Logger.Log("Exception while stopping scanning:  " + ex.Message, LoggingLevel.Normal, GetType());
         }
         finally
         {
             _bluetoothCentralManager = null;
         }
     });
 }
 override public void UpdatedState(CBCentralManager mgr)
 {
     if (mgr.State == CBCentralManagerState.PoweredOn)
     {
         Console.WriteLine("Bluetooth is available");
         //Passing in null scans for all peripherals. Peripherals can be targeted by using CBUIIDs
         CBUUID[] cbuuids = null;
         mgr.ScanForPeripherals(cbuuids);     //Initiates async calls of DiscoveredPeripheral
                                              //Timeout after 30 seconds
         var timer = new Timer(30 * 1000);
         timer.Elapsed += (sender, e) => mgr.StopScan();
     }
     else
     {
         //Invalid state -- Bluetooth powered down, unavailable, etc.
         System.Console.WriteLine("Bluetooth is not available");
     }
 }
Esempio n. 27
0
        public async Task ScanForDevices(CBCentralManager manager)
        {
            if (manager.State == CBCentralManagerState.PoweredOn)
            {
                //Passing in null scans for all peripherals. Peripherals can be targeted by using CBUIIDs
                CBUUID[] cbuuids = null;
                manager.ScanForPeripherals(cbuuids);

                await Task.Delay((int)_scanTimeout.TotalMilliseconds);

                manager.StopScan();

                _isScanning = false;
                _scanForDevicesTCS.SetResult(_discoveredDevices);
            }
            else
            {
                Console.WriteLine("Bluetooth is not available");
                _scanForDevicesTCS.SetException(new Exception("Bluetooth is not available"));
            }
        }
Esempio n. 28
0
        protected override async Task ScanAsync(CancellationToken cancellationToken)
        {
            try
            {
                // start a fresh manager delegate to collect/read results
                _bluetoothCentralManagerDelegate = new iOSBluetoothDeviceProximityProbeCentralManagerDelegate(_deviceIdService, _deviceIdCharacteristic, this);

                // initialize manager, which starts scan.
                _bluetoothCentralManager = new CBCentralManager(_bluetoothCentralManagerDelegate,
                                                                new DispatchQueue("ble"),
                                                                NSDictionary.FromObjectAndKey(NSNumber.FromBoolean(false), CBCentralManager.OptionShowPowerAlertKey));  // the base class handles prompting using to turn on bluetooth and stops the probe if the user does not.

                TaskCompletionSource <bool> scanCompletionSource = new TaskCompletionSource <bool>();

                cancellationToken.Register(() =>
                {
                    try
                    {
                        _bluetoothCentralManager.StopScan();
                    }
                    catch (Exception ex)
                    {
                        SensusServiceHelper.Get().Logger.Log("Exception while stopping scan:  " + ex.Message, LoggingLevel.Normal, GetType());
                    }
                    finally
                    {
                        _bluetoothCentralManager = null;
                        scanCompletionSource.TrySetResult(true);
                    }
                });

                await scanCompletionSource.Task;
            }
            catch (Exception ex)
            {
                SensusServiceHelper.Get().Logger.Log("Exception while scanning:  " + ex.Message, LoggingLevel.Normal, GetType());
            }
        }
Esempio n. 29
0
 protected override void StopScanNative()
 {
     _centralManager.StopScan();
 }
Esempio n. 30
0
 public void StopScan()
 {
     _CentralManager.StopScan();
 }
Esempio n. 31
0
 public void StopS(String d)
 {
     Console.WriteLine("From " + d);
     manager.StopScan();
     Console.WriteLine("Scan is stopped!!!");
 }