From deb63ab33adf4e6553221df487aa35edb0e8bf1d Mon Sep 17 00:00:00 2001 From: Thijs Triemstra Date: Wed, 8 Mar 2017 00:59:11 +0100 Subject: [PATCH] add decorator for rpi.gpio and spidev --- luma/core/lib.py | 42 ++++++++++++++++++++++++++++++++++++++++++ luma/core/serial.py | 22 ++++------------------ 2 files changed, 46 insertions(+), 18 deletions(-) create mode 100644 luma/core/lib.py diff --git a/luma/core/lib.py b/luma/core/lib.py new file mode 100644 index 00000000..21a12cbb --- /dev/null +++ b/luma/core/lib.py @@ -0,0 +1,42 @@ +from functools import wraps + +import luma.core.error + + +__all__ = ["rpi_gpio", "spidev"] + + +def __spidev__(self): + # spidev cant compile on macOS, so use a similar technique to + # initialize (mainly so the tests run unhindered) + import spidev + return spidev.SpiDev() + + +def __rpi_gpio__(self): + # RPi.GPIO _really_ doesn't like being run on anything other than + # a Raspberry Pi... this is imported here so we can swap out the + # implementation for a mock + try: + import RPi.GPIO + return RPi.GPIO + except RuntimeError as e: + if str(e) == 'This module can only be run on a Raspberry Pi!': + raise luma.core.error.UnsupportedPlatform( + 'GPIO access not available') + + +def rpi_gpio(f): + @wraps(f) + def wrapper(*args, **kwds): + f.__rpi_gpio__ = classmethod(__rpi_gpio__) + return f(*args, **kwds) + return wrapper + + +def spidev(f): + @wraps(f) + def wrapper(*args, **kwds): + f.__spidev__ = classmethod(__spidev__) + return f(*args, **kwds) + return wrapper diff --git a/luma/core/serial.py b/luma/core/serial.py index 81eb299f..da36935f 100644 --- a/luma/core/serial.py +++ b/luma/core/serial.py @@ -11,6 +11,8 @@ import luma.core.error +from luma.core import lib + __all__ = ["i2c", "spi"] @@ -111,6 +113,8 @@ def cleanup(self): self._bus.close() +@lib.spidev +@lib.rpi_gpio class spi(object): """ Wraps an `SPI `_ @@ -166,24 +170,6 @@ def __init__(self, spi=None, gpio=None, port=0, device=0, self._gpio.output(self._bcm_RST, self._gpio.LOW) # Reset device self._gpio.output(self._bcm_RST, self._gpio.HIGH) # Keep RESET pulled high - def __rpi_gpio__(self): - # RPi.GPIO _really_ doesn't like being run on anything other than - # a Raspberry Pi... this is imported here so we can swap out the - # implementation for a mock - try: - import RPi.GPIO - return RPi.GPIO - except RuntimeError as e: - if str(e) == 'This module can only be run on a Raspberry Pi!': - raise luma.core.error.UnsupportedPlatform( - 'GPIO access not available') - - def __spidev__(self): - # spidev cant compile on macOS, so use a similar technique to - # initialize (mainly so the tests run unhindered) - import spidev - return spidev.SpiDev() - def command(self, *cmd): """ Sends a command or sequence of commands through to the SPI device.