Python Forum
Reading mixed ASCII/binary serial input - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Reading mixed ASCII/binary serial input (/thread-19026.html)



Reading mixed ASCII/binary serial input - N8UR - Jun-10-2019

I am trying to read serial data from a device that outputs in a mix of ASCII and binary, using Python 3.

The message format is: "$PASHR,<msg type>,<binary payload>,<checksum>,\r\n" (minus the quotes)

To make it more interesting, there are several different message types, and they have different payload lengths, so I can't just read X bytes (I can infer the payload length based on the message type). The sequence of five messages (one of each type) is sent every 20 seconds, at 115200 baud.

I haven't been able to read this with serial.readline(), probably because of newlines embedded in the payload.

I think that if I could set the line-end character to "$PASH" that would give me a way to frame the messages -- ie, everything between one $PASH and the next is one message. But I haven't succeeded in setting serial.newline to that value.

Is there a way to set the newline to that multi-character string, or is there a different/better approach I should use?

Thanks!


RE: Reading mixed ASCII/binary serial input - N8UR - Jun-11-2019

I think I figured it out. This seems to work with a timeout of 1 second:

    self.serial.timeout = 1
    delimiter = b'$PASHR'
    if self.serial.in_waiting:
        message = self.serial.read_until(delimiter)
        if len(message) > 6: # ignore carryover b'$PASHR'
            ***process message***
When I looked carefully at the variable length returns, I discovered that the message sequence after the first incomplete cycle was:

b'$PASHR' (6 bytes)
b',MPC,<data><checksum>\r\n$PASHR' (108 bytes)
...
b',MPC,<data><checksum>\r\n' (102 bytes)
(delay)
b'$PASHR' (6 bytes)

The delimiter from the last message in the sequence is chopped off and output at the beginning of the next sequence. I can deal with that.