简体   繁体   中英

Bluetooth LE scanner Xamarin Android

What I want to do with my application is to be able to read the characteristics of the scanned devices. I'm able to scan devices, but the scan will keep taking in whatever it finds. So I would like to have an filter for that as well. An attached picture of my results are located below my codes.

Here are my codes

using Robotics.Mobile.Core.Bluetooth.LE;
using Adapter = Robotics.Mobile.Core.Bluetooth.LE.Adapter;

var appContext = Application.Context;
            _manager = (BluetoothManager)appContext.GetSystemService(BluetoothService); // ("bluetooth");
            _adapter = _manager.Adapter;

            _bleAdapter = new Adapter();
            _bleAdapter.DeviceDiscovered += _bleAdapter_DeviceDiscovered;
            _bleAdapter.ScanTimeoutElapsed += _bleAdapter_ScanTimeoutElapsed;
        }

        private void _bleAdapter_ScanTimeoutElapsed(object sender, EventArgs e)
        {
            _bleAdapter.StopScanningForDevices();
            DisplayInformation("Bluetooth scan timeout elapsed, no ble devices were found");
        }

        private void _bleAdapter_DeviceDiscovered(object sender, DeviceDiscoveredEventArgs e)
        {
            var msg = string.Format(@"Device found: {0}
  {1} - {2}", e.Device.Name, e.Device.ID, e.Device.Rssi);
            DisplayInformation(msg);
        }

        private void ButtonScanBleClick(object sender, EventArgs e)
        {
            if (!_bleAdapter.IsScanning)
                _bleAdapter.StartScanningForDevices();
        }

        private void DisplayInformation(string line)
        {
            _textboxResults.Text = $"{line}\r\n{_textboxResults.Text}";
            Console.WriteLine(line);
        }

Picture of my output result Here

If I understand well, you want some filter for found devices. You have to write a bluetooth scanner callback, and then something like this:

in callback:

public void OnLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
        {
            if (device.Name != null)
            {
                EventScanDevice(device, rssi);                
            }
        }

in MainActivity:

List<string> scanList;

private void Scanner_EventScanDevice(BluetoothDevice device, int rssi)
{
 if (!scanList.Contains(device.Name))
 {
      scanList.Add(device.Name + ", RSSI = " + rssi.ToString());
              
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM