如何从'bytes'列表提取字节数并放入新的'bytes'列表中
我有一个设备,它使用了一种修改过的modbus协议。这个设备会通过串口向树莓派3发送消息。每条消息有14个字节,开头是一个同步字节,接着是11个数据字节,最后是两个modbus CRC-16字节。
为了检查消息的有效性(通过CRC校验),我只能把那11个数据字节发送给CRC校验函数。问题是,我就是搞不清楚怎么把这11个字节提取出来,并放到一个新的字节列表中(??),这样才能被CRC函数接受。
下面是程序的代码,以及运行后的输出(输出中的错误是可以理解的,因为newData
列表还没有创建——这正是我希望得到帮助的地方)。
import serial
from time import sleep
from modbus_crc import check_crc
ser = serial.Serial("/dev/ttyS0", 9600)
print("waiting for message from the serial port ......\n")
rxData = ser.read()
sleep(0.03)
data_left = ser.inWaiting()
rxData += ser.read(data_left)
print("Message has been received\n")
print("The 'rxData' type from ser.read() is ",type(rxData), " and length is ", len(rxData))
print("'rxData - ", [hex(i) for i in rxData], "\n")
print("Now show only bytes 1 to 11 of rxData\n")
x = range(1,12,1)
for i in x:
print((hex(rxData[i])), end=" ")
print("\n")
#####################
#### Missing code to make newData with only the bytes (1 to 11 in rxData
#####################
print("\nThe 'newData' type is ",type(newData), " and length is ", len(newData))
print("'newData' - ", [hex(i) for i in newData], "\n")
print("\n")
print("check if newData CRC is OK\n")
if not check_crc(newData):
print("CRC is NOT OK")
else:
print("CRC is OK!")
运行程序后的输出:
waiting for message from the serial port ......
Message has been received
The 'rxData' type from ser.read() is <class 'bytes'> and length is 14
'rxData - ['0xff', '0xd', '0x77', '0x2', '0x1', '0x1', '0x12', '0x33', '0x30', '0x2e', '0x38', '0x39', '0xfd', '0x78']
Now show only bytes 1 to 11 of rxData
0xd 0x77 0x2 0x1 0x1 0x12 0x33 0x30 0x2e 0x38 0x39
Traceback (most recent call last):
File "/home/stevev/Projects/TKinter/20240309-operation on Bytes class.py", line 29, in <module>
print("\nThe 'newData' type is ",type(newData), " and length is ", len(newData))
NameError: name 'newData' is not defined
1 个回答
0