swiftbluetooth-lowenergycore-bluetoothcbcentralmanagerswift5

My Corebluetooth framework is connecting to multiple device


I'm working on a project with corebluetooth framework.When my central manager starts scanning for peripherals it connects to a single peripheral after sometime maybe one minute it starts connecting to multiple peripherals with same UUID.

Is there a way to tell the device to stick to one peripheral which is connected initially? Variables

public var centralManager: CBCentralManager? = nil
public let baseLayerServices = [SkiinUUID(string: SkiinPeripheral.baseLayerService)]
@Published public var peripherals: AllPeripherals = AllPeripherals()

Did update state

 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 Peripheral Code

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)
    }

Solution

  • When this code discovers a peripheral, it tries to connect to it. I don't see anywhere that it stops scanning, and it doesn't avoid connecting just because it's connected.

    If you don't want to keep scanning after you discover something, call stopScanning(). If you don't want to connect when you're already connected (or connecting), then don't call connect() in those cases.