Wednesday, 15 February 2012

c# - Best way to implement a request response pattern that is extendable -



c# - Best way to implement a request response pattern that is extendable -

ok,

i have create c# library can send commands device , process command specific responses , broadcasts on serial port (or other communications method). library must able handle request , response extensions held in other libraries devices implement extended command set, must possible take whether these extended commands utilised (i guess using reflection in client app). have created class of type packet able create packet , add together payload, calculate checksum , write packet stream.

public class packet { internal packetheadertype header { get; private set; } internal list<byte> payload { get; private set; } protected int payloadlength { { homecoming payload.count; } } protected byte headerbyte { { homecoming (byte)((convert.tobyte(header) << 4) | payloadlength); } } //we need add together packet length lower nibble of header before sending public packet(packetheadertype header, list<byte> payload) { this.header = header; this.payload = new list<byte>(payload); } public packet(packetheadertype headerbyte) { this.header = headerbyte; this.payload = new list<byte>(); } internal byte xorbyte { { byte xorbyte = convert.tobyte(headerbyte); (int = 0; < payloadlength; i++) xorbyte ^= payload.toarray()[i]; homecoming xorbyte; } } public async task writeasync(stream stream, bool flush = true, cancellationtoken token = default(cancellationtoken)) { var buffer = new list<byte>(); buffer.add(headerbyte); if (payload != null && payloadlength > 0) { buffer.addrange(payload); } buffer.add(xorbyte); await stream.writeasync(buffer.toarray(), 0, buffer.count); if (flush) { await stream.flushasync(); } } }

i have created kid classes implement type packet each of valid commands. have created class of type packethandler able read bytes stream , create packet object.

the way envisage using library this:

public async string getcmdstnsoftwareversion() { var msgreq = new cmdstnsoftwareversionreqmessage(); await msgreq.writeasync(sport.basestream); await var response = msgreq.getresponse(5); //5 = timeout in seconds! homecoming string.format("{0}.{1}", response.major, response.minor); }

what stuck on pattern and/or illustration implementation handling responses compatible implementing extension libraries. can provide input?

c#

No comments:

Post a Comment