'Problem with the delimiter of data packet

The following example reads data from the UART. In my case, the delimiter where packet starts with b '\x02' everything works, but the problem appears when b '\x02' appears in the packet and it is not the beginning of the packet because uart data often comes in one string. I will add that the packet that needs to be read always starts with b '\x02\x84' the only question is how to check if the first byte b '\x02’ followed by b '\x84' and if so then do a split.

Sample package consisting of several and with the problem:

\x02\x84"\x00\x19\x03\x00l\xe0\x02D\x00\x02\x84"\x00\x19\x03\x00l

I want to get two as handle_packet:

b'\x84"\x00\x19\x03\x00l\xe0\x02D\x00'

b'\x84"\x00\x19\x03\x00l'

rx_buff = bytes()

while True:
    recv = reader.read(-1)
    if not recv:
        continue

    rx_buff += recv

    packets = rx_buff.split(bytes(b'\x02'))

    for packet in packets:
       if not packet:
           continue
 
       msg = mod.handle_packet(packet)
       if (msg):
           get_response(msg)

    rx_buff = (bytes() if mod.handle_packet(packet) else packet)


Solution 1:[1]

I spent a little more time reading. If you do it this way, your problem is going to be the first packet you split, because, I am assuming it doesn't follow the splitting pattern b'\x02\x84". If that is the case, you can just take the first of split_bytes and remove the first byte.

my_bytes = b'\x02\x84"\x00\x19\x03\x00l\xe0\x02D\x00\x02\x84"\x00\x19\x03\x00l'
split_bytes = my_bytes.split(b'\x02\x84"')
packets = []
for e in split_bytes:
    if e != b'':
        packets.append(b'\x84"' + e)

print(packets)

Yields:

[b'\x84"\x00\x19\x03\x00l\xe0\x02D\x00', b'\x84"\x00\x19\x03\x00l']

Your desired packets:

[b'\x84"\x00\x19\x03\x00l\xe0\x02D\x00', b'\x84"\x00\x19\x03\x00l']

If I am missing something, please point it out.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1