从CBPeripheral *获取IOBluetoothDevice *(Mac OS X)

时间:2018-03-07 04:33:21

标签: bluetooth core-bluetooth iobluetooth

我想知道是否有一种方法可以从IOBluetoothDevice *对象获取CBPeripheral *对象,因为我正在制作一个高级蓝牙控制器框架(它将基于IOBluetooth )我正在使用它,因此扫描Bluetooth ClassicBluetooth Low Energy设备。以下是一些问题:

  1. IOBluetooth允许您搜索这两个网络但由于某种原因它未显示Bluetooth Low Energy所有CoreBluetooth设备。

  2. 如果我使用CoreBluetooth搜索Bluetooth Low Energy设备,我将无法获取以后需要的地址。

  3. 那么我有什么方法可以从IOBluetoothDevice获得CBPeripheral个对象吗?

    谢谢:D

2 个答案:

答案 0 :(得分:3)

我发现我可以搜索恰好包含UUID的/Library/Preferences/com.apple.bluetooth.plist > CoreBluetoothCache及其字典DeviceAddress =地址;)。

所以我可以使用方法

获取CBPeripheral的UUID
NSString *uuid = [[<*CBPeripheral*> identifier] UUIDString]; 

然后在属性列表中查找

NSDicionary *btdict = [NSDictionary dictionaryWithContentsOfFile:@"/Library/Preferences/com.apple.bluetooth.plist"];
NSDictionary *bleDevices = [btDict objectForKey:@"CoreBluetoothCache"];
NSString *address = [[bleDevices objectForKey:uuid] objectForKey:@"DeviceAddress"];

然后使用该地址创建一个新的IOBluetoothDevice:

IOBluetoothDevice *device = [IOBluetoothDevice deviceWithAddressString:address];

就像那样简单:D

答案 1 :(得分:0)

Swift 5.3 解决方案:

fileprivate func getDeviceAddress(for cbPeripheral: CBPeripheral) -> String?
{
    if let userDefaults = UserDefaults(suiteName: "/Library/Preferences/com.apple.Bluetooth")
   {
        if  let coreBluetoothCache = userDefaults.object(forKey: "CoreBluetoothCache") as? [String : Any]
        {
            if let deviceData = coreBluetoothCache[cbPeripheral.identifier.uuidString] as? [String : Any]
            {
                return deviceData["DeviceAddress"] as? String
            }
        }
    }
        
    return nil
}

用法:

if let deviceAddress = self.getDeviceAddress(for: peripheral)
{
    if let bluetoothDevice = IOBluetoothDevice(addressString: deviceAddress)
    {
        // Do your stuff
    }
}