def _encode_message(cmd): """Add message preamble and calculate checksum, add padding.""" length = len(cmd) + _STRUCT_PREAMBLE.size + _STRUCT_CODA.size preamble = _STRUCT_PREAMBLE.pack(_STX, length) message = preamble + cmd + bytes((_ETX, )) checksum = _STRUCT_CHECKSUM.pack(lifescan.crc_ccitt(message)) # Pad the message to match the size of the register. return message + checksum + bytes(_REGISTER_SIZE - 2 - len(message))
def _extract_message(register): """Parse the message preamble and verify checksums.""" stx, length = _STRUCT_PREAMBLE.unpack_from(register) if stx != _STX: raise lifescan.MalformedCommand('invalid STX byte: %02x' % stx) if length > _REGISTER_SIZE: raise lifescan.MalformedCommand('invalid length: %d > REGISTER_SIZE' % length) # 2 is the length of the checksum, so it should be ignored. calculated_checksum = lifescan.crc_ccitt(register[:(length - 2)]) coda_offset = length - _STRUCT_CODA.size etx, encoded_checksum = _STRUCT_CODA.unpack_from(register[coda_offset:]) if etx != _ETX: raise lifescan.MalformedCommand('invalid ETX byte: %02x' % etx) if encoded_checksum != calculated_checksum: raise exceptions.InvalidChecksum(encoded_checksum, calculated_checksum) response = register[_STRUCT_PREAMBLE.size:coda_offset] return response
def checksum(self): return lifescan.crc_ccitt(self.cmd[:_IDX_CHECKSUM].tobytes())
def test_crc_array(self): cmd_array = array.array('B', b'\x02\x06\x08\x03') self.assertEqual( 0x62C2, lifescan.crc_ccitt(cmd_array))
def test_crc(self): self.assertEqual( 0x41cd, lifescan.crc_ccitt(b'\x02\x06\x06\x03'))
def test_crc_array(self): cmd_array = array.array('B', b'\x02\x06\x08\x03') self.assertEqual(0x62C2, lifescan.crc_ccitt(cmd_array))
def test_crc(self): self.assertEqual(0x41cd, lifescan.crc_ccitt(b'\x02\x06\x06\x03'))
def test_crc_array(self): cmd_array = array.array("B", b"\x02\x06\x08\x03") self.assertEqual(0x62C2, lifescan.crc_ccitt(cmd_array))
def test_crc(self): self.assertEqual(0x41CD, lifescan.crc_ccitt(b"\x02\x06\x06\x03"))
def testCrc(self): self.assertEqual(0x41cd, lifescan.crc_ccitt(b'\x02\x06\x06\x03')) cmd_array = array.array('B', b'\x02\x06\x08\x03') self.assertEqual(0x62C2, lifescan.crc_ccitt(cmd_array))