问:CoreBluetooth外设:didConnect被调用两次

时间:2020-08-04 17:38:18

标签: core-bluetooth

我使用的是MacOS 10.14.6,每次我调用_centralManager?.connect一次,我都为同一设备两次调用了peripheral:didConnect。有人知道为什么吗?好像我接到2个呼叫didConnect,具体取决于我连接的设备。一些设备被调用一次,而其他设备被调用两次。我连接的设备型号不同,因此所有广告和GATT数据库数据都不同。这是我的代码:

func Init(){
    let centralQueue: DispatchQueue = DispatchQueue(label: "centralMsgQueue", attributes: .concurrent)
    let opts = [CBCentralManagerOptionShowPowerAlertKey: false]
    _centralManager = CBCentralManager(delegate: self, queue: centralQueue, options: opts)

  }


  func Open(id: Int) -> Int {
    let i = GetDevice(id: id)
    if (i != -1)
    {
        let uuid = UUID(uuidString:_deviceTable[i].uuid!);
        let data = _centralManager!.retrievePeripherals(withIdentifiers: [uuid!]) as [CBPeripheral]
        if data.count > 0 {
          _deviceTable[i]._periph = data[0]
          _deviceTable[i]._periph?.delegate = self
          _deviceTable[i].conn_status = CONN_STATUS_PENDING
          _centralManager?.connect(_deviceTable[i]._periph!, options: nil)
        }
    }
    else
    {
        return -1
    }
    return 0
  }

  func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    let i = GetDevicePeriph(per: peripheral)
    if (i != -1) {
        if (_deviceTable[i].conn_status == CONN_STATUS_PENDING)
        {
            _deviceTable[i].conn_status = CONN_STATUS_DIDCONN
            peripheral.discoverServices(nil)
        }
    }
    else {
        _centralManager?.cancelPeripheralConnection(peripheral)
    }
  } // END func centralManager(... didConnect peripheral

  func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
      let peripheralID = peripheral.identifier.uuidString
      let deviceName = (advertisementData as NSDictionary).object(forKey: CBAdvertisementDataLocalNameKey) as? String
      if (deviceName == "Test"){
        _centralManager?.stopScan()
        let dev = device(_periph: nil, uuid: peripheralID, conn_status: CONN_STATUS_DISCOVERED)
        _deviceTable.append(dev)
      }
}

func Discover() {
self._centralManager?.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey:_scanAllowDuplicates])
}

func Test() {
  Init()
  Discover()
  Thread.sleep(forTimeInterval: 5.0)
  if (_deviceTable.count > 0) {
    Open(0)}
}

0 个答案:

没有答案