写出主要价值

  • 你需要发现服务和特征
  • 在写入之前,你不需要特征的读取值。
  • 对于这个例子,在读取值之后将继续。修改 func 外设(_ peripheral:CBPeripheral,didUpdateValueFor 特性:CBCharacteristic,错误:错误?)
  • 添加变量 new_major 和 reset_characteristic
var reset_characteristic : CBCharacteristic!
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)
        }
        if(characteristic.uuid.uuidString == "FFFF"){
            reset_characteristic = characteristic
        }
    }
}
let new_major : UInt16 = 100
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.writeValue(new_major.data, for: characteristic, type: CBCharacteristicWriteType.withResponse)
}
  • 由 deafult 提供的 iPhone 将以 Little Endian 格式发送和接收字节,但我的设备 MINEW 芯片组 NRF51822 具有 ARM 存档并需要 Big Endian 格式的字节,因此我必须交换它。
  • BLE 设备文档将说明每种特性将具有哪种类型的输入和输出,以及你是否可以像上面那样阅读它(CBCharacteristicWriteType.withResponse)。
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
    print("Characteristic write: \(characteristic)\n error: \(error)")
    if(characteristic.uuid.uuidString == "FFF2"){
            print("Resetting")
            peripheral.writeValue("minew123".data(using: String.Encoding.utf8)!, for: reset_characteristic, type: CBCharacteristicWriteType.withResponse)
        }
    if(characteristic.uuid.uuidString == "FFFF"){
        print("Reboot finish")
        cb_manager.cancelPeripheralConnection(peripheral)
    }
}
  • 要更新 gatt 服务器信息,你必须以编程方式重新启动它或将数据保存到它并关闭并手动打开。
  • FFFF 是在此设备中执行此操作的特征。
  • ‘minew123’是在这种情况下重启 o 保存信息的默认密码。
  • 运行你的应用程序并观察你控制台的任何错误,我希望没有,但你不会看到新的价值。
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.writeValue(new_major.data, for: characteristic, type: CBCharacteristicWriteType.withResponse)

}

  • 最后一步是在方法 didUpdateValueFor 中注释最后一行并重新运行应用程序,现在你将获得新值。