Continuous read from serial port with background thread

Since communication on the serial port is asynchronous, I first understood my project related to communication with the RS 232 device, that I would have to have a background thread constantly reading the port for the received data. Now I'm using IronPython (.NET 4.0), so I have access to the smooth SerialPort class built into .NET. This allows me to write code as follows:

self.port = System.IO.Ports.SerialPort('COM1', 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One)
self.port.Open()
reading = self.port.ReadExisting() #grabs all bytes currently sitting in the input buffer

Simple enough. But, as I said, I want to constantly check this port for new data as it arrives. Ideally, I would like the OS to tell me when the data will be waiting. Whaddaya know, my prayers were answered, there is an event DataReceived!

self.port.DataReceived += self.OnDataReceived

def OnDataReceived(self, sender, event):
    reading = self.port.ReadExisting()
    ...

, , !!

DataReceived .

, . BackgroundWorker, port.ReadExisting() . , , (\r\n), , linebuffer. linebuffer, , - , .

, -, . - BackgroundWorker, linebuffer. , linebuffer.

. linebuffer, , ; . , , ? , linebuffer, concurrency.

, / , !

+3
4

, DataReceived.

DataReceived . BytesToRead , .

, , , . , BytesToRead .

+3

, .

SerialPort.BaseStream.BeginRead(...). , SerialPort. BeginRead , . EndRead , . BaseStream (SerialStream) Stream .Net Streams, .

, .Net, , . , "".

http://msdn.microsoft.com/en-us/library/system.io.stream.beginread.aspx

+2

, LineBuffer

, , , , 100 != 100 - , .

+1

VB-, , :

Dim rcvQ As New Queue(Of Byte()) 'a queue of buffers
Dim rcvQLock As New Object

Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, _
                                     ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
                                 Handles SerialPort1.DataReceived

    'an approach
    Do While SerialPort1.IsOpen AndAlso SerialPort1.BytesToRead <> 0
        'what if the number of bytes available changes at ANY point?
        Dim bytsToRead As Integer = SerialPort1.BytesToRead
        Dim buf(bytsToRead - 1) As Byte

        bytsToRead = SerialPort1.Read(buf, 0, bytsToRead)

        'place the buffer in a queue that can be processed somewhere else
        Threading.Monitor.Enter(rcvQLock)
        rcvQ.Enqueue(buf)
        Threading.Monitor.Exit(rcvQLock)

    Loop

End Sub

, , , 1 /.

+1

Source: https://habr.com/ru/post/1774617/


All Articles