def write(self, value): magic_code = value[:2] length = value[2:4] payload = value[4:] packet = Packet.extract(payload) self.input_buffer.append(packet) if packet.payload_type in self.callbacks: self.callbacks[packet.payload_type]()
def test_extract(): """ Test extract packet information from raw bytes. """ # These raw bytes are from the ReadCentral packet built in test_build() raw_payload = bytearray( b'\x10\x00\x00\x00\x0c\x00\x10\x00\x0c\x00\x09\x00\x04\x00\x0a\x00\x0c\x00\x00\x00\x1c\x00' b'\x00\x00\x00\x0b\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00\x08\x00' b'\x06\x00\x04\x00\x08\x00\x00\x00\x03\x00\x40\x00') packet = Packet.extract(raw_payload) assert isinstance(packet, Packet) assert packet.controller_id == 0 assert packet.payload_type == Payload.Payload.ReadCentral assert packet.get('connection_handle') == 0x0040 assert packet.get('attribute_handle') == 0x0003 # Test with a wrong payload bytes (random) raw_payload2 = bytearray(b'\x10\x00\x00\x00\x0c\x00') with pytest.raises(Exception): Packet.extract(raw_payload2)
def run(self): while True: header = bytearray() while len(header) < 4: header += self.file.read(1) if header[:2] != MAGIC_CODE: self.logger.error("Wrong magic code received: %s", header[:2]) continue if sys.byteorder == 'little': # depends on ENDIANNESS length = (header[3] << 8) | header[2] else: length = (header[2] << 8) | header[3] payload = bytearray() while len(payload) < length: payload += self.file.read(1) packet = Packet.extract(payload) if packet.payload_type == Payload.Exit: break self.on_receive(packet)