Let's say we are creating a gpio pin interface for mulitple boards. For example:
if board == "raspberrypi":
import RPi.GPIO as gpio
elif board == "bananapi":
import BPi.GPIO as gpio
gpio.setmode(gpio.BCM)
class Pin:
def __init__(self, pinNo):
self.pin = pinNo
def set(self):
gpio.output(self.pin, 1)
This approach seems very simple and clear. However, I'm not sure how I would unittest this. But I've seen people do this. And what happens when a GPIO module that has different methods from RPi.GPIO enters?
A different approach would be to create a GPIO interface and have an adapter that makes sure GPIO module fits the interface.
class GPIOInterface:
__metaclass__ = ABCMeta
@abstractmethod
def set(self, pin: int):
pass
import RPi.GPIO
class GPIORaspberryAdapter(GPIOInterface):
def __init__(self):
RPi.GPIO.setmode(RPi.GPIO.BCM)
def set(self, pin: int):
RPi.GPIO.output(pin, 1)
Then you simply inject it into the Pin class:
class Pin:
def __init__(self, pinNo: int, gpio:GPIOInterface):
self.pin = pinNo
self.gpio = gpio
def set(self):
self.gpio.set(self.pin)
Which way is better and why?
Aucun commentaire:
Enregistrer un commentaire