C++ Swift通过BLE从设备接收数据
我有一个设备,它通过BLE传输一条消息,该消息是这样组成的:[STX]A1[ETX]C++ Swift通过BLE从设备接收数据,c++,swift,boolean,bluetooth-lowenergy,C++,Swift,Boolean,Bluetooth Lowenergy,我有一个设备,它通过BLE传输一条消息,该消息是这样组成的:[STX]A1[ETX] 此设备使用C++编写的软件,第三字符为布尔值!p> 现在,我将通过iOS使用swift接收此消息。它接收到的其他传入消息正确,但此消息不正确 这是C++中的一种方法: isModeOn = (byte)data[1] == 1 ? true : false; //Send message by BLE (by Serial) Serial3.write(STX); Serial3.write(GF); Ser
此设备使用C++编写的软件,第三字符为布尔值!p> 现在,我将通过iOS使用swift接收此消息。它接收到的其他传入消息正确,但此消息不正确
这是C++中的一种方法:
isModeOn = (byte)data[1] == 1 ? true : false;
//Send message by BLE (by Serial)
Serial3.write(STX);
Serial3.write(GF);
Serial3.write(isModeOn);
Serial3.write(ETX);
这是我在swift中的方法,接收:
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print(#function)
var receivedMessage: String
if characteristic.uuid == BLE_RX_UUID {
receivedMessage = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue)! as String
processMessage(receivedMessage: "\(receivedMessage as String)")
}
}
有人能帮我吗
更新!
我发现这种方法:
//Lettura fecilitata dei NSData
struct DataReader {
var data: Data
var offset: Int = 0
mutating func read() -> UInt8 {
let result = data[offset]
offset += MemoryLayout<UInt8>.size
return result
}
mutating func read2() -> UInt16 {
let subdata = data.subdata(in: offset..<offset+MemoryLayout<UInt16>.size)
let result: UInt16 = subdata.withUnsafeBytes {(bytes: UnsafePointer<UInt16>) in
bytes.pointee.littleEndian
}
offset += MemoryLayout<UInt16>.size
return result
}
}
好的!如果我需要发送同样的信息
sendMessage(message: String("\(COMMAND)\(Character(UnicodeScalar(UInt8(1))))"), withResponde: true)
我必须在UnicodeScalar中转换UInt8(1),然后转换字符,就这样 您如何知道收到的消息不正确?您是否可以向我们显示错误消息?打印(characteristic.value!as NSData)会得到什么结果?我收到[STX]A\0[ETX],然后是4个字符,但\0它应该是1或0(分别为true和false)。我不知道如何格式化此邮件。。。我可以用字节数组格式化吗?怎么用?我希望避免将消息转换为字符串……我找到了一种解码接收到的消息的方法
sendMessage(message: String("\(COMMAND)\(Character(UnicodeScalar(UInt8(1))))"), withResponde: true)