Swift:CBCentralManager 找不到任何设备

生气

我正在尝试按照此页面上的教程,列出 BLE 设备并与之通信。

与作者不同,我对制作 GUI 应用程序不感兴趣,而宁愿让它保持基于控制台。

我制作了两个文件来测试蓝牙通信,main.swift 和 BluetoothWorker.swift。

主类如下所示:

import Foundation

var worker = BluetoothWorker();
worker.findStretchSensor();

while worker.foundAddresses.isEmpty {
    print("### no devices found, sleeping");
    sleep(5);
    print("### done sleeping");
}

这是我的蓝牙课程的样子:

import Foundation

import CoreBluetooth;

class BluetoothWorker: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {

    var foundAddresses = [String]();
    var manager = CBCentralManager();
    var myPherif: CBPeripheral?;

    func findStretchSensor() {
        manager = CBCentralManager(delegate: self, queue: nil);

        print("### we are in the find sensor");
        if (myPherif != nil) {
            print("### we are canceling");
            manager.cancelPeripheralConnection(myPherif!);
        }

        print("### we are scanning for devices");
        manager.scanForPeripherals(withServices: nil, options: nil);
    }


    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        print("### we are checking the state");
        if (central.state != CBCentralManagerState.poweredOn) {
            print("### bluetooth is not available");
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("we found a device");
        if (peripheral.name != nil) {
            let message: String = "found peripheral:: " + peripheral.name!;
            foundAddresses.append(peripheral.name!);
            print(message);
        }
    }
}

我的控制台输出如下所示:

### we are in the find sensor
### we are scanning for devices
### no devices found, sleeping
### done sleeping
### no devices found, sleeping
### done sleeping
### no devices found, sleeping

我一生都无法弄清楚为什么没有列出任何设备,以及为什么委托的方法没有执行。如果我下载这个示例(它与我的蓝牙设备之一非常相似),我的设备将被识别。(注意,这个库也是基于 GUI 的)

有什么明显的我遗漏了吗?

拉尔斯·布隆伯格

我在这里看到的两件事:

  1. 你打电话worker.findStretchSensor()太早了。

你必须等到centralManagerDidUpdateState()报告central.state == CBCentralManagerState.poweredOn,即:

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    print("### we are checking the state");
    if (central.state == .poweredOn) {
        findStretchSensor()
    }
}

您错误地假设central.state在您创建CBCentralManager. 事实并非如此。接收.poweredOn状态需要一段时间

  1. 由于您正在运行一个没有 GUI 的应用程序,主队列可能不足以处理蓝牙事件,即可能没有蓝牙堆栈可以将事件分派到的事件循环。可能这就是为什么你没有接到任何电话的原因centralManagerDidUpdateState()

您是否尝试过为中央管理器创建传递队列?IE:

queue = ...
manager = CBCentralManager(delegate: self, queue: queue)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章