提问者:小点点

如何在Ios swift中向BLE设备写入多个命令


我在做一个应用程序,需要从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")
        }
        
    }

共1个答案

匿名用户

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

enum Command: String {

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

这样,如果需要,还可以获得rawvalue