I’m writing a .Net app that will need to talk to a serial port device. The device is basically a transmitter for some old school alphanumeric pagers. Occasionally, my app will need to open up a serial port and send a message to the transmitter.
I know the protocol for talking to the device. It’s a bit of a back and forth “chatty” protocol. Send a command … wait for a particular response … send another command … wait for another particular response … send the actual message … wait for an “accepted” response. I can get this to work with some really hacky code involving a series of Write(…) method calls on a SerialPort object, with Thread.Sleep calls in between.
Of course, I don’t want to actually do this by relying on Thread.Sleep to wait for the device to respond. It seems like the Reactive Extensions framework should be suited for this type of thing, but I’m having trouble getting my head around it. I started with this, but quickly got lost and wasn’t sure where to go next, or if this even makes sense:
var receivedData = Observable.FromEventPattern<SerialDataReceivedEventArgs>(serialPort, "DataReceived");
receivedData
.Where(d => d.EventArgs.EventType == SerialData.Chars)
.Subscribe(args =>
{
var response = serialPort.ReadExisting();
// Now what?
});
First, how do I kick this thing off with the first serialPort.Write() call? Then how do I chain them together by checking for the expected response before issuing the next Write() call? And of course if I don’t get the expected response I’d want to break out and throw an exception or something. Am I even barking up the right tree with Rx, or is there another pattern that would be better suited for this? Thanks!
Rx is abstraction over “data source pushing data” scenarios. In your case you have modeled the serial port “read” method as Rx observable and this need to be combined with serial port write method. One possible solution would be something like below, although it may require some other modifications based on the specific needs of your application.