代码位于:openmv/scripts/libraries/modbus.py
https://github.com/openmv/openmv/blob/master/scripts/libraries/modbus.py
REQUEST = self.uart.read()if debug:print("GOT REQUEST: ", REQUEST)additional_address = REQUEST[0]error_check = REQUEST[-2:]function_code = REQUEST[1]data = REQUEST[2:]RESPONSE = struct.pack("b", self.SLAVE_ID)if self.crc16(REQUEST[:-2]) != error_check:if debug:print("crc not match")return 0 # do nothingif self.SLAVE_ID != additional_address:if debug:print("OpenMV slave id: ", self.SLAVE_ID)print("got cmd id: ", additional_address)return 0 # do nothingif function_code == 0x03: passelif function_code == 0x06: passelif function_code == 0x10:starting_address = struct.unpack(">h", data[:2])[0]quantity_of_registers = struct.unpack(">h", data[2:4])[0]byte_of_registers = struct.unpack("b", data[4:5])[0]try:if byte_of_registers != 2 * quantity_of_registers:raise struct.errorvalues = struct.unpack(">%dh" % quantity_of_registers, data[5:])except struct.error as err:RESPONSE += struct.pack("b", function_code | 0x80)RESPONSE += struct.pack("b", 0x03) # Illegal Data Valueif debug:print("Illegal Data Value, data length error")else:try:for i in range(quantity_of_registers):self.REGISTER[starting_address + i] = values[i]except IndexError as err:RESPONSE += struct.pack("b", function_code | 0x80)RESPONSE += struct.pack("b", 0x02) # Illegal Data Addressif debug:print("Illegal Data Address: ")print(err)else:RESPONSE += struct.pack("b", function_code)RESPONSE += struct.pack(">h", starting_address)RESPONSE += struct.pack(">h", quantity_of_registers)
elif function_code == 0x10:
starting_address = struct.unpack(">h", data[:2])[0]
quantity_of_registers = struct.unpack(">h", data[2:4])[0]
byte_of_registers = struct.unpack("b", data[4:5])[0]
try:
if byte_of_registers != 2 * quantity_of_registers:
raise struct.error
values = struct.unpack(">%dh" % quantity_of_registers, data[5:])
该句疑似应该把data[5:]写为data[5:-2].
data = REQUEST[2:]该句包含crcL crcH。
在提出起始地址,寄存器数量,字节数后,data仍旧包括crc数据。
starting_address = struct.unpack(">h", data[:2])[0]
quantity_of_registers = struct.unpack(">h", data[2:4])[0]
byte_of_registers = struct.unpack("b", data[4:5])[0]
故此怀疑struct.unpack 参数错误。
留存。马克