From f507bb35dcd72a147f4f795464e034dfac929d05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20Elio=20Petten=C3=B2?= Date: Sat, 13 Feb 2016 00:08:32 +0000 Subject: otultraeasy: move the crc function to lifescan_common. The same CRC-CCITT function is used in Verio 2015 devices, so prepare to reuse it by moving it to the common module. --- glucometerutils/drivers/lifescan_common.py | 24 ++++++++++++++++++++++++ glucometerutils/drivers/otultraeasy.py | 15 +-------------- test/test_otultraeasy.py | 4 ++-- 3 files changed, 27 insertions(+), 16 deletions(-) diff --git a/glucometerutils/drivers/lifescan_common.py b/glucometerutils/drivers/lifescan_common.py index 9a60ab6..f37903a 100644 --- a/glucometerutils/drivers/lifescan_common.py +++ b/glucometerutils/drivers/lifescan_common.py @@ -26,3 +26,27 @@ class InvalidSerialNumber(exceptions.Error): """The serial number is not as expected.""" def __init__(self, serial_number): self.message = 'Serial number %s is invalid.' % serial_number + + +def crc_ccitt(data): + """Calculate the CRC-16-CCITT with LifeScan's common seed. + + Args: + data: (bytes) the data to calculate the checksum of + + Returns: + (int) The 16-bit integer value of the CRC-CCITT calculated. + + This function uses the non-default 0xFFFF seed as used by multiple + LifeScan meters. + """ + crc = 0xffff + + for byte in data: + crc = (crc >> 8) & 0xffff | (crc << 8) & 0xffff + crc ^= byte + crc ^= (crc & 0xff) >> 4 + crc ^= (((crc << 8) & 0xffff) << 4) & 0xffff + crc ^= (crc & 0xff) << 5 + + return (crc & 0xffff) diff --git a/glucometerutils/drivers/otultraeasy.py b/glucometerutils/drivers/otultraeasy.py index 422a7c1..0028ff6 100644 --- a/glucometerutils/drivers/otultraeasy.py +++ b/glucometerutils/drivers/otultraeasy.py @@ -68,19 +68,6 @@ def _convert_timestamp(timestamp_bytes): class _Packet(object): _STRUCT = struct.Struct('> 8) & 0xffff | (crc << 8) & 0xffff - crc ^= byte - crc ^= (crc & 0xff) >> 4 - crc ^= (((crc << 8) & 0xffff) << 4) & 0xffff - crc ^= (crc & 0xff) << 5 - - return (crc & 0xffff) - def __init__(self): self.cmd = array.array('B') @@ -148,7 +135,7 @@ class _Packet(object): @property def checksum(self): - return self._crc(self.cmd[:_IDX_CHECKSUM].tobytes()) + return lifescan_common.crc_ccitt(self.cmd[:_IDX_CHECKSUM].tobytes()) @property def acknowledge(self): diff --git a/test/test_otultraeasy.py b/test/test_otultraeasy.py index 326aeea..f263f12 100644 --- a/test/test_otultraeasy.py +++ b/test/test_otultraeasy.py @@ -31,12 +31,12 @@ class TestOTUltraMini(unittest.TestCase): def testCrc(self): self.assertEqual( 0x41cd, - otultraeasy._Packet._crc(b'\x02\x06\x06\x03')) + lifescan_common.crc_ccitt(b'\x02\x06\x06\x03')) cmd_array = array.array('B', b'\x02\x06\x08\x03') self.assertEqual( 0x62C2, - otultraeasy._Packet._crc(cmd_array)) + lifescan_common.crc_ccitt(cmd_array)) def testPacketUpdateChecksum(self): packet = otultraeasy._Packet() -- cgit v1.2.3