python: open SPI device once (#2066)

Co-authored-by: Comma Device <device@comma.ai>
This commit is contained in:
Adeeb Shihadeh 2024-10-24 13:27:49 -07:00 committed by GitHub
parent 9aec4294cc
commit 8422a7437f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 10 additions and 7 deletions

View File

@ -70,8 +70,6 @@ class PandaSpiTransferFailed(PandaSpiException):
pass pass
SPI_LOCK = threading.Lock()
class PandaSpiTransfer(ctypes.Structure): class PandaSpiTransfer(ctypes.Structure):
_fields_ = [ _fields_ = [
('rx_buf', ctypes.c_uint64), ('rx_buf', ctypes.c_uint64),
@ -83,6 +81,9 @@ class PandaSpiTransfer(ctypes.Structure):
('expect_disconnect', ctypes.c_uint8), ('expect_disconnect', ctypes.c_uint8),
] ]
SPI_LOCK = threading.Lock()
SPI_DEVICES = {}
class SpiDevice: class SpiDevice:
""" """
Provides locked, thread-safe access to a panda's SPI interface. Provides locked, thread-safe access to a panda's SPI interface.
@ -100,9 +101,12 @@ class SpiDevice:
if spidev is None: if spidev is None:
raise PandaSpiUnavailable("spidev is not installed") raise PandaSpiUnavailable("spidev is not installed")
self._spidev = spidev.SpiDev() # pylint: disable=c-extension-no-member with SPI_LOCK:
self._spidev.open(0, 0) if speed not in SPI_DEVICES:
self._spidev.max_speed_hz = speed SPI_DEVICES[speed] = spidev.SpiDev() # pylint: disable=c-extension-no-member
SPI_DEVICES[speed].open(0, 0)
SPI_DEVICES[speed].max_speed_hz = speed
self._spidev = SPI_DEVICES[speed]
@contextmanager @contextmanager
def acquire(self): def acquire(self):
@ -115,8 +119,7 @@ class SpiDevice:
SPI_LOCK.release() SPI_LOCK.release()
def close(self): def close(self):
self._spidev.close() pass
class PandaSpiHandle(BaseHandle): class PandaSpiHandle(BaseHandle):