連線並讀取主要值

  • 我在一個受控制的房間裡,有一個使用 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。