pci.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import numpy as np
  2. from _pciffi import ffi, lib
  3. class Error(Exception):
  4. pass
  5. class Types(object):
  6. # This enum also maps directly to the type size for now
  7. UINT8 = 1
  8. UINT32 = 4
  9. TYPE_NAMES = {
  10. Types.UINT8: 'uint8_t',
  11. Types.UINT32: 'uint32_t',
  12. }
  13. class Device(object):
  14. def __init__(self, model, device='/dev/fpga0'):
  15. self.handle = lib.pcilib_open(device, model)
  16. self.dma_engine = lib.pcilib_find_dma_by_addr(self.handle, lib.PCILIB_DMA_BIDIRECTIONAL, 0xFF)
  17. def __enter__(self):
  18. return self
  19. def __exit__(self, *args):
  20. self.close()
  21. def read(self, addr, num, t=Types.UINT32):
  22. data = ffi.new("{}[]".format(TYPE_NAMES[t]), num)
  23. if lib.pcilib_read(self.handle, 0, addr, num, t, data) != 0:
  24. raise Error("Could not read")
  25. return list(data[0:len(data)])
  26. def write(self, addr, value, t=Types.UINT32):
  27. data = ffi.new("{}[]".format(TYPE_NAMES[t]), [value])
  28. if lib.pcilib_write(self.handle, 0, addr, t, 1, data) != 0:
  29. raise Error("Could not write")
  30. def start_dma(self):
  31. lib.pcilib_start_dma(self.handle, self.dma_engine, lib.PCILIB_DMA_FLAGS_DEFAULT)
  32. def close(self):
  33. lib.pcilib_close(self.handle)