我的 Corebluetooth 框架正在连接到多个设备

My Corebluetooth framework is connecting to multiple device

我正在使用 corebluetooth 进行一个项目 framework.When 我的中央管理器开始扫描它连接到单个外围设备的外围设备,可能在一分钟后它开始连接到具有相同 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{[=11=].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)
    }

当此代码发现外围设备时,它会尝试连接到它。我没有看到它停止扫描的任何地方,它也不会因为已连接而避免连接。

如果您不想在发现某些内容后继续扫描,请致电stopScanning()。如果您不想在已经连接(或正在连接)时连接,那么在这些情况下不要调用 connect()