Search code examples
pythonclassgpio

Avoiding repeating code by creating a handler class


I'm new to Python and trying to avoid repeating the same code over and over. I'm currently working with a Raspberry Pi that uses GPIO in several different classes so instead of writing

servoPin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPin,GPIO.IN)

in several different classes I was hoping to bundle all the GPIO events in a PinHandler of sorts..

So, I thought of something like this for my handler class

import RPi.GPIO as GPIO
 class PinHandler:
  def __init__(self):
   self.servoPin = 17
   GPIO.setmode(GPIO.BCM)
   GPIO.setup(self.servoPin,GPIO.IN)
  def getPinStatus(self,pin):
   return GPIO.input(pin)
  def addEventListener(self,functionName)
   GPIO.add_event_callback(self.servopin, functionName)

and then in my other classes all I have to type is

from pinHandler.py import PinHandler
import time

pinHandler = PinHandler()

pinHandler.addEventListener(myAwesomeFunction)

def myAwesomeFunction:
 pass

This would then add the callback to myAwesomeFunction which is outside the scope of pinHandler. Am I on the right track here or is there a better way of doing this?


Solution

  • More complete OOP design:

    import RPi.GPIO as GPIO
    
    class PinHandler:
        """
        Base class, wrapts all GPIO tasks
        """
        def __init__(self, pin):
            self.pin = pin
            GPIO.setmode(GPIO.BCM)
            GPIO.setup(self.pin,GPIO.IN)
    
        def getPinStatus(self,pin):
           return GPIO.input(pin)
    
        def add_event_callback(self, callback)
            GPIO.add_event_callback(self.pin, callback)
    

    from pinHandler.py import PinHandler
    
    
    class Servo(PinHandler):
        """
        Spezialized class, handle all `Servo` related
        """
        def __init__(self):
            super().__init__(17)
            self.add_event_callback(self.event_listener)
    
        def event_listener(self, event):
            # handle event
            pass
    

    Usage:

    servo = Servo()