def escape(data): """ escape: byte string -> byte string When a 'special' byte is encountered in the given data string, it is preceded by an escape byte and XORed with 0x20. """ escaped_data = b"" for byte in data: if intToByte(byteToInt(byte)) in APIFrame.ESCAPE_BYTES: escaped_data += APIFrame.ESCAPE_BYTE escaped_data += intToByte(0x20 ^ byteToInt(byte)) else: escaped_data += intToByte(byteToInt(byte)) return escaped_data
def fill(self, byte): """ fill: byte -> None Adds the given raw byte to this APIFrame. If this APIFrame is marked as escaped and this byte is an escape byte, the next byte in a call to fill() will be unescaped. """ if self._unescape_next_byte: byte = intToByte(byteToInt(byte) ^ 0x20) self._unescape_next_byte = False elif self.escaped and byte == APIFrame.ESCAPE_BYTE: self._unescape_next_byte = True return self.raw_data += intToByte(byteToInt(byte))
def fill(self, byte): """ fill: byte -> None Adds the given raw byte to this APIFrame. If this APIFrame is marked as escaped and this byte is an escape byte, the next byte in a call to fill() will be unescaped. """ self.escaped = True if self._unescape_next_byte: byte = intToByte(byteToInt(byte) ^ 0x20) self._unescape_next_byte = False elif self.escaped and byte == APIFrame.ESCAPE_BYTE: self._unescape_next_byte = True return self.raw_data += intToByte(byteToInt(byte))
def test_invalid_checksum(self): """ when an invalid frame is read, an exception must be raised """ api_frame = APIFrame() frame = b'\x7E\x00\x01\x00\xF6' for byte in frame: api_frame.fill(intToByte(byteToInt(byte))) self.assertRaises(ValueError, api_frame.parse)
def test_build_at(self): """ _build_command should build a valid at command packet which has no parameter data to be saved """ at_command = stringToBytes("MY") frame = intToByte(43) data = self.xbee._build_command("at", frame_id=frame, command=at_command) expected_data = b'\x08+MY' self.assertEqual(data, expected_data)
def test_single_byte(self): """ read a frame containing a single byte """ api_frame = APIFrame() frame = b'\x7E\x00\x01\x00\xFF' expected_data = b'\x00' for byte in frame: api_frame.fill(intToByte(byteToInt(byte))) api_frame.parse() self.assertEqual(api_frame.data, expected_data)
def test_build_at(self): """ _build_command should build a valid at command packet which has no parameter data to be saved """ at_command = stringToBytes("MY") frame = intToByte(43) data = self.xbee._build_command( "at", frame_id=frame, command=at_command ) expected_data = b'\x08+MY' self.assertEqual(data, expected_data)
def checksum(self): """ checksum: None -> single checksum byte checksum adds all bytes of the binary, unescaped data in the frame, saves the last byte of the result, and subtracts it from 0xFF. The final result is the checksum """ total = 0 # Add together all bytes for byte in self.data: total += byteToInt(byte) # Only keep the last byte total = total & 0xFF return intToByte(0xFF - total)