[英]How to write multiple commands to BLE Device
I'm working on an app which needs to get data from BLE device to show on app.我正在开发一个需要从 BLE 设备获取数据以显示在应用程序上的应用程序。 In order to get datas from BLE device I have to write certain commands like
NUM_QUEUE
, READ_ALL
etc.为了从 BLE 设备获取数据,我必须编写某些命令,例如
NUM_QUEUE
、 READ_ALL
等。
So I'm stuck here to execute all commands together;所以我被困在这里一起执行所有命令; I assigned all commands into an array and execute write function on loop by fetching each commands.
我将所有命令分配到一个数组中,并通过获取每个命令在循环中执行 write function。
But when I read value I got the value of only last command in the array.但是当我读取值时,我得到了数组中最后一个命令的值。
Here is the code:这是代码:
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let characterArray = service.characteristics as [CBCharacteristic]? {
for cc in characterArray {
myCharacteristic = cc
peripheral.readValue(for: cc)
peripheral.setNotifyValue(true, for: myCharacteristic)
writeValue()
}
}
}
func writeValue() {
if isMyPeripheralConected { //check if myPeripheral is connected to send data
let arrayCommands = ["NUM_QUEUE\r","READ_ALL\r"]
for i in 0...arrayCommands.count-1 {
let dataToSend: Data = arrayCommands[i].data(using: String.Encoding.utf8)!
myBluetoothPeripheral.writeValue(dataToSend, for: myCharacteristic, type: CBCharacteristicWriteType.withResponse)
}
} else {
print("Not connected")
}
}
I would use enum
for keeping all of the commands together.我会使用
enum
将所有命令放在一起。 Like so:像这样:
enum Command: String {
case NUM_QUEUE = "..."
case READ_ALL = "..."
This way you can also get rawValue
if you need it.这样,如果需要,您也可以获得
rawValue
。
Create an enum that has a String
raw value type and follows the CaseIterable
protocol.创建一个具有
String
原始值类型并遵循CaseIterable
协议的枚举。 This allows you to enumerate your commands using BluetoothCommand.allCases.forEach
这允许您使用
BluetoothCommand.allCases.forEach
枚举您的命令
I've also simplified your code slightly by using an anonymous argument $0
which in this case will correspond to each of your enum cases.我还通过使用匿名参数
$0
稍微简化了您的代码,在这种情况下,它将对应于您的每个枚举案例。 I also shortened String.Encoding.utf8
to just .utf8
because I believe its type can be inferred by the compiler.我还将
String.Encoding.utf8
缩短为.utf8
,因为我相信编译器可以推断出它的类型。
enum BluetoothCommand: String, CaseIterable {
case numQueue = "NUM_QUEUE\r"
case readAll = "READ_ALL\r"
}
func writeValue() {
if isMyPeripheralConected { //check if myPeripheral is connected to send data
BluetoothCommand.allCases.forEach {
let dataToSend: Data = $0.rawValue.data(using: .utf8)!
myBluetoothPeripheral.writeValue(dataToSend, for: myCharacteristic, type: .withResponse)
}
} else {
print("Not connected")
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.