ios - 通过蓝牙接收字符串数据

标签 ios swift bluetooth core-bluetooth cbcentralmanager

我正在创建一个与单个外围设备通信的简单 BLE 应用程序。电话充当中心。我有一台 iPad,用作测试的外围设备。它有应用程序 LightBlue安装模拟外围设备。外围设备应该以这种格式发送一串数据。

TEM:25.11 | HUM:70 | PM10:43 | PM25:32

因此,我使用一项服务在 LightBlue 中创建了一个空白的虚拟外围设备。

enter image description here

enter image description here

下面是我的蓝牙连接处理代码。

import UIKit
import CoreBluetooth

class ViewController: UIViewController {

    fileprivate let serviceUUID = CBUUID(string: "19B10010-E8F2-537E-4F6C-D104768A1214")
    fileprivate let characteristicUUID = CBUUID(string: "19B10011-E8F2-537E-4F6C-D104768A1214")

    fileprivate var manager: CBCentralManager!
    fileprivate var peripheral: CBPeripheral!
    fileprivate var characteristic: CBCharacteristic!

    override func viewDidLoad() {
        super.viewDidLoad()
        manager = CBCentralManager(delegate: self, queue: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        stopScan()
    }

    fileprivate func startScan() {
        manager.scanForPeripherals(withServices: [serviceUUID], options: nil)
    }

    fileprivate func stopScan() {
        manager.stopScan()
    }

    fileprivate func disconnectFromDevice() {
        guard let peripheral = peripheral else { return }
        manager.cancelPeripheralConnection(peripheral)
    }

    fileprivate func restoreCentralManager() {
        manager.delegate = self
    }

}

// MARK: - CBCentralManagerDelegate
extension ViewController: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .unsupported:
            print("Unsupported")
        case .unauthorized:
            print("Unauthorized")
        case .poweredOn:
            print("Powered On")
            startScan()
        case .resetting:
            print("Resetting")
        case .poweredOff:
            print("Powered Off")
        case .unknown:
            print("Unknown")
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("Discovered \(String(describing: peripheral.name)) at \(RSSI)")

        if peripheral.name == nil || peripheral.name == "" {
            return
        }

        if self.peripheral == nil || self.peripheral.state == .disconnected {
            stopScan()

            self.peripheral = peripheral
            central.connect(peripheral, options: nil)
        }
    }

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        peripheral.delegate = self
        peripheral.discoverServices([serviceUUID])
    }

    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {

        self.peripheral = nil
        central.scanForPeripherals(withServices: nil, options: nil)
    }

    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        self.peripheral = nil
    }

    func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
    }
}

// MARK: - CBPeripheralDelegate
extension ViewController: CBPeripheralDelegate {
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard let services = peripheral.services else { return }
        print("No. of services: \(services.count)")

        for service in services {
            print(service.uuid)
            if service.uuid == serviceUUID {
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        guard let characteristics = service.characteristics else { return }

        for characteristic in characteristics {
            print("characteristic: \(characteristic.uuid)")
            if characteristic.uuid == characteristicUUID {
                self.characteristic = characteristic
                peripheral.setNotifyValue(true, for: characteristic)
                peripheral.readValue(for: characteristic)
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        print(error)
    }

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {        
        if characteristic.uuid == characteristicUUID {
            print("Got reply from: \(characteristic.uuid)")
            print(characteristic.value)
            if let data = characteristic.value, let string = String(data: data, encoding: String.Encoding.utf8) {
                print(string)
            } else {
                print("No response!")
            }
        }
    }

}

发现和连接部分工作得很好。问题是我没有从外围设备接收到该数据字符串。

peripheral(_:didUpdateValueFor:error:) 方法确实被触发了。我在控制台中得到 Got reply from: 19B10011-E8F2-537E-4F6C-D104768A1214 输出。然而,当我试图通过打印出 characteristic.value 来查看是否有任何数据时,它返回 nil

不确定是不是我的代码有问题。或者我错误地配置了 LightBlue 上的外围设备。 LightBlue 会自动发送数据吗?我也没有在任何地方看到任何发送按钮或任何东西。

我上传了一个演示项目 here

最佳答案

您的 LightBlue 配置显示您只能在该特定特征上写入值您还必须读取它

关于ios - 通过蓝牙接收字符串数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46537901/

相关文章:

ios - UIImageView 上的手势识别器(滑动)

swift - 将时间字符串转换为当天的 Unix 时间日期

ios - 为什么程序在登录时不执行segue?

node.js - 约翰尼五世蓝牙连接问题

ios - 获取 CFNetwork SSLHandshake 失败 (-9806) 错误

ios - 自上次 Xcode 更新以来的 "Direct comparision of a string literal"警告

ios - 代码只能在 DispatchQueue.main.async block 中工作,为什么?

ios - Swift - 从解析中接收图像并显示它们时出现问题

android - 在android中打印时如何更改字体大小?

service - Windows 10 - 后台代理/服务?