1

我正在尝试连接到使用 BlueFruit BLE spi 模块的 Arduino 项目。尝试使用我的 iOS 应用程序连接时遇到问题。找到设备后,我尝试连接它,但状态卡在“正在连接”状态=1。这会阻止我搜索服务等,因为未达到“连接”状态这是一个代码片段......

//check state of the bluetooth on phone
func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOff{
        //TODO: ADD SAVE DATA TO REALM BEFORE DISSMISSING
        errorView.isHidden = false
    }
    if central.state == .poweredOn{
        errorView.isHidden = true
        //scan for peripherals with the service i created
        central.scanForPeripherals(withServices: nil, options: nil)
    }
}

//devices found(should only be ours because we will create Unique serviceID)
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    // get advertisement data and check to make sure the name is matching. set it as the peripheral then make connection
    if let peripheralName = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
        print("NEXT PERIPHERAL NAME: \(peripheralName)")
        print("NEXT PERIPHERAL UUID: \(peripheral.identifier.uuidString)")

    if peripheralName == nameID{
        manager.stopScan()
        self.peripheralHalo = peripheral
        peripheralHalo!.delegate = self
        manager.connect(peripheral, options: nil)

       while(peripheralHalo?.state.rawValue == 1)
       {
            if(manager.retrieveConnectedPeripherals(withServices: [serviceID]).count > 0 ){
                print("\(manager.retrieveConnectedPeripherals(withServices: [serviceID]))")
            }
        }
    }
        print("Connected!!")
    }

当我调用 manager.connect(peripheral, options: nil) 时,外围设备会尝试连接。我添加了以下 while 循环进行测试,并始终将状态显示为“正在连接”。我已经尝试过 LightBlue iOS 应用程序,我可以正确连接并接收特征值更改的通知,因此 Arduino 固件应该是好的。请帮助!!!

4

1 回答 1

1

你不想要那个while循环;这只会阻塞核心蓝牙委托线程。发出后,connect您将获得对该方法的调用。连接外围设备后,您需要调用外围设备,这将为外围设备委托方法提供回调。然后,您可以以类似的方式发现特征。didConnect CBCentralManagerDelegatediscoverServicesperipheral:didDiscoverServices:

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// get advertisement data and check to make sure the name is matching. set it as the peripheral then make connection
    if let peripheralName = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
        print("NEXT PERIPHERAL NAME: \(peripheralName)")
        print("NEXT PERIPHERAL UUID: \(peripheral.identifier.uuidString)")

        if peripheralName == nameID {
            self.peripheralHalo = peripheral
            central.stopScan()
            central.connect(peripheral, options: nil)
        }
    }
}

func centralManager(_ central: CBCentralManager, 
              didConnect peripheral: CBPeripheral) {
    print("Connected!!")
    peripheralHalo!.delegate = self
    peripheral.discoverServices([serviceID)
}

此外,如果您要存储标识要连接的外围设备的内容,我建议您使用标识符而不是名称,因为名称可以更改。

于 2016-11-28T23:21:40.103 回答