2016-08-29 117 views
2

我正尝试使用RXBluetoothKit快速连接BLE设备。该装置的所有数据的命令遵循以下顺序 1.写的命令(writeWithResponse) 2.阅读来自通知的响应(在不同的特性)如何结合写入特征和特征通知使用RXBluetoothKit for RxSwift

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

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

回答

2
// 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() 
     } 
} 

你可以试试以上。这只是一个想法,你可以如何处理它。我试图评论最重要的事情。请让我知道这对你有没有用。