[Tutor] how to transform the data as below?
Peter Otten
__peter__ at web.de
Thu Mar 17 05:47:47 EDT 2016
Yeh wrote:
> Hi,
>
> I got messages from a MCU by using codes below:
>
> import socket
> import time
>
> port = 8888
> s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
> s.bind(("",port))
> print('waiting on port:', port)
> while True:
> data, addr = s.recvfrom(1024)
> print("DATA:", data, addr)
> time.sleep(100)
>
> The messages should be a head "YY" and 5 integers, (each integer is
> transferred by 2 bytes.) but I got data below. So, how to transform the
> data? and how to arrange the data to a array?
>
> DATA:
> b'\t\x01x\x01\xfd\x02\x01\x02[YY\x01\t\x01x\x01...
> ('192.168.1.101', 35000)
What you read are the raw bytes. The array module offers one way to convert
bytes to integers. Unfortunately the separator byte sequence b"YY" (or b"XY"
followed by b"YZ") is also that for the integer 22873:
>>> array.array("H", b"YY")
array('H', [22873])
Therefore you cannot be 100% sure when you start the bytes-to-int conversion
at the first occurence of b"YY". Here's an example that uses a simple
heuristics (which may fail!) to cope with the problem
import array, re
def find_start(data):
for m in re.compile(b"YY").finditer(data):
if all(
data[i:i+2] == b"YY"
for i in range(m.start(), len(data), 12)):
return m.start()
raise ValueError
data = b'\t\x01x\x01\xfd\x02\x01\x02[YY\x01\t...
if __name__ == "__main__":
start = find_start(data)
for i in range(start, len(data)-11, 12):
chunk = data[i:i+12]
print(chunk, "-->", list(array.array("H", chunk[2:])))
More information about the Tutor
mailing list