1

我的序列有混合数据格式,一些输出有 \[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.
>>>

但有时在这些行之后会有一些额外的文字

4

0 回答 0