首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法发现任何服务,但可以连接到设备

无法发现任何服务,但可以连接到设备
EN

Stack Overflow用户
提问于 2022-02-04 23:06:15
回答 1查看 105关注 0票数 2

我能够连接到BLE设备,但是.discoverServices()不能工作。我的日志显示了一个无用的通用错误:[CoreBluetooth] XPC connection invalid

连接到它确实有效:

代码语言:javascript
复制
    func connectToPeripheral(id: Int) -> Bool {
        guard id >= 0 && id <= peripherals.count else {
            return false
        }
                
        let arrayItem = peripherals[id]
        connectedPeripheral = arrayItem.peripheral
        connectedPeripheral!.delegate = self

        myCentral.connect(connectedPeripheral!, options: nil)
        print("connected to \(arrayItem.name)")
        
        myCentral.stopScan()
        return true
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Connected to \(String(describing: peripheral.name)) \(peripheral.description)!")
        print(peripheral.services as Any)
        peripheral.discoverServices(nil) 
    }

但是这个函数永远不会被调用。为什么?

代码语言:javascript
复制
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        print("Services:")
        print(peripheral.services as Any)
    }

不知道我做错了什么,救命?

下面是完整的代码:

代码语言:javascript
复制
import Foundation
import CoreBluetooth

class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate {

    var myCentral: CBCentralManager!

    @Published var isSwitchedOn = false
    @Published var peripherals = [Peripheral]()
    @Published var connectedPeripheral: CBPeripheral?

    override init() {
        super.init()

        myCentral = CBCentralManager(delegate: self, queue: nil)
        myCentral.delegate = self
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        var peripheralName: String!
       
        if let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
            peripheralName = name
        } else {
            peripheralName = "Unknown"
        }
       
        if peripherals.contains(where: { p in p.name == peripheralName }) {
            return
        }
        
        let newPeripheral = Peripheral(id: peripherals.count, name: peripheralName, rssi: RSSI.intValue, peripheral: peripheral)
        peripherals.append(newPeripheral)
    }

    func startScanning() {
        print("startScanning")
        peripherals.removeAll()
        myCentral.scanForPeripherals(withServices: nil, options: nil)
    }

    func stopScanning() {
        print("stopScanning")
        myCentral.stopScan()
    }

    func connectToPeripheral(id: Int) -> Bool {
        guard id >= 0 && id <= peripherals.count else {
            return false
        }
                
        let arrayItem = peripherals[id]
        connectedPeripheral = arrayItem.peripheral
        connectedPeripheral!.delegate = self

        myCentral.connect(connectedPeripheral!, options: nil)
        print("connected to \(arrayItem.name)")
        
        myCentral.stopScan()
        return true
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Connected to \(String(describing: peripheral.name)) \(peripheral.description)!")
        print(peripheral.services as Any)
        peripheral.discoverServices(nil)
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        print("Services:")
        print(peripheral.services as Any)
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        print("got Characteristics...")        
    }

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        print("centralManagerDidUpdateState: poweredOn=\(central.state == .poweredOn)")
        
        if central.state == .poweredOn {
            //if it wasn't previously on, start scanning
            if !isSwitchedOn {
                isSwitchedOn = true
                startScanning()
            }
        } else {
            isSwitchedOn = false
        }
    }
}

struct Peripheral: Identifiable {
    let id: Int
    let name: String
    let rssi: Int
    let peripheral: CBPeripheral
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-07 19:22:21

我在代码中发现了两个bug。

  1. I给startScanning()打电话时,centralManagerDidUpdateState()central.state == .poweredOn一起被调用。这导致扫描在调用myCentral.connect(connectedPeripheral!, options: nil)
  2. Calling myCentral.stopScan()之后再次启动,而myCentral.connect(connectedPeripheral!, options: nil)是导致myCentral.connect(connectedPeripheral!, options: nil)的原因之一。

我不明白为什么会发生这两种情况,但修复它们使我现在可以连接并获得服务和特性!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70993815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档