我的序列具有混合数据格式,某些输出具有
\[0;32m...\[0m
,其中一些为纯文本。
func serialPortWasOpened(_ serialPort: ORSSerialPort) {
let regex = try! NSRegularExpression(pattern: "\\[0;3.{1}m.*\\[0m", options: [])
let descriptor = ORSSerialPacketDescriptor(regularExpression: regex, maximumPacketLength: 512, userInfo: nil)
self.serialPort!.startListeningForPackets(matching: descriptor)
}
func serialPort(_ serialPort: ORSSerialPort, didReceivePacket packetData: Data, matching descriptor: ORSSerialPacketDescriptor) {
if let string = NSString(data: packetData, encoding: String.Encoding.utf8.rawValue) {
textView.textStorage?.append(textView.appendANSIColoredText(string: string))
print(">>> \(string) <<<")
}
}
...
extension NSTextView {
func appendANSIColoredText(string: NSString) -> NSAttributedString {
let color:NSColor;
switch string {
case _ where string.hasPrefix("[0;30m"): color = .black
case _ where string.hasPrefix("[0;31m"): color = .red
case _ where string.hasPrefix("[0;32m"): color = .green
case _ where string.hasPrefix("[0;33m"): color = .yellow
case _ where string.hasPrefix("[0;34m"): color = .blue
case _ where string.hasPrefix("[0;35m"): color = .magenta
case _ where string.hasPrefix("[0;36m"): color = .cyan
case _ where string.hasPrefix("[0;37m"): color = .white
case _ where string.hasPrefix("[0;39m"): color = .magenta
default: color = .white
}
let str = ( string.hasPrefix("\[0;3") ) ? string.substring(with: NSRange(location: 6, length: string.length-11)) as NSString : string as NSString
let attributes: [NSAttributedString.Key: Any] = [
.font: NSFont(name:"Menlo", size: 12.0) as Any,
.foregroundColor: color
]
return NSAttributedString(string: str as String, attributes: attributes)
}
}
我的完整输出在这里https://pastebin.ubuntu.com/p/WTtJmGS9y5/
根据代码,您可以看到通过serialPort didReceivePacket
获得的数据具有>>> <<<标记,但不是全部。...
似乎didReceivePacket
做出了异步响应,导致我的输出必须以
Type "help()" for more information.
>>>
但是有时在这些行之后还有一些其他文字