【问题标题】:How to write multiple commands to BLE Device in Ios swift如何在 Ios swift 中向 BLE 设备写入多个命令
【发布时间】:2020-10-15 21:23:45
【问题描述】:

我正在开发一个应用程序,该应用程序需要从 ble 设备获取数据以显示在应用程序上,为了从 ble 设备获取数据,我必须编写某些命令,如 NUM_QUEUE、READ_ALL 等。所以我卡在这里一起执行所有命令,我所做的是我将所有命令分配到一个数组中,并通过获取每个命令在循环上执行写入函数,但是当我读取值时,我只得到了数组中最后一个命令的值。请帮助我读取所有命令的所有值,用数组写命令有什么问题吗,请帮忙。

这是我要编写的代码

 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")
        }
        
    }

【问题讨论】:

  • 能否请您发布您正在使用的代码?
  • 已添加,请查看

标签: ios swift xcode bluetooth-lowenergy write


【解决方案1】:

我会使用enum 将所有命令放在一起。像这样:

enum Command: String {

case NUM_QUEUE = "..."
case READ_ALL  = "..."

如果需要,也可以通过这种方式获取rawValue

【讨论】:

  • Swift 的约定是让 enum 大小写为驼峰大小写 case numQueue, readAll
  • @Daniel 谢谢丹尼尔告诉我——我真的不知道。我只是在我的项目中使用上限,这是关于使用 BLE 设备。
  • @Lilya 当你使用枚举时,你是否能够从每个命令中读取所有值
  • @iOS 在我的情况下,每个命令只有一个 rawValue 可以读取。例如,为了达到它,我使用Command.NUM_QUEUE。我也可以一次只向我的 BLE 设备写入一个命令。我只是想也许使用枚举会更好。尝试将您的命令放入枚举并像这样迭代它:simpleswiftguide.com/how-to-iterate-over-enum-cases-in-swift
【解决方案2】:

创建一个具有String 原始值类型并遵循CaseIterable 协议的枚举。这允许您使用BluetoothCommand.allCases.forEach 枚举您的命令

我还通过使用匿名参数$0 稍微简化了您的代码,在这种情况下,它将对应于您的每个枚举案例。我还将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")
    }

}

【讨论】:

    猜你喜欢
    • 2020-01-18
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多