As serial port communication is asynchronous, I figured out early on into my project involving communication with a RS 232 device that I will have to have a background thread constantly reading the port for data received. Now, I'm using IronPython (.NET 4.0) so I have access to the slick SerialPort class built into .NET. This lets me write code like this:
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 mentioned I want to be constantly checking this port for new data as it arrives. Ideally, I would have the OS tell me anytime there's data waiting. Whaddaya know, my prayers have been answered, there is a DataReceived
event provided!
self.port.DataReceived += self.OnDataReceived
def OnDataReceived(self, sender, event):
reading = self.port.ReadExisting()
...
Too bad this is worthless, though, because this event isn't guaranteed to be raised!
The DataReceived event is not guaranteed to be raised for every byte received.
So back to writing a listener thread, then. I've accomplished this rather quickly with a BackgroundWorker
that just calls port.ReadExisting()
over and over again. It reads bytes as they come in, and when it sees a line ending (\r\n
), it places what it read into a linebuffer
. Then other parts of my program look at the linebuffer
to see if there are any complete lines waiting to be used.
Now, this is a classic producer-consumer problem, obviously. The producer is the BackgroundWorker
, placing complete lines into linebuffer
. The consumer is some code that consumes those lines from the linebuffer
as fast as possible.
However, the consumer is sort of inefficient. Right now he's constantly checking the linebuffer
, getting disappointed each time to find it empty; though every once in a while does find a line waiting inside. What's the best way to optimize this so that the consumer only wakes up when there is a line available? That way the consumer isn't spinning around constantly accessing the linebuffer
, which might introduce some concurrency issues.
Also, if there is a simpler/better way of reading constantly from a serial port, I'm open to suggestions!