开发者

Synchronizing a java serial port connection using RXTX

开发者 https://www.devze.com 2023-01-12 05:59 出处:网络
I have a Java program that continually listens for messages of a certain format on a serial port.When the sender application is not sending messages, it sends heartbeat messages in the following forma

I have a Java program that continually listens for messages of a certain format on a serial port. When the sender application is not sending messages, it sends heartbeat messages in the following format:

  • byte 1: 1
  • byte 2: 0xFE
  • byte 3: 0xED
  • bytes 4-255: 0

If the receiver application is started before the sender, everything functions correctly, however, if the sender has been throwing down heartbeats, it's almost certain that the receiver, when started, will begin listening in the middle of a heartbeat message (which is a problem because I read in chunks of 255 bytes as each message is Reed-Solomon encoded). I wrote a synchronizing function that's a simple state machine. It reads 1 byte at a time with the following conditions:

  • If I just read a 1: switch to the 开发者_运维知识库NEW_MESSAGE state.

  • If I just read a 0xFE: switch to the POTENTIAL_HEARTBEAT state.

  • If I just read a 0xED: switch to the HEARTBEAT state

Relevant checks are in place to ensure that these states cannot be arrived upon out of order, and once I've reached the HEARTBEAT state, I read the remaining 252 0's and assume the receiver has been synchronized. In testing so far, this synchronizer has not worked correctly despite the correct bytes being sent down to effectively trigger a synchronization. My question is this: is there a better way to synchronize serial communications, because I really don't like my method at all.


The problem was actually just me forgetting the importance of bit ordering. The byte channel I was reading from was little endian so the 16 bit integer 0xFEED was coming to me as 0xED 0xFE instead of 0xFE oxED. With a simple switch in the state checking, everything works peachy king.

Sincere thanks to all that commented.


Extend your state machine and check for the last 3 received bytes. Comapre them to the first 3 bytes of your heartbeat message. As the first 3 bytes seems to be always the same, you can use this to detect the beginning of the heartbeat message and do your sync.

0

精彩评论

暂无评论...
验证码 换一张
取 消