【发布时间】:2018-09-04 06:43:41
【问题描述】:
我正在通过 Hm10 从滑块和按钮向 Arduino 发送数据,但问题是我的字符串被分成两部分读取,它从倒数第二个特征划分为新的行字符串。
func writeValue(data: String){
let valueString = (data as NSString).data(using: String.Encoding.utf8.rawValue)
print("data string is" , data)
//change the "data" to valueString
if let blePeripheral = blePeripheral{
if let txCharacteristic = txCharacteristic {
blePeripheral.writeValue(valueString!, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse)
print(valueString!)
}
}
}
@IBAction func switchAction(_ sender: Any) {
if switchUI.isOn {
print("On ")
// writeCharacteristic(val: 1)
writeValue(data:"tp1z ")
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print("characterstic value is" , characteristic.value!)
if characteristic == rxCharacteristic {
if let ASCIIstring = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue) {
characteristicASCIIValue = ASCIIstring
print("Value Recieved: \((characteristicASCIIValue as String))")
NotificationCenter.default.post(name:NSNotification.Name(rawValue: "Notify"), object: nil)
}
}
}
func updateIncomingData () {
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "Notify"), object: nil , queue: nil){
notification in
let appendString = "\n"
let myFont = UIFont(name: "Helvetica Neue", size: 15.0)
let myAttributes2 = [NSAttributedStringKey.font: myFont!, NSAttributedStringKey.foregroundColor: UIColor.red]
let attribString = NSAttributedString(string: "[Incoming]: " + (characteristicASCIIValue as String) + appendString, attributes: myAttributes2)
let newAsciiText = NSMutableAttributedString(attributedString: self.consoleAsciiText!)
self.baseTextView.attributedText = NSAttributedString(string: characteristicASCIIValue as String , attributes: myAttributes2)
newAsciiText.append(attribString)
self.consoleAsciiText = newAsciiText
self.baseTextView.attributedText = self.consoleAsciiText
print("incoming")
}
}
我无法理解为什么它会从倒数第二个字符中断我的字符串。
【问题讨论】:
-
你的字符串有多长?使用 GATT 特性一次只能发送大约 20 个字节。 为什么并不重要,您只需要处理可能需要多次传输的事实
-
我不认为这是一个字节问题,因为 m 发送的字符串少于 20 个字节,假设如果我发送 6 个字节的字符串,那么它将发送 2 个字符串 4 个字节,然后是 2 个字节,但 m 不是了解原因
-
原因无关紧要。它只是一个字节流。您将含义放在换行符上,但它只是另一个字节。您需要编写代码来收集传入数据并识别您感兴趣的序列。有限状态机是您可以研究的一种方法
-
检查我更新的代码,还是一样的问题
-
什么问题?你得到什么输出或结果?你想要什么?
标签: ios swift bluetooth-lowenergy cbperipheral hm-10