Parsing/formatting data from serial port - C#

前端 未结 3 820
别那么骄傲
别那么骄傲 2020-12-01 15:25

I\'ve developed a small program that listens to a serial port. My program is receiving data. The problem is, its not displaying it in the desired format (one string). The da

3条回答
  •  借酒劲吻你
    2020-12-01 15:53

    Assuming there is no termination character, something like this may work. The tricky part is figuring out when to print a new line.

    You may try inserting a newline before every ID: (e.g., replace "ID:" with "\r\n\ID:"). This will still sometimes fail when you receive StreetType:AveI first and then "D:23566 St" next. To fix this, you could just look for any I after StreetType:, but that's not as easy as it sounds either -- what if you see 345 Stre, etTy, pe:RdI. Also, what if I is a valid character (tType:DRI,VE ID:23525)?

    I think that the following code should correctly handle these cases. Note that I switched from Console.WriteLine to Console.Write and manually add the new line when needed:

    private static var previousStringPerPort = new Dictionary();
    private static void Port_DataReceived(object sender, 
                                          SerialDataReceivedEventArgs e)
    {
        SerialPort spL = (SerialPort) sender;
        int bufSize = 20;
        Byte[] dataBuffer = new Byte[bufSize];
        Console.WriteLine("Data Received at"+DateTime.Now);
        Console.WriteLine(spL.Read(dataBuffer, 0, bufSize));
        if (!previousStringPerPort.ContainsKey(spL))
            previousStringPerPort[spL] = "";
        string s = previousStringPerPort[spL] + 
                   System.Text.ASCIIEncoding.ASCII.GetString(dataBuffer);
        s = s.Replace("ID:",Environment.NewLine + "ID:");
        if (s.EndsWith("I"))
        {
            previousStringPerPort[spL] = "I";
            s = s.Remove(s.Length-1);
        }
        else if (s.EndsWith("ID"))
        {
            previousStringPerPort[spL] = "ID";
            s = s.Remove(s.Length - 2);
        }
        Console.Write(s);
    }
    

    Now the only problem remaining is that if the last record really does end in I or ID, it will never be printed. A periodic timeout to flush the previous string could fix this, but it introduces (many) more problems of its own.

提交回复
热议问题