I am currently tasked with developing a software module for communication with a stepper motor controller. The project is written in C #, I have a C ++ dll to communicate with the controller. Communication is done through the serial port. I plan to write the entire fragment in C # by importing the necessary DllImport methods. The key method looks something like this:
ComSendReceive(pHandle, bufferIn,sizeBufferIn,bufferOut,ref bufferOut)
There are several types of messages:
- You send a message and wait for confirmation (not the same for each message, sometimes it’s normal, sometimes it is FULL, etc.
- You send a message and receive a message - you may receive an error message or data (for example, GET_CONTROLLER_ID)
- Several other types
Of course, I need to control the connection for timeouts.
My question is: is there any "design pattern" to use for this kind of problem? I am sure that this is a fairly common problem that many developers have already solved.
To contribute, I encountered a similar problem in my last work, and I solved it like this:
I had a class to communicate with the Com port and the AT_message class with a bunch of overloaded constructors:
class AT_Message
{
public bool DoResponseCheck;
public string ExpectedResponse;
public AT_COMMAND command;
public string data;
public bool AddCarriageReturn;
...
}
class UnfriendlyInterface
{
Response SendMessage(AT_Message msg)
{
}
}
And I had a class that the main application was communicating with, it had friendly human methods like
class FriendlyInterface
{
bool AutodetectPortAndOpenComm();
Result AnalyzeSignal(byte[] buffer)
{
Response response = UnfriendlyInterface.SendMessage(new Message(AT_Command.PrepareForSignal, (doResponseCheck)true, ExpectedResponse.Ok,Timeout.short);
Response response = UnfriendlyInterface.SendMessage(new Message(buffer,(doResponseCheck)false,Timeout.long);
}
}
Since the last time I was in a hurry, I applied the first solution that came to my mind. But is there a way to make this better? Now the device I'm communicating with is more complex than the previous one, so if there is a way to do it better, I would like to do it this way.