连接并读取主要值

  • 我在一个受控制的房间里,有一个使用 IBEACON 协议的单一矿工信标。
  • BLEController 需要扩展 CBPeripheralDelegate
  • 我会在搜索停止后使用第一个 BLE 进行连接。
  • 修改方法 StopSearchBLE()
class BLEController: CBCentralManagerDelegate, CBPeripheralDelegate{
//...
    func StopSearchMiniewBeacon() {
        let when = DispatchTime.now() + 5 // change 2 to desired number of seconds
        DispatchQueue.main.asyncAfter(deadline: when) {
            self.cb_manager.stopScan()
            self.cb_manager.connect(bles.first)
        }
    }
/...
}
  • 在你的 BLE 设备的文档中,你应该查找 SERVICE UUID 和 MAJOR UUID CHARACTERISTIC
var service_uuid =  CBUUID(string: "0000fff0-0000-1000-8000-00805f9b34fb")
var major_uuid =  CBUUID(string: "0000fff2-0000-1000-8000-00805f9b34fb")
func centralManager(_ central: CBCentralManager, didConnect peripheral:             
CBPeripheral) {
    peripheral.delegate = self
    peripheral.discoverServices([service_uuid])
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    print("Service: \(service)\n error: \(error)")
    peripheral.discoverCharacteristics([major_uuid], for: (peripheral.services?[0])!)
}
  • 像上面的代码一样创建变量’service_uuid’和’major_uuid’。 ‘-0000-1000-8000-00805f9b34fb’是该标准的一部分。 ‘fff0’是我的服务 UUID,‘fff2’是我的 MAJOR UUID 特性,‘0000’需要填充 4 个字节的 uuid1º块。
  • discoverCharacteristics([major_uuid],for:(peripheral.services?[0])!)将从我的设备 gatt 服务器获得主要特征,它现在将具有 NIL 作为值。
  • (peripheral.services?[0])! - 一旦我做了 peripheral.discoverServices([service_uuid]),0 beacuse 将返回一个值
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    for characteristic in service.characteristics! {
        print("Characteristic: \(characteristic)\n error: \(error)")
        if(characteristic.uuid.uuidString == "FFF2"){
            peripheral.readValue(for: characteristic)
        }
    }
}

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    print("Characteristic read: \(characteristic)\n error: \(error)")
    let major = UInt16.init(bigEndian: UInt16(data: characteristic.value!)!)
    print("major: \(major)")
}
  • 只有在调用 peripheral.readValue(for:characteristic)后才能读取特征值
  • readValue 将导致 func 外设(_ peripheral:CBPeripheral,didUpdateValueFor 特性:CBCharacteristic,错误:错误?),其数据类型为 value。