我正在使用corebluetooth框架进行一个项目。当我的中央管理器开始扫描外围设备时,它会在大约一分钟后连接到单个外围设备,它开始连接到具有相同UUID的多个外围设备。
有没有办法告诉设备坚持最初连接的一个外围设备? 变量
public var centralManager: CBCentralManager? = nil
public let baseLayerServices = [SkiinUUID(string: SkiinPeripheral.baseLayerService)]
@Published public var peripherals: AllPeripherals = AllPeripherals()
是否更新了状态
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
print("state: \(self.getStateString())")
if central.state == .poweredOn {
self.showStateAlert = false
if let connectedPeripherals = self.centralManager?.retrieveConnectedPeripherals(withServices: self.baseLayerServices), connectedPeripherals.count > 0 {
print("Already connected: \(connectedPeripherals.map{$0.name}), self.peripherals: \(self.peripherals)")
self.centralManager?.stopScan()
}
else {
print("scanForPeripherals")
self.centralManager?.scanForPeripherals(withServices: self.baseLayerServices, options: nil)
}
}
else {
self.showStateAlert = true
}
}
didDiscover 外设代码
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
guard peripheral.state != .connected else {
return
}
print("didDiscover: \(peripheral.name ?? peripheral.identifier.uuidString)")
self.peripherals.baseLayer.top.add(cbPeripheral: peripheral)
self.centralManager?.connect(peripheral, options: nil)
self.observe(peripheral: self.peripherals.baseLayer.top)
}