def read(self, device_addr: int, num_bytes: int) -> bytes: """Reads bytes from buffer. Returns 0x00 if buffer is empty.""" msg = "Reading {} bytes, buffer: {}".format(num_bytes, byte_str(self.buffer)) self.logger.debug(msg) # Check device address matches if device_addr != self.device_addr: message = "Address not found: 0x{:02X}".format(device_addr) raise ReadError(message) # Pop bytes from buffer and return bytes_ = [] while num_bytes > 0: # Check for empty buffer or pop byte from buffer if len(self.buffer) == 0: bytes_.append(0x00) else: bytes_.append(self.buffer.pop()) # Decrement num bytes to read num_bytes = num_bytes - 1 # Successfully read bytes return bytes(bytes_)
def write(self, bytes_: bytes, retry: bool = True, disable_mux: bool = False) -> None: """Writes byte list to device. Converts byte list to byte array then sends bytes. Returns error message.""" with self.i2c_lock: self.manage_mux("write bytes", disable_mux) self.logger.debug("Writing bytes: {}".format(byte_str(bytes_))) self.io.write(self.address, bytes_)
def read(self, num_bytes: int, retry: bool = True, disable_mux: bool = False) -> bytes: """Reads num bytes from device. Returns byte array.""" with self.i2c_lock: self.manage_mux("read bytes", disable_mux) self.logger.debug("Reading {} bytes".format(num_bytes)) bytes_ = bytes(self.io.read(self.address, num_bytes)) self.logger.debug("Read bytes: {}".format(byte_str(bytes_))) return bytes_
def write(self, address: int, bytes_: bytes) -> None: """Writes bytes to buffer.""" # Check if writing to mux if address == self.mux_address: # Check if mux command valid if len(bytes_) > 1: raise MuxError("Unable to set mux, only 1 command byte is allowed") # Set mux to channel self.mux_simulator.set(self.mux_address, bytes_[0]) # type: ignore # Check if writing to device elif address == self.device_addr: # Verify mux connection if self.mux_address != None: address = self.mux_address # type: ignore channel = self.mux_channel self.mux_simulator.verify(address, channel) # type: ignore # Get response bytes response_bytes = self.writes.get(byte_str(bytes_), None) # Verify known write bytes if response_bytes == None: raise WriteError("Unknown write bytes: {}".format(byte_str(bytes_))) # Write response bytes to buffer response_byte_string = byte_str(response_bytes) # type: ignore self.logger.debug("Response bytes: {}".format(response_byte_string)) for byte in response_bytes: # type: ignore self.buffer.insert(0, byte) self.logger.debug("Buffer: {}".format(byte_str(self.buffer))) # Check for invalid address else: message = "Address not found: 0x{:02X}".format(address) raise WriteError(message)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.writes = {byte_str(bytes([0x01])): bytes([0x02])}