Reorder a list in Python so that it starts with control values

I read serial data using Pyserial to populate a list of 17 values ​​(1 byte each) with a sampling frequency of 256 Hz.

The byte that I ultimately want to use is the fifth to eighth place on the list. Apart from bytes, the first two values ​​of the stream are always the same ('165', '90'). I get quite a few discarded values, and my list values ​​change, so when I read 5-8 bytes, they are not valid values.

I partially fought this, making sure that before the captured request is captured, the first few values ​​are checked for what they should be (that is, if mylist [0] == 165 & ....).
This is rude, but normal, since the probability that these two values ​​appear next to each other in a list in another place is small. The problem is that this means that as soon as the byte shift, I lose the load of values ​​until it rebuilds.

My question is: what code can I use for:

a) Forcibly reinstall the list as soon as it is discovered that it no longer starts at 165.90. (Elif ....).

b) Determine where '165' and '90' are (next to each other) in the list and extract the values ​​that I want in relation to their position (further, but one, further).

Thanks in advance

S_s

Qs,

mylist.append(mylist.pop(0)) 

, . , ?

+5
3

, , :

l = [67, 126, 165, 90, 11, 1, 3, 5, 151, 99, 23]

:    = [3,5,151,99]

:

# obtain places where 165 is followed by 90
match = [x for x in xrange(len(l)-1) if l[x]==165 and l[x+1]==90]
# obtain range of useful values
useful = l[match[0]+4:match[0]+8]

, , . , ,

+2

, 17- . , - :

while True:    
    mylist.extend(get_more_data())

    # If we're misaligned, skip bytes until we're aligned again
    while mylist and mylist[0] != 165 or mylist[1] != 90:
        mylist.pop(0)

    # If we've skip bytes, we might not have enough data, so get more
    if len(mylist) < 17:
        continue

    # Process one chunk of data and remove it from the list
    process_data(mylist[:17])
    del mylist[:17]
0

165 90 , . , :

def get_message():
    while True: #Some timeout functionality is useful here ;-)
       message = []
       byte = xxx.get_byte()
       if byte == 165:
          byte = xxx.get_byte()
          if byte == 90:
             xxx.get_byte() #drop it
             xxx.get_byte() #drop it
             message[0] = xxx.get_byte()
             message[1] = xxx.get_byte()
             message[2] = xxx.get_byte()
             message[3] = xxx.get_byte()
             #Break out of loop. We have a message! 
             return message

If you are designing both sides, you really have to insert some kind of checksum. If you just hacked something, look in bytes for a checksum. Perhaps it already is.

0
source

All Articles