gpt4 book ai didi

swift - 如何使用 RXBluetoothKit for RxSwift 结合写入特性和特性通知

转载 作者:可可西里 更新时间:2023-11-01 01:32:02 32 4
gpt4 key购买 nike

我正在尝试使用 RXBluetoothKit 快速连接 BLE 设备。设备的所有数据命令都遵循以下顺序1.写一个命令(writeWithResponse)2.读取通知的响应(在不同的特征上)

通知数据包的数量(一个通知数据包中最多 20 个字节)将取决于命令。这将是一个固定数字,或者基本上使用通知值中的数据结束位来指示。

这可以使用 writeValue()、monitorValueUpdate() 组合来实现吗?

最佳答案

// Abstraction of your commands / results
enum Command {
case Command1(arg: Float)
case Command2(arg: Int, arg2: Int)
}

struct CommandResult {
let command: Command
let data: NSData
}

extension Command {
func toByteCommand() -> NSData {
return NSData()
}
}

// Make sure to setup notifications before subscribing to returned observable!!!
func processCommand(notifyCharacteristic: Characteristic,
_ writeCharacteristic: Characteristic,
_ command: Command) -> Observable<CommandResult> {

// This observable will take care of accumulating data received from notifications
let result = notifyCharacteristic.monitorValueUpdate()
.takeWhile { characteristic in
// Your logic which know when to stop reading notifications.
return true
}
.reduce(NSMutableData(), accumulator: { (data, characteristic) -> NSMutableData in
// Your custom code to append data?
if let packetData = characteristic.value {
data.appendData(packetData)
}
return data
})

// Your code for sending commands, flatmap with more commands if needed or do something similar
let query = writeCharacteristic.writeValue(command.toByteCommand(), type: .WithResponse)

return Observable.zip(result, query, resultSelector: { (result: NSMutableData, query: Characteristic) -> CommandResult in
// This block will be called after query is executed and correct result is collected.
// You can now return some command specific result.

return CommandResult(command: command, data: result)
})
}

// If you would like to serialize multiple commands, you can do for example:
func processMultipleCommands(notifyCharacteristic: Characteristic,
writeCharacteristic: Characteristic,
commands: [Command]) -> Observable<()> {
return Observable.from(Observable.just(commands))
// concatMap would be more appropriate, because in theory we should wait for
// flatmap result before processing next command. It's not available in RxSwift yet.
.flatMap { command in
return processCommand(notifyCharacteristic, writeCharacteristic, command)
}
.map { result in
return ()
}
}

你可以试试上面的。这只是你如何处理它的一个想法。我试图评论最重要的事情。让我知道它是否适合您。

关于swift - 如何使用 RXBluetoothKit for RxSwift 结合写入特性和特性通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39206622/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com