寫出主要價值
- 你需要發現服務和特徵
- 在寫入之前,你不需要特徵的讀取值。
- 對於這個例子,在讀取值之後將繼續。修改 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 中註釋最後一行並重新執行應用程式,現在你將獲得新值。