Why does the serial BT data I received get chopped out?

前端 未结 1 469
半阙折子戏
半阙折子戏 2021-01-28 18:59

The data i receive from a BT serial connection should be:

0
1
2
3
.
.
.
27
28
29
0
1
2
3
.
.
.
etc

But what i actually get are some of the data

相关标签:
1条回答
  • 2021-01-28 19:25

    Look at your data again - you actually are receiving it all, you have just made an invalid assumption that you will receive it in the same size chunks you sent it in.

    05-06 17:28:07.079: I/HBAS(15090): 11
    05-06 17:28:07.079: I/HBAS(15090): 12
    05-06 17:28:07.969: I/HBAS(15090): 1
    05-06 17:28:08.029: I/HBAS(15090): 3
    

    See you got your '13' - only it came in as a '1' and then a '3'.

    That's perfectly allowed and something you should expect to have happen quite frequently. You will need to introduce some means of regrouping your data and dividing it up into useful pieces.

    You could do something like send

    0011
    0012
    0013
    

    etc and always assemble four-byte chunks before attempting to parse them. If the transport is one that is guaranteed, this actually will work, though it feels risky - if it ever gots out of sync, it would stay out of sync until the system was reset or randomly wandered back on. But if the transport is guaranteed not to drop or re-order anything (without at least warning you that it has), then in theory that probably won't be seen (outside of your error handler).

    Another common idea would be to introduce delimiters which cannot occur in the data, for example

    11\n
    12\n
    13\n
    

    And look for the terminating newline before attempting to parse. This has the advantage that you could discard something garbled and recover by synching to the next newline you find.

    Finally, there is the case where all values are possible in the data, so you cannot reserve one for a delimiter/terminator. In that case, it's common to reserve one as an escape character which precedes a sequence of special meaning, and have one of those special sequences stand for a literal occurrence of the escape character - that's like the handling of \ in quoted strings where "\n" means newline and "\\" means a literal \

    EDIT: oh, the humor, I had to escape the double backslashes to get them to display, but not the backslash n

    0 讨论(0)
提交回复
热议问题