C# COM Messaging system design
I can use some help for a designing my COMport connection classes.
I have a device with a microcontroller (which I programmed) connected to my comport. Whenever I send a message to it, it should send an acknowledge.
So whenever I send something over the comport, it should wait for an acknowledge before continuing.
Ofcourse, I dont want something like a while(!ack) wait()
.
When a ack is not received in 1 second or so, it should send the command again. The Ack looks different for each type of command (note: only the type, no message-specific id). The connected device also sends messages (apart from ACKs), which need to be handled by the application itself.
Does anybody has suggestions about an easy and flexible way开发者_如何学运维 (a design pattern maybe? a sample?) to fix this?
You'll probably want a dedicated thread that handles the communications. You'll need a Queue on which the client code can push a message, protect it with a ReaderWriterLockSlim. No need for the DataReceived event, just call SerialPort.Read() directly. Detect timeouts with the ReadTimeout property. If you get responses that need to go back to the client code then use an event.
Watch out designing the protocol, it isn't that easy to get right. You'll protect against loss of bytes with your scheme, but it is just as likely for the ACK to be lost. The microcontroller will see the same command twice. Now you need a "message number" to suppress duplicates and a way for both ends to synchronize them. Take a look at RFC 916.
精彩评论