开发者

SerialPort Data Writes are ending up in Receive Buffer

开发者 https://www.devze.com 2023-04-01 05:17 出处:网络
I have a wrapper class that wraps .Net\'s SerialPort class to perform modem operations and data flow. When I\'m reading from the SerialPort object, the data that I previously wrote to the port is foun

I have a wrapper class that wraps .Net's SerialPort class to perform modem operations and data flow. When I'm reading from the SerialPort object, the data that I previously wrote to the port is found within the receive buffer. Is that a behavior that I can change with the SerialPort object? I haven't found a property for the class that prevents my outgoing data from ending up in the receive buffer.

I use SerialPort.Write() to write the data and this is what I do to read data

private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    Task.Factory.Startnew(() => WriteToBuffer());
}

// ... 

private void WriteToBuffer()
{
    string data = string.Empty;

    lock(_serialPort)
    {
        StringBuilder sb = new StringBuilder();

        while(_serialPort.BytesToRead > 0)
        {
            sb.Append(_serialPort.ReadExisting());
        }

        data = sb.ToString();
    }

    // .. then do some additional processing
}

I read the data in a non-blocking manner because I'd rather be paranoid and not miss any data received events and have client code think there was some type of timeout.

I can prevent Hayes AT commands from being copied into the receive buffer by sending ATE0 but any data I send after the modem is connected to a remote modem is still creeping into the receive buffer.

Is there anything I can do? It's hard to just check and see what I wrote last to the buffer and ignore it because sometimes I read one byte at a time and is part of the data returned. For instance if I send something like "ID 123", I might read "ID " with the while loop and find that there are 0 byte开发者_如何学Cs to read so it stops there. I know that I could just call a Thread.Sleep() each time but I think that would not be good practice.

Can I expect this echoing behavior in ALL modems? If so, then I can add code to filter my written data.


I tried out a handful of other modems and the write data returned in the input buffer just like the original modem model that I tried. My solution was to filter out the written data to correctly read other data coming from the remote modem.

0

精彩评论

暂无评论...
验证码 换一张
取 消