如何从bytes对象提取指定字节生成新bytes对象用于Modbus CRC校验
问题:从Modbus串口消息中提取数据字节并生成CRC校验用的bytes对象
我有一台运行修改版Modbus协议的设备,会向树莓派3的串口发送消息。消息总长14字节:开头1个同步字节,接着11个数据字节,最后2个Modbus CRC-16校验字节。我需要把这11个数据字节传入CRC校验函数来验证消息有效性,但不知道怎么提取这些字节并生成校验函数能接受的新bytes对象。以下是我的代码和运行报错(报错是因为未创建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
解决方案
直接利用Python的bytes切片特性就能提取指定范围的字节,在缺失代码的位置添加以下一行即可:
newData = rxData[1:12]
说明:
Python的序列切片采用左闭右开规则,rxData[1:12]会提取索引从1到11的所有元素(结束索引12不包含在内),正好对应你需要的11个数据字节。切片返回的结果本身就是bytes类型,无需额外转换,完全符合check_crc函数的参数要求。
修改后运行代码,就能正常生成newData并完成CRC校验。
内容的提问来源于stack exchange,提问作者slv026
相关产品推荐
相关产品推荐

