So I'm making a program that is a serial port wedge. In other words I want it to listen to a serial port. If data comes in, wait a given amount of time, then play a sound and finally send the data out.
All of those things have a abstract class associated with it. I'm thinking that I might eventually want to monitor USB:HID
things so I made a IInput class which has abstract methods of Open
, Close
, ToXmlString
, ParseXmlString
and has a event of DataAvailable
. I extend that class with ComPortInput
.
This is the question of it: Do I subscribe to my data event in the Open method, then unsubscribe in close? Or should I just have it in the initializer. I have a GUI that a user can change any of the 4 elements on this wedge at any time. But I'm not sure what would be the cleanest way of doing this. I'm thinking that the GUI would always create a new instance of my ComPortInput
class. Part of me wants to force that GUI to have another method like Check Input. which in this case if the COM port was invalid or busy it would return false. Then instead of making a ComPortInput
I would then want a NoInputInput class (for when I don't want to port forward) If I did it this way then I could get rid of my null checks on the serial port (Much desired) but is that too tricky? (as in too hard to read?) I'm thinking that if i do that I could put in my constructor of ComPortInput
to Assert not null of the SerialPort
. To me this looks better
public ComPortInput(SerialPort sp, int delay) : base(delay)
{
if (sp == null)
throw new System.ArgumentNullException("Serial port can not be null");
LibraryTrace.Start("ComPortInput", delay);
serialPort = sp;
serialPort.DataReceived += sp_DataReceived;
LibraryTrace.End("ComportInput");
}
~ComPortInput()
{
serialPort.Dispose();
}
My thoughts on this way, though, is that it might be hard to have a abstract CheckValidity
... Hmm just thought as I was typing what if I put a params object[] args
for CheckValidity and just have the comport i could try a few things and return true or false. Then if I ever decide to accept other types of input I could do something similar (such as if it was USB:HID
I could accept the PID/VID
) What do you guys think? Am I on the right track?
IDisposable
and follow the disposable pattern for it: stackoverflow.com/a/898867/3312 \$\endgroup\$