Reputation: 99
I'm trying to communicate with with external machine using serial port and what i did, Sending a command getting Positive Response then Sending ENQ and Here in output should show me the Final Response.
First Problem is that the Output Result Repeating 3 Times and it's weird because im Not using any loop in program,
The Second Problem Is i want to Extract the Result to Calculating the Response BCC Im not sure how i can read from buffer and Extract from Buffer!
Upvotes: 0
Views: 1245
Reputation: 17573
When working with a serial communication port or with some other type of slow data transfer mechanism you must take into account that the CPU is probably much much faster than the data transfer through the much slower communications port.
I suggest that you take a look at this stack overflow parsing/formatting data from serial port - C#.
The second problem that you will have is to place onto a stream of bytes a structure that separates out the various messages that are in the byte stream. Normally the approach is to have a series of levels of software, a kind of protocol stack similar to the OSI Model so that different areas of the software deal with different aspects or parts of the communication problem.
With serial communication ports there is usually some kind of a protocol that specifies the starting indicator byte, the series of message bytes, and an ending indicator.
This protocol specifies the actual messages that are transferred so that the sender and the receiver can take the stream of bytes and chop it up into individual messages. These individual messages are then provided to some other functions to actually parse through and perform some action.
Reading your source it appears that you need to rethink your approach to a more modular and more layered approach.
For instance your port interface layer should be processing individual bytes in order to assemble the bytes into a message. The approach that I would take for this would be to use a finite state machine approach (also see state machines - basic of computer science). And I would use an observer pattern so that as messages are assembled, any object that wants the assembled messages would register as a listener and then be provided the assembled message.
So I would have an object that handles the communication port events. This object would read the stream of bytes from the communication port and then assemble byte arrays of individual messages from the stream. I expect that this would be a singleton object to ensure that only one object is interacting with the communications port so this object would also have methods to write a message to the communications port.
This object would also implement the observer pattern so that other objects could register for communication port messages. Once a complete message is received, the communication port object would then provide it to all of the registered listeners.
Upvotes: 1