Improve CRC speed

This commit is contained in:
Jean-Louis Dupond 2020-02-16 09:14:31 +01:00
parent d714528c5a
commit 78419f6cc7

View File

@ -11,6 +11,8 @@ logger = logging.getLogger(__name__)
class TelegramParser(object): class TelegramParser(object):
crc16_tab = []
def __init__(self, telegram_specification, apply_checksum_validation=True): def __init__(self, telegram_specification, apply_checksum_validation=True):
""" """
:param telegram_specification: determines how the telegram is parsed :param telegram_specification: determines how the telegram is parsed
@ -93,8 +95,14 @@ class TelegramParser(object):
@staticmethod @staticmethod
def crc16(telegram): def crc16(telegram):
crc16_tab = [] """
Calculate the CRC16 value for the given telegram
:param str telegram:
"""
crcValue = 0x0000
if len(TelegramParser.crc16_tab) == 0:
for i in range(0, 256): for i in range(0, 256):
crc = c_ushort(i).value crc = c_ushort(i).value
for j in range(0, 8): for j in range(0, 8):
@ -102,15 +110,13 @@ class TelegramParser(object):
crc = c_ushort(crc >> 1).value ^ 0xA001 crc = c_ushort(crc >> 1).value ^ 0xA001
else: else:
crc = c_ushort(crc >> 1).value crc = c_ushort(crc >> 1).value
crc16_tab.append(hex(crc)) TelegramParser.crc16_tab.append(hex(crc))
crcValue = 0x0000
for c in telegram: for c in telegram:
d = ord(c) d = ord(c)
tmp = crcValue ^ d tmp = crcValue ^ d
rotated = c_ushort(crcValue >> 8).value rotated = c_ushort(crcValue >> 8).value
crcValue = rotated ^ int(crc16_tab[(tmp & 0x00ff)], 0) crcValue = rotated ^ int(TelegramParser.crc16_tab[(tmp & 0x00ff)], 0)
return crcValue return crcValue