ios 如何在Swift中向BLE设备发送json命令并获得相同命令的响应?

jjhzyzn0  于 2023-06-25  发布在  iOS
关注(0)|答案(1)|浏览(145)

我是BLE设备集成的新手。我已经实现了与BLE设备连接的代码,它已经成功连接,但现在我想传递自定义命令从该设备获取数据。
下面是需要传递给BLE设备的Json。

获取设备电量。

应用程序到设备:

{"cmd": "getBatteryLevel"}

设备到应用程序(OK响应):

{"cmd": "getBatteryLevel", "response":100}

我试过下面。但这并不奏效。

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    
    guard let characteristics = service.characteristics else { return }
    
    for characteristic in characteristics {
        if characteristic.properties.contains(.write) && !isValueWritten {
            // Save the characteristic for later use
            self.characteristic = characteristic
            guard let data = self.viewModel.setBLELightCommand() else { return
                print("Invalid data")
            }
            
            peripheral.writeValue(data, for: characteristic, type: .withResponse)
        }
    }
}

func convertJsonDictToData(_ dict:[String:Any])->Data?{
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
        // here "jsonData" is the dictionary encoded in JSON data
        guard let jsonString = String(data: jsonData, encoding: .utf8), let data = jsonString.data(using: .utf8) else {
            return nil
        }
        return data
        
    } catch {
        print(error.localizedDescription)
        return nil
    }
}

func setBLELightCommand()->Data?{
    let setLightCommand = [
        "cmd" : "setLight",
        "channel" : "0",
        "brightness" : "50",
        "state" : "ON"
    ]
    return convertJsonDictToData(setLightCommand)
}
0md85ypi

0md85ypi1#

BLE设备通常不会以您所描述的方式工作。通常,BLE设备发布可以从其读取的多个值。电池电量可能是这些值之一。每个值都被称为一个“特性”,您可以订阅对该特性的更改。因此,在您的情况下,您将订阅电池电量的更改,并且每次电池电量更改时,您的应用都会收到通知。
也就是说,如果你的描述是正确的,那么你的设备似乎使用一个特征作为文本字符串来向设备写入命令,另一个字符串特征被告知响应。根据接口文档,确定这些特征。
订阅关于“已读”特征的通知。每次该特征发生变化时,都会调用您的例程。处理在上面收到的字符串。
然后将您的JSON字符串命令写入“write”特征(文档中提到的那个;而不仅仅是具有“写入”能力的所有这些设备)。确保字符串不长于BLE字符串的最大长度。

相关问题