我有一个通过BLE发送以这种方式编写的消息的设备:[STX] A1 [ETX]
此设备使用C ++编写的软件,并且第三个字符是布尔值!
现在,我将使用swift通过iOS收到此消息。它可以正确接收其他传入消息,但此消息不能。
这是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);
这是我迅速收到的方法:
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
}
}
以此我可以轻松接收我的数据
var reader = MessageHelper.DataReader.init(data: receivedMessage, offset: 0)
for _ in 1...reader.data.count {
let value = reader.read()
if value == STX {
incomingMessage = ""
} else if value == ETX {
print(#function, incomingMessage)
commandSelector(message: incomingMessage)
} else {
if value == 0x01 {
incomingMessage += "1"
} else if value == 0x00 {
incomingMessage += "0"
} else {
incomingMessage += "\(Character(UnicodeScalar(value)))"
}
}
}
好!如果我需要发送相同的消息
sendMessage(message: String("\(COMMAND)\(Character(UnicodeScalar(UInt8(1))))"), withResponde: true)
我必须先将UnicodeScalar中的UInt8(1)转换为Character,仅此而已!