def transfer(self, read_addr, read_data, write_addr, write_data): buf_len_words = len(write_data) if len(read_data) != buf_len_words: raise ValueError("Read and write buffer sizes must match.") buf_len_bytes = SPI_BYTES_PER_WORD * buf_len_words address_offset_bytes = 2 * SPI_BYTES_PER_WORD bytes_in_transfer = address_offset_bytes + buf_len_bytes # Build the data packet: read addr, write addr, data. write_buf = self.write_buf[:bytes_in_transfer] read_buf = self.read_buf[:bytes_in_transfer] self._addresses[0] = read_addr self._addresses[1] = write_addr fixeds_to_spi(self._addresses, write_buf[:address_offset_bytes]) fixeds_to_spi(write_data, write_buf[address_offset_bytes:]) # Do transfer. self.dev.transfer(write_buf, read_buf) # Unpack results spi_to_fixeds(read_buf[address_offset_bytes:], read_data)
def test_spi_roundtrip(n=10, reps=100): for i in xrange(reps): # Encode ref, decode ref fixeds = np.random.randint(2**36-1, size=n).astype(np.uint64) ref_spi = fixeds_to_spi(fixeds) ref_roundtrip_result = spi_to_fixeds(ref_spi) assert np.all(fixeds==ref_roundtrip_result) # Encode ref, decode cython fixed_buf = np.empty(n, dtype=np.uint64) wireformat.spi_to_fixeds(ref_spi, fixed_buf) assert np.all(fixeds == fixed_buf) # Encode cython, decode ref spi_buf = np.empty(n * 8, dtype=np.uint8) wireformat.fixeds_to_spi(ref_roundtrip_result, spi_buf) assert np.all(spi_buf == ref_spi) assert np.all(fixeds == spi_to_fixeds(spi_buf)) # Encode cython, decode cython wireformat.fixeds_to_spi(fixeds, spi_buf) wireformat.spi_to_fixeds(spi_buf, fixed_buf) assert np.all(fixeds == fixed_buf)