Sunday, 15 June 2014

c# - How to use Reactive Extensions to parse a stream of characters from a serial port? -



c# - How to use Reactive Extensions to parse a stream of characters from a serial port? -

i need parse stream of serial info coming test instrument, , seems first-class application reactive extensions.

the protocol simple...each "packet" single letter followed numeric digits. number of numeric digits fixed each packet type, can vary between packet types. e.g.

...a1234b123456c12...

i trying break observable of strings, e.g.

"a1234" "b123456" "c12" ...

thought simple, don't see obvious way approach (i have experience linq, new rx).

here's code have far, produces observable of chars serial port's serialdatareceived event.

var serialdata = observable .fromeventpattern<serialdatareceivedeventargs>(serialportmain, "datareceived") .selectmany(_ => { int datalength = serialportmain.bytestoread; byte[] info = new byte[datalength]; int nbrdataread = serialportmain.read(data, 0, datalength); if (nbrdataread == 0) homecoming new char[0]; var chars = encoding.ascii.getchars(data); homecoming chars; });

how can transform serialdata observable of string, each string packet?

here's shorter method, in same style james' first solution, similar helper method:

public static bool iscompletepacket(string s) { switch (s[0]) { case 'a': homecoming s.length == 5; case 'b': homecoming s.length == 6; case 'c': homecoming s.length == 7; default: throw new argumentexception("packet must begin letter"); } }

the code then:

var packets = chars .scan(string.empty, (prev, cur) => char.isletter(cur) ? cur.tostring() : prev + cur) .where(iscompletepacket);

the scan part builds strings terminate on letter e.g.:

a a1 a12 a123 ...

the where selects right length. removes tuple james' , uses string length instead.

c# serial-port system.reactive reactive-programming

No comments:

Post a Comment