使用通用信标库扫描信标

时间:2018-12-31 17:50:05

标签: bluetooth-lowenergy ibeacon beacon ios-bluetooth

我正在尝试实现一个移动应用程序(在iPhone上),该应用程序仅扫描信标并显示每个通知。我是一个带有信标/蓝牙的菜鸟。

我使用通用信标库(https://github.com/andijakl/universal-beacon)来实现它,并附加了ios蓝牙实现。

我的问题是,即使我只有两个,我仍然收到大约12个信标添加的事件(我假设它正在接我所有其他的蓝牙设备)。我也只会在ads_received事件中收到本地名称。

我的问题是:

  1. 如何区分它是添加的信标?
  2. 如何从信标获取唯一ID和URL? (它们是kontakt信标)

感谢您的帮助。

我的信标服务:

    public BeaconService()
    {
        // get the platform-specific provider
        var provider = RootWorkItem.Services.Get<IBluetoothPacketProvider>();

        if (null != provider)
        {
            // create a beacon manager, giving it an invoker to marshal collection changes to the UI thread
            _manager = new BeaconManager(provider, Device.BeginInvokeOnMainThread);
            _manager.Start();

            _manager.BeaconAdded += _manager_BeaconAdded;
            provider.AdvertisementPacketReceived += Provider_AdvertisementPacketReceived;
        }
    }

我的ios蓝牙实现:

public class iOSBluetoothPacketProvider : CocoaBluetoothPacketProvider { }

public class CocoaBluetoothPacketProvider : NSObject, IBluetoothPacketProvider
{
    public event EventHandler<BLEAdvertisementPacketArgs> AdvertisementPacketReceived;
    public event EventHandler<BTError> WatcherStopped;

    private readonly CocoaBluetoothCentralDelegate centralDelegate;
    private readonly CBCentralManager central;

    public CocoaBluetoothPacketProvider()
    {
        Debug.WriteLine("BluetoothPacketProvider()");

        centralDelegate = new CocoaBluetoothCentralDelegate();
        central = new CBCentralManager(centralDelegate, null);
    }

    private void ScanCallback_OnAdvertisementPacketReceived(object sender, BLEAdvertisementPacketArgs e)
    {
        AdvertisementPacketReceived?.Invoke(this, e);
    }

    public void Start()
    {
        Debug.WriteLine("BluetoothPacketProvider:Start()");
        centralDelegate.OnAdvertisementPacketReceived += ScanCallback_OnAdvertisementPacketReceived;

        // Wait for the PoweredOn state

        //if(CBCentralManagerState.PoweredOn == central.State) {
        //    central.ScanForPeripherals(peripheralUuids: new CBUUID[] { },
        //                                               options: new PeripheralScanningOptions { AllowDuplicatesKey = false });
        //}
    }

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

        central.StopScan();
        WatcherStopped?.Invoke(sender: this, e: new BTError(BTError.BluetoothError.Success));
    }
}
internal class CocoaBluetoothCentralDelegate : CBCentralManagerDelegate
{
    public event EventHandler<BLEAdvertisementPacketArgs> OnAdvertisementPacketReceived;

    #region CBCentralManagerDelegate

    public override void ConnectedPeripheral(CBCentralManager central, CBPeripheral peripheral)
    {
        Debug.WriteLine($"ConnectedPeripheral(CBCentralManager central, CBPeripheral {peripheral})");
    }

    public override void DisconnectedPeripheral(CBCentralManager central, CBPeripheral peripheral, NSError error)
    {
        Debug.WriteLine($"DisconnectedPeripheral(CBCentralManager central, CBPeripheral {peripheral}, NSError {error})");
    }

    public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
    {
        Debug.WriteLine($"Cocoa peripheral {peripheral}");
        Debug.WriteLine($"Cocoa advertisementData {advertisementData}");
        Debug.WriteLine($"Cocoa RSSI {RSSI}");

        var bLEAdvertisementPacket = new BLEAdvertisementPacket()
        {
            Advertisement = new BLEAdvertisement()
            {
                LocalName = peripheral.Name,
                ServiceUuids = new List<Guid>(),
                DataSections = new List<BLEAdvertisementDataSection>(),
                ManufacturerData = new List<BLEManufacturerData>()
            },
            AdvertisementType = BLEAdvertisementType.ScanResponse,
            BluetoothAddress = (ulong)peripheral.Identifier.GetHashCode(),
            RawSignalStrengthInDBm = RSSI.Int16Value,
            Timestamp = DateTimeOffset.Now
        };

        //https://developer.apple.com/documentation/corebluetooth/cbadvertisementdataserviceuuidskey
        //if (advertisementData.ContainsKey(CBAdvertisement.DataServiceUUIDsKey))
        //{
        //    bLEAdvertisementPacket.Advertisement.ServiceUuids.Add(
        //        item: new BLEManufacturerData(packetType: BLEPacketType.UUID16List,
        //                                      data: (advertisementData[CBAdvertisement.DataServiceUUIDsKey])));
        //}

        //https://developer.apple.com/documentation/corebluetooth/cbadvertisementdataservicedatakey
        //if (advertisementData.ContainsKey(CBAdvertisement.DataServiceDataKey))
        //{
        //    bLEAdvertisementPacket.Advertisement.DataSections.Add(
        //        item: new BLEManufacturerData(packetType: BLEPacketType.ServiceData,
        //                                      data: advertisementData[CBAdvertisement.DataServiceDataKey]));
        //}

        //https://developer.apple.com/documentation/corebluetooth/cbadvertisementdatamanufacturerdatakey
        if (advertisementData.ContainsKey(CBAdvertisement.DataManufacturerDataKey))
        {
            bLEAdvertisementPacket.Advertisement.ManufacturerData.Add(
                item: new BLEManufacturerData(packetType: BLEPacketType.ManufacturerData,
                                              data: (advertisementData[CBAdvertisement.DataManufacturerDataKey]
                                                     as NSData).ToArray()));
        }

        // Missing CBAdvertisement.DataTxPowerLevelKey

        var bLEAdvertisementPacketArgs = new BLEAdvertisementPacketArgs(data: bLEAdvertisementPacket);
        OnAdvertisementPacketReceived?.Invoke(this, bLEAdvertisementPacketArgs);
    }

    public override void FailedToConnectPeripheral(CBCentralManager central, CBPeripheral peripheral, NSError error)
    {
        Debug.WriteLine($"FailedToConnectPeripheral(CBCentralManager central, CBPeripheral {peripheral}, NSError {error})");
    }

    public override void UpdatedState(CBCentralManager central)
    {
        switch (central.State)
        {
            case CBCentralManagerState.Unknown:
                Debug.WriteLine("CBCentralManagerState.Unknown");
                break;
            case CBCentralManagerState.Resetting:
                Debug.WriteLine("CBCentralManagerState.Resetting");
                break;
            case CBCentralManagerState.Unsupported:
                Debug.WriteLine("CBCentralManagerState.Unsupported");
                break;
            case CBCentralManagerState.Unauthorized:
                Debug.WriteLine("CBCentralManagerState.Unauthorized");
                break;
            case CBCentralManagerState.PoweredOff:
                Debug.WriteLine("CBCentralManagerState.PoweredOff");
                break;
            case CBCentralManagerState.PoweredOn:
                Debug.WriteLine("CBCentralManagerState.PoweredOn");
                central.ScanForPeripherals(peripheralUuids: new CBUUID[] { },
                                                           options: new PeripheralScanningOptions { AllowDuplicatesKey = true });
                break;
            default:
                throw new NotImplementedException();
        }
    }

    public override void WillRestoreState(CBCentralManager central, NSDictionary dict)
    {
        Debug.WriteLine($"WillRestoreState(CBCentralManager central, NSDictionary {dict})");
    }

    #endregion CBCentralManagerDelegate
}

1 个答案:

答案 0 :(得分:1)

因此,万一有人在寻找这个。通用信标库没有将ios数据包转换为通用数据包的ios实现。这需要实现。

  1. 如何区分它是添加的信标?

我在寻找Eddystone数据包,如果找到了,我会添加到可观察列表中。

  1. 如何从信标获取唯一ID和URL? (它们是kontakt信标)

您需要遍历与广告一起发送的adsData并创建BLEAdvertisementDataSection。将帧数据复制为NSData。