Example #1
0
 // метод проверки есть ли ещё устройства поблизости и запись их в FoundDevice
 public void Tick(object sender, EventArgs e)
 {
     progressBar1.Increment(1);
     if (info != null)
     {
         foreach (BluetoothDeviceInfo device in info)
         {
             // проверка повтора устройств в списке
             if (!FoundDevices.Items.Contains(device.DeviceName + " - " + device.DeviceAddress))
             {
                 // добавление
                 FoundDevices.Items.Add(device.DeviceName + " - " + device.DeviceAddress);
                 FoundDevices.Refresh();
                 FoundDevices.Update();
             }
         }
         // замена название кнопки
         if (Searchdevice.Text == "Start")
         {
             Searchdevice.Text = "Restart";
         }
         // активиуем кнопки
         Searchdevice.Enabled = true;
         // выключаем индексатор поиска
         Indexer.Visible        = false;
         Choosefromused.Enabled = true;
         // выключаем таймер
         timer.Stop();
         progressBar1.Visible = false;
         progressBar1.Value   = 0;
     }
 }
Example #2
0
        private async void StartScan(Double seconds)
        {
            if (IsScanning)
            {
                return;
            }

            if (!IsAdapterEnabled)
            {
                m_dialogs.Toast("Cannot start scan, Bluetooth is turned off");
                return;
            }

            StopScan();
            IsScanning     = true;
            seconds        = BleSampleAppUtils.ClampSeconds(seconds);
            m_scanCancel   = new CancellationTokenSource(TimeSpan.FromSeconds(seconds));
            m_scanStopTime = DateTime.UtcNow.AddSeconds(seconds);

            Log.Trace("Beginning device scan. timeout={0} seconds", seconds);

            RaisePropertyChanged(nameof(ScanTimeRemaining));

            Device.StartTimer(
                TimeSpan.FromSeconds(1),
                () =>
            {
                RaisePropertyChanged(nameof(ScanTimeRemaining));
                return(IsScanning);
            });

            await m_bleAdapter.ScanForBroadcasts(


                new ScanFilter().AddAdvertisedService("0000fe9a-0000-1000-8000-00805f9b34fb"),

                peripheral =>
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                {
                    var temp     = new BleDevice(peripheral);
                    var existing = FoundDevices.FirstOrDefault(d => d.Address == peripheral.Address.Select(b => b.EncodeToBase16String()).Join(":"));
                    if (existing != null)
                    {
                        existing.Update(temp.abs);
                    }
                    else
                    {
                        FoundDevices.Add(new BlePeripheralViewModel(temp));
                    }
                });
            },
                m_scanCancel.Token);

            IsScanning = false;
        }
Example #3
0
        private async void StartScan(Double seconds)
        {
            if (IsScanning)
            {
                return;
            }

            if (!IsAdapterEnabled)
            {
                m_dialogs.Toast("Cannot start scan, Bluetooth is turned off");
                return;
            }

            StopScan();
            IsScanning     = true;
            seconds        = BleSampleAppUtils.ClampSeconds(seconds);
            m_scanCancel   = new CancellationTokenSource(TimeSpan.FromSeconds(seconds));
            m_scanStopTime = DateTime.UtcNow.AddSeconds(seconds);

            Log.Trace("Beginning device scan. timeout={0} seconds", seconds);

            RaisePropertyChanged(nameof(ScanTimeRemaining));
            // RaisePropertyChanged of ScanTimeRemaining while scan is running
            Device.StartTimer(
                TimeSpan.FromSeconds(1),
                () =>
            {
                RaisePropertyChanged(nameof(ScanTimeRemaining));
                return(IsScanning);
            });

            await m_bleAdapter.ScanForBroadcasts(
                // NOTE: You can provide a scan filter to look for particular devices, e.g.:
                //new ScanFilter.Factory {AdvertisedManufacturerCompanyId = BleSampleAppUtils.COMPANY_ID_GOOGLE}.CreateFilter(),
                peripheral =>
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                {
                    var existing = FoundDevices.FirstOrDefault(d => d.Equals(peripheral));
                    if (existing != null)
                    {
                        existing.Update(peripheral);
                    }
                    else
                    {
                        FoundDevices.Add(new BlePeripheralViewModel(peripheral, m_connectionFunc));
                    }
                });
            },
                m_scanCancel.Token);

            IsScanning = false;
        }
        private async void StartScan()
        {
            Log.Debug("StartScan. BLE adapter. enabled={0}", m_adapter.IsEnabled);
            if (IsScanning)
            {
                return;
            }
            if (!m_adapter.IsEnabled)
            {
                m_dialogs.Toast("Cannot start scan, Bluetooth is turned off");
                return;
            }
            StopScan();
            IsScanning   = true;
            m_scanCancel = new CancellationTokenSource(TimeSpan.FromSeconds(30));
            await m_adapter.ScanForDevices(
                Observer.Create(
                    ( IBlePeripheral peripheral ) =>
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                {
                    var existing = FoundDevices.FirstOrDefault(d => d.Equals(peripheral));
                    if (existing != null)
                    {
                        /*
                         * Log.Trace(
                         * "Advertisement. rssi={2} name={3} address={0} id={1}",
                         * device.Address.EncodeToBase16String(),
                         * device.DeviceId,
                         * device.Rssi,
                         * device.Advertisement.DeviceName );
                         * Log.Trace(
                         * "   services={0} tx={1} service-data={2}",
                         * device.Advertisement.Services.Select( x => x.ToString() ).Join( "," ),
                         * device.Advertisement.TxPowerLevel,
                         * device.Advertisement.ServiceData.Select( x => x.Key + ":" + x.Value.EncodeToBase16String() ).Join( "," ) );
                         * Log.Trace(
                         * "   flags={0} mfg-data={1}",
                         * device.Advertisement.Flags,
                         * device.Advertisement.ManufacturerSpecificData.Select(
                         *          x => GetManufacturerName( x.Key ) + ":" + x.Value.EncodeToBase16String() ).Join( "," ) );
                         * //*/
                        existing.Update(peripheral);
                    }
                    else
                    {
                        FoundDevices.Add(new BlePeripheralViewModel(peripheral));
                    }
                });
            }), m_scanCancel.Token);

            IsScanning = false;
        }
Example #5
0
 private void Rec_BondStateChanged(object sender, BondStateChangedEventArgs e)
 {
     if (e.NewState == Bond.Bonded)
     {
         ListAdapter.Remove(e.Device.Name);
         FoundDevices.Remove(e.Device);
         Toast.MakeText(this, "Gekoppeld met " + e.Device.Name, ToastLength.Short);
     }
     else
     {
         Toast.MakeText(this, "Bezig met koppelen met " + e.Device.Name, ToastLength.Long);
     }
 }
Example #6
0
 private void Rec_DeviceFound(object sender, DeviceFoundEventArgs e)
 {
     if (e.Device == null)
     {
         return;
     }
     if (e.Device.Name == null)
     {
         return;
     }
     if (e.Device.BondState == Bond.Bonded | e.Device.BondState == Bond.Bonding)
     {
         return;
     }
     ListAdapter.Add(e.Device.Name);
     FoundDevices.Add(e.Device);
 }
        private async void StartScan(Double seconds)
        {
#if __ANDROID__
#endif
            if (IsScanning)
            {
                return;
            }

            if (!IsAdapterEnabled)
            {
                m_dialogs.Toast("Cannot start scan, Bluetooth is turned off");
                return;
            }

            StopScan();
            IsScanning     = true;
            seconds        = BleSampleAppUtils.ClampSeconds(seconds);
            m_scanCancel   = new CancellationTokenSource(TimeSpan.FromSeconds(seconds));
            m_scanStopTime = DateTime.UtcNow.AddSeconds(seconds);

            Log.Trace("Beginning device scan. timeout={0} seconds", seconds);

            RaisePropertyChanged(nameof(ScanTimeRemaining));
            // RaisePropertyChanged of ScanTimeRemaining while scan is running
            Device.StartTimer(
                TimeSpan.FromSeconds(1),
                () =>
            {
                RaisePropertyChanged(nameof(ScanTimeRemaining));
                return(IsScanning);
            });

            await m_bleAdapter.ScanForBroadcasts(
                // NOTE:
                //
                // You can provide a scan filter to look for particular devices. See Readme.md for more information
                // e.g.:
                //    new ScanFilter().SetAdvertisedManufacturerCompanyId( 224 /*Google*/ ),
                //
                // You can also specify additional scan settings like the amount of power to direct to the Bluetooth antenna:
                // e.g.:
                //    new ScanSettings()
                //    {
                //       Mode = ScanMode.LowPower,
                //       Filter = new ScanFilter().SetAdvertisedManufacturerCompanyId( 224 /*Google*/ )
                //    },
                peripheral =>
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                {
                    var existing = FoundDevices.FirstOrDefault(d => d.Equals(peripheral));
                    if (existing != null)
                    {
                        existing.Update(peripheral);
                    }
                    else
                    {
                        FoundDevices.Add(new BlePeripheralViewModel(peripheral, m_onSelectDevice));
                    }
                });
            },
                m_scanCancel.Token);

            IsScanning = false;
        }
Example #8
0
        public async void StartScan(Double seconds)
        {
            FoundDevices.Clear();
            notPairedDeviceTitle = "0";

            if (IsScanning)
            {
                return;
            }

            if (!IsAdapterEnabled)
            {
                m_dialogs.Toast("Cannot start scan, Bluetooth is turned off");
                return;
            }

            StopScan();
            IsScanning     = true;
            seconds        = BleSampleAppUtils.ClampSeconds(seconds);
            m_scanCancel   = new CancellationTokenSource(TimeSpan.FromSeconds(seconds));
            m_scanStopTime = DateTime.UtcNow.AddSeconds(seconds);



            Log.Trace("Beginning device scan. timeout={0} seconds", seconds);

            RaisePropertyChanged(nameof(ScanTimeRemaining));
            // RaisePropertyChanged of ScanTimeRemaining while scan is running
            Device.StartTimer(
                TimeSpan.FromSeconds(1),
                () =>
            {
                RaisePropertyChanged(nameof(ScanTimeRemaining));
                return(IsScanning);
            });

            await m_bleAdapter.ScanForBroadcasts(


                peripheral =>
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                {
                    var existing      = FoundDevices.FirstOrDefault(d => d.Equals(peripheral));
                    var addre         = peripheral.Address.Select(b => b.EncodeToBase16String()).Join(":");
                    var deviceModel   = App.Database.GetDevice(addre);
                    String deviceName = null;
                    if (App.Database.GetDevice(addre) != null)
                    {
                        deviceName = deviceModel.DeviceName;
                    }

                    if (existing != null)
                    {
                        existing.Update(peripheral);
                    }
                    else
                    {
                        if (peripheral.Advertisement.DeviceName != null && (deviceName != peripheral.Advertisement.DeviceName) && !IsExist(FoundDevices, addre))
                        {
                            FoundDevices.Add(new BlePeripheralViewModel(peripheral, m_onSelectDevice));
                            notPairedDeviceTitle = FoundDevices.Count.ToString();
                        }


                        if ((peripheral.Advertisement.DeviceName != null) && (deviceName == peripheral.Advertisement.DeviceName) && !IsExist(FoundConnectDevices, addre))

                        {
                            FoundConnectDevices.Add(new BlePeripheralViewModel(peripheral, m_onSelectDevice));


                            alreadyPairedDeviceTitle = FoundConnectDevices.Count.ToString();
                        }
                    }
                });
            },
                m_scanCancel.Token);

            //DeviceTitle = DeviceTitle + FoundConnectDevices.Count.ToString();

            IsScanning = false;
        }
        private async void StartScan(Double seconds)
        {
            if (IsScanning)
            {
                return;
            }

            if (!IsAdapterEnabled)
            {
                m_dialogs.Toast("Cannot start scan, Bluetooth is turned off");
                return;
            }

            StopScan();
            IsScanning     = true;
            seconds        = BleSampleAppUtils.ClampSeconds(seconds);
            m_scanCancel   = new CancellationTokenSource(TimeSpan.FromSeconds(seconds));
            m_scanStopTime = DateTime.UtcNow.AddSeconds(seconds);

            Log.Trace("Beginning device scan. timeout={0} seconds", seconds);

            RaisePropertyChanged(nameof(ScanTimeRemaining));
            // RaisePropertyChanged of ScanTimeRemaining while scan is running
            Device.StartTimer(
                TimeSpan.FromSeconds(1),
                () =>
            {
                RaisePropertyChanged(nameof(ScanTimeRemaining));
                return(IsScanning);
            });


            // 开始扫描附近的蓝牙 ble 设备.
            await m_bleAdapter.ScanForBroadcasts(
                // NOTE:
                //
                // You can provide a scan filter to look for particular devices. See Readme.md for more information
                // e.g.:
                //    new ScanFilter().SetAdvertisedManufacturerCompanyId( 224 /*Google*/ ),
                //
                // You can also specify additional scan settings like the amount of power to direct to the Bluetooth antenna:
                // e.g.:

                new ScanSettings()
            {
                Mode = ScanMode.LowPower,
                //Filter = new ScanFilter().SetAdvertisedManufacturerCompanyId(224 /*Google*/ )


                Filter = new ScanFilter()
                {
                    //只扫描 固定名字 的设备,但不知道怎么扫描 一个数组名字 的设备.
                    //AdvertisedDeviceName = "Cramer",
                },
                IgnoreRepeatBroadcasts = false
            },
                peripheral =>
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                {
                    // 扫描到设备,如果已经有了的,就更新,否则就添加.
                    var existing = FoundDevices.FirstOrDefault(d => d.Equals(peripheral));
                    if (existing != null)
                    {
                        existing.Update(peripheral);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("peripheral Name:" + peripheral.Advertisement.DeviceName);

                        FoundDevices.Add(new BlePeripheralViewModel(peripheral, m_onSelectDevice));
                    }
                });
            },
                m_scanCancel.Token);

            IsScanning = false;
        }
        protected void Discovering()
        {
            MsHid.NativeMethods.WSAStartup();
            while (discoveringThread == Thread.CurrentThread)
            {
                List <BluetoothAddress> notFoundAddresses = new List <BluetoothAddress>(lookupFoundDevices.Keys);
                foreach (ReportDevice device in lookupConnectedDevices.Values)
                {
                    notFoundAddresses.Remove(((MsBluetoothDeviceInfo)device.DeviceInfo).Address);
                }

                IEnumerable <NativeMethods.BluetoothDeviceInfo> devices;
                try
                {
                    devices = NativeMethods.GetDeviceInfos(true, true, true, true, true, 2);
                }
                catch (System.ComponentModel.Win32Exception e)
                {
                    if (e.ErrorCode == -2147467259)
                    {
                        // The dongle was not available, so try again later.
                        Thread.Sleep(1000);
                        continue;
                    }
                    else
                    {
                        throw;
                    }
                }
                foreach (NativeMethods.BluetoothDeviceInfo deviceInfo in devices)
                {
                    if (!IsWiiDevice(deviceInfo))
                    {
                        continue;
                    }
                    if (deviceInfo.connected)
                    {
                        continue;
                    }
                    if (deviceInfo.remembered)
                    {
                        NativeMethods.RemoveDevice(deviceInfo.address);
                        continue;
                    }

                    BluetoothAddress address = new BluetoothAddress(deviceInfo.address.address);
                    notFoundAddresses.Remove(address);
                    MsBluetoothDeviceInfo bluetoothDeviceInfo;
                    if (lookupFoundDevices.TryGetValue(address, out bluetoothDeviceInfo))
                    {
                        bluetoothDeviceInfo.Device = deviceInfo;
                    }
                    else
                    {
                        bluetoothDeviceInfo = new MsBluetoothDeviceInfo(address, deviceInfo);
                        FoundDevices.Add(bluetoothDeviceInfo);
                        lookupFoundDevices.Add(address, bluetoothDeviceInfo);
                        OnDeviceFound(new DeviceInfoEventArgs(bluetoothDeviceInfo));
                    }
                }

                // Remove the lost devices from the list and notify DeviceLost event.
                foreach (BluetoothAddress notFoundAddress in notFoundAddresses)
                {
                    IDeviceInfo notFoundDeviceInfo = lookupFoundDevices[notFoundAddress];
                    lookupFoundDevices.Remove(notFoundAddress);
                    foundDevices.Remove(notFoundDeviceInfo);
                    OnDeviceLost(new DeviceInfoEventArgs(notFoundDeviceInfo));
                }
                Thread.Sleep(1000);
            }
        }