Skip to content

Commit

Permalink
python: open SPI device once (#2066)
Browse files Browse the repository at this point in the history
Co-authored-by: Comma Device <[email protected]>
  • Loading branch information
adeebshihadeh and Comma Device authored Oct 24, 2024
1 parent 9aec429 commit 8422a74
Showing 1 changed file with 10 additions and 7 deletions.
17 changes: 10 additions & 7 deletions python/spi.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,6 @@ class PandaSpiTransferFailed(PandaSpiException):
pass


SPI_LOCK = threading.Lock()

class PandaSpiTransfer(ctypes.Structure):
_fields_ = [
('rx_buf', ctypes.c_uint64),
Expand All @@ -83,6 +81,9 @@ class PandaSpiTransfer(ctypes.Structure):
('expect_disconnect', ctypes.c_uint8),
]


SPI_LOCK = threading.Lock()
SPI_DEVICES = {}
class SpiDevice:
"""
Provides locked, thread-safe access to a panda's SPI interface.
Expand All @@ -100,9 +101,12 @@ def __init__(self, speed=MAX_SPEED):
if spidev is None:
raise PandaSpiUnavailable("spidev is not installed")

self._spidev = spidev.SpiDev() # pylint: disable=c-extension-no-member
self._spidev.open(0, 0)
self._spidev.max_speed_hz = speed
with SPI_LOCK:
if speed not in SPI_DEVICES:
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
def acquire(self):
Expand All @@ -115,8 +119,7 @@ def acquire(self):
SPI_LOCK.release()

def close(self):
self._spidev.close()

pass


class PandaSpiHandle(BaseHandle):
Expand Down

0 comments on commit 8422a74

Please sign in to comment.