BLE:如何获得正确的服务 UUID 和特征 UUID?

时间:2021-01-06 00:05:59

标签: ios objective-c swift bluetooth-lowenergy

我是蓝牙连接的新手,我想在我的 iOS 项目中添加第二个设备。我已经有了一个设备,新设备与第一个非常相似,但有点不同。我有两个设备的一个进程,我没有更改很多代码,只是为新设备创造了所有价值。我的所有设备都有不同的名称和标识符,第一个设备工作正常。

为了创建 UUID 值,我使用了 UUID 生成器 (https://www.guidgenerator.com/online-guid-generator.aspx)。

class BleConstants: NSObject {
let deviceTwoServiceUUID = “59DE3994-6A63-4654-8FF0-F85C5163B2F5”
let deviceTwoFirstCharacteristicUUID = “59DE3994-6A63-4654-8FF0-F85C5163B2F6”
let deviceTwoSecondCharacteristicUUID = “59DE3994-6A63-4654-8FF0-F85C5163B2F7”
let deviceOneServiceUUID = “A6AF4483-E210-457B-B9D6-B8A621513D1D”
let deviceOneFirstCharacteristicUUID = “A6AF4483-E210-457B-B9D6-B8A621513D2D”
let deviceOneSecondCharacteristicUUID = “A6AF4483-E210-457B-B9D6-B8A621513D2D”
}

class BleManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
@objc private(set) static var sharedInstance = BleManager()
var cbManager : CBCentralManager? = nil
var currentPeripheral : CBPeripheral? = nil
var secondService : CBService? = nil
var firstService : CBService? = nil
var secondFirstCharacteristic : CBCharacteristic!
var secondSecondCharacteristic : CBCharacteristic!
var firstFirstCharacteristic : CBCharacteristic!
var firstSecondCharacteristic : CBCharacteristic!

func initCentralManager() {
    if cbManager == nil {
        cbManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey : “MyApp”, CBCentralManagerOptionShowPowerAlertKey: true])            
    }

func deinitCentralManager() {
    cbManager = nil
}

func isBluetoothAvailable() -> Bool {
    return cbManager?.state == CBManagerState.poweredOn
}

func scan() {
    if (cbManager != nil && (cbManager?.isScanning)!) {
        return
    }
    
    discoveredPeripherals.removeAll()
    
    let serviceUUIDs = [CBUUID(string: BleConstants.deviceTwoServiceUUID), CBUUID(string: BleConstants.deviceOneServiceUUID)]
    
    cbManager?.scanForPeripherals(withServices: serviceUUIDs,
                                  options: [CBCentralManagerScanOptionAllowDuplicatesKey : 1])
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    if(!discoveredPeripherals.contains(peripheral)) {
        discoveredPeripherals.append(peripheral)
    }
}

func stopScan() {
    if cbManager != nil && (cbManager?.isScanning)! {
        cbManager?.stopScan()
    }
}

func connect(peripheral: CBPeripheral) {
    if cbManager?.state == CBManagerState.poweredOn {
        if currentPeripheral == nil || currentPeripheral?.state != CBPeripheralState.connected {
            cbManager?.connect(peripheral, options: nil)
        } else {
            cbManager?.cancelPeripheralConnection(peripheral)
        }
    }
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
Device.savePeripheralString(peripheral: peripheral.identifier.uuidString)
    AutoConnect.stop()
DeviceUpdate.updateProgress = .None
Device.isDongleConnected = true
currentPeripheral = peripheral
currentPeripheral?.delegate = self
currentPeripheral?.discoverServices(nil)
disableSleep()
}

func disableSleep() {
    UIApplication.shared.isIdleTimerDisabled = true
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
 if error != nil {
        return
    }

    if let services = peripheral.services {

        for service in services {
            if service.uuid.uuidString == BleConstants.deviceTwoServiceUUID {
        Device.dongleType = port.second
                    secondService = service
                peripheral.discoverCharacteristics(nil, for: service)
        }
            if service.uuid.uuidString == BleConstants.deviceOneServiceUUID {
        Device.dongleType = port.first
                firstService = service
                peripheral.discoverCharacteristics(nil, for: service)
            } else {
                Log.bt("didDiscoverServices for peripheral not found \(peripheral.identifier.uuidString)")
            }
        }
    }
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

    for characteristic in service.characteristics! {
        if characteristic.uuid.uuidString == BleConstants.deviceOneFirstCharacteristicUUID {
     firstCharacteristic = characteristic
        }  
    else if characteristic.uuid.uuidString == BleConstants.deviceOneSecondCharacteristicUUID {
           firstSecondCharacteristic = characteristic
        else if characteristic.uuid.uuidString == BleConstants.deviceTwoFirstCharacteristicUUID {
            secondFirstCharacteristic = characteristic
        } else if characteristic.uuid.uuidString == BleConstants.deviceTwoSecondCharacteristicUUID {
    secondSecondCharacteristic = characteristic
        } else {
            Log.bt("didDiscoverCharacteristics not found \(characteristic.uuid.uuidString)")
        }
    }
    
    if Device.dongleType == .deviceTwo {
         openPortDeviceTwo()
    } else {
        openPortDeviceOne()
    }
}

}

来自日志的数据:

对于第一台设备:

  1. isBluetoothAvailable()
  2. 扫描()
  3. CentralManager(_ central: CBCentralManager, didDiscoverperipheral: CBPeripheral,advertiseData: [String : Any], rssi RSSI: NSNumber) (peripheral
  4. CentralManager(_中心:CBCentralManager,didDiscover外设:CBPeripheral,advertisingData:[String:Any],rssi RSSI:NSNumber)
  5. 扫描()
  6. CentralManager(_ central: CBCentralManager, didDiscoverperipheral: CBPeripheral,advertiseData: [String : Any], rssi RSSI: NSNumber) (peripheral )
  7. stopScan()
  8. connect(peripheral: CBPeripheral) (currentPeripheral nil, currentPeripheral nil)
  9. CentralManager(_central: CBCentralManager, didConnect 外设: CBPeripheral
  10. centralManager(_:didConnect:) - didConnectPeripheral FJ1478HJ-EH8J-6709-1FH0-1456HGJ0BC901 第二个设备
  11. 已保存PeripheralString FJ1478HJ-EH8J-6709-1FH0-1456HGJ0BC901 第二个设备
  12. Bluetooth stop() currentPeripheral 可选()
  13. disableSleep()
  14. 外设(_外设:CBPeripheral,didDiscoverServices 错误:错误?)
  15. peripheral(_:didDiscoverServices:) - 外设的 didDiscoverServices FJ1478HJ-EH8J-6709-1FH0-1456HGJ0BC901
  16. peripheral(_:didDiscoverServices:) - didDiscoverServices forperipheral.services Optional([, UUID = 设备信息>]) [, ] , isPrimary = YES, UUID = 59DE3994-6A63-4654-8FF0-F85C5163B2F5>, ])) service.uuid.uuidString 是 59DE3994-6A63-4654-8FF0-F85C5163B2F5 和 services 是 []
  17. 外设(_:didDiscoverServices:) - didDiscoverServices SecondDevice 59DE3994-6A63-4654-8FF0-F85C5163B2F5
  18. peripheral(_:didDiscoverServices:) - 未找到外围设备的 didDiscoverServices FJ1478HJ-EH8J-6709-1FH0-1456HGJ0BC901

对于第二个设备:

  1. isBluetoothAvailable()
  2. 扫描()
  3. CentralManager(_central: CBCentralManager, didDiscoverperipheral: CBPeripheral,advertiseData: [String : Any], rssi RSSI: NSNumber) (peripheral
  4. 扫描()
  5. CentralManager(_central: CBCentralManager, didDiscoverperipheral: CBPeripheral,advertiseData: [String : Any], rssi RSSI: NSNumber) (peripheral
  6. CentralManager(_中心:CBCentralManager,didDiscover外设:CBPeripheral,advertisingData:[String:Any],rssi RSSI:NSNumber)
  7. stopScan()
  8. connect(peripheral: CBPeripheral) currentPeripheral nil, currentPeripheral nil
  9. CentralManager(_central: CBCentralManager, didConnect 外设: CBPeripheral
  10. centralManager(_:didConnect:) - didConnectPeripheral H56KIL35-7835-7JKL-2B11-HJKLIYTAA400
  11. 已保存PeripheralString H56KIL35-7835-7JKL-2B11-HJKLIYTAA400
  12. 蓝牙停止() - currentPeripheral 可选()
  13. disableSleep()
  14. 外设(_外设:CBPeripheral,didDiscoverServices 错误:错误?)
  15. peripheral(_:didDiscoverServices:) - 外围 H56KIL35-7835-7JKL-2B11-HJKLIYTAA400 的 didDiscoverServices
  16. **peripheral(_:didDiscoverServices:) - 用于外设的 didDiscoverServices.services Optional([,同 : 0x281111180, isPrimary = YES, UUID = 设备信息>]) 服务是 [, 可选([, service.uuid.uuidString 为 59DE3994-6A63-4654-8FF0-F85C5163B2F5 - 与第二个设备相同,服务为 []
  17. peripheral(_:didDiscoverServices:) - didDiscoverServices ThirdDevice 59DE3994-6A63-4654-8FF0-F85C5163B2F5 - 与 secondDevice 相同
  18. peripheral(_:didDiscoverServices:) - 未找到外围设备的 didDiscoverServices H56KIL35-7835-7JKL-2B11-HJKLIYTAA400**

基于连接到我的第一个服务 UUID 和第一个特征 UUID 的第 16 步应用程序中第二个设备的日志信息,这是错误的!

你知道吗,我创建的 UUID 是否正确?

附: Android 应用在两种设备上都能正常运行。

非常感谢!

1 个答案:

答案 0 :(得分:0)

为多个 BLE 设备接收相同的服务和特征 UUID 是完全正常的,这仅意味着所有设备都提供完全相同的服务。

例如: 如果您有两个设备可以测量一个人的心率,例如智能手表,两种设备都可能提供具有相同 UUID 的心率服务。

如果您想区分设备,您可以使用您在提供的日志的第 3 步中收到的标识符