crcmodbuspymodbus3

Python, using variables in pymodbus.utilities.computeCRC


I am searching for days, if I used the wrong search strings, I am sorry.

I want to use "pymodbus.utilities.computeCRC" to calculate the CRC value to communicate with a Modbus device that uses proprietary code, so no default "read register" functions can be used.

Correct CRC is 0x34bb

The problem is, that it only works with version 1, give the hex values direct to computeCRC, but none of the "variable" options are working.

import pymodbus.utilities
meins=[]
meins.append('10')
meins.append('33')
meins.append('01')
meins.append('01')

meins1=''
for i in meins:
        meins1 = meins1 + "\\x" + i

meins2='\x10\x33\x01\x01'

meins3=bytearray.fromhex("10330101")

crc=hex(pymodbus.utilities.computeCRC('\x10\x33\x01\x01'))
print(crc)
crc=hex(pymodbus.utilities.computeCRC(meins))
print(crc)
crc=hex(pymodbus.utilities.computeCRC(meins1))
print(crc)
crc=hex(pymodbus.utilities.computeCRC(meins2))
print(crc)
crc=hex(pymodbus.utilities.computeCRC(meins3))
print(crc)

Output:


Solution

  • Here is how you can use the CRC generator for your need , There is a subtle difference on how to the input needs to be passed depending on the python version (2.7 or 3.x).

    Python3 and Pymodbus==1.3.2

    Note python3 and pymodbus requires bytestrings to generate CRC .

    import pymodbus.utilities
    from pymodbus.compat import int2byte
    meins=[]
    meins.append(0x10)
    meins.append(0x33)
    meins.append(0x01)
    meins.append(0x01)
    
    meins1=b''
    for i in meins:
        meins1 = meins1 + int2byte(i)
    
    meins2=b'\x10\x33\x01\x01'
    
    meins3=bytearray.fromhex("10330101")
    
    crc=hex(pymodbus.utilities.computeCRC(b'\x10\x33\x01\x01'))
    print(crc)
    crc=hex(pymodbus.utilities.computeCRC(meins))
    print(crc)
    crc=hex(pymodbus.utilities.computeCRC(meins1))
    print(crc)
    crc=hex(pymodbus.utilities.computeCRC(meins2))
    print(crc)
    crc=hex(pymodbus.utilities.computeCRC(meins3))
    print(crc)
    

    Output

    0x34bb
    0x34bb
    0x34bb
    0x34bb
    0x34bb
    

    Python2 and pymodbus==1.3.2

    import pymodbus.utilities
    from pymodbus.compat import int2byte
    meins=[]
    meins.append(int2byte(0x10))
    meins.append(int2byte(0x33))
    meins.append(int2byte(0x1))
    meins.append(int2byte(0x1))
    
    meins1=''
    for i in meins:
            meins1 = meins1 + i
    
    meins2='\x10\x33\x01\x01'
    
    meins3=bytearray.fromhex("10330101")
    meins3=''.join(str(meins3))
    
    crc=hex(pymodbus.utilities.computeCRC('\x10\x33\x01\x01'))
    print(crc)
    crc=hex(pymodbus.utilities.computeCRC(meins))
    print(crc)
    crc=hex(pymodbus.utilities.computeCRC(meins1))
    print(crc)
    crc=hex(pymodbus.utilities.computeCRC(meins2))
    print(crc)
    crc=hex(pymodbus.utilities.computeCRC(meins3))
    print(crc)
    

    Output

    0x34bb
    0x34bb
    0x34bb
    0x34bb
    0x34bb