Skip to content

Commit

Permalink
single GPIO cleanup hook
Browse files Browse the repository at this point in the history
  • Loading branch information
quantenschaum committed Oct 31, 2017
1 parent 05dcf48 commit 9ce21e0
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 9 deletions.
2 changes: 1 addition & 1 deletion piripherals/__version__.py
@@ -1,7 +1,7 @@
__title__ = 'piripherals'
__description__ = 'a collection of classes to interact with peripherals for the RaspberryPi'
__url__ = 'https://github.com/quantenschaum/piripherals'
__version__ = '0.1a2'
__version__ = '0.1a3'
__author__ = 'quantenschaum'
__author_email__ = 'software@louisenhof2.de'
__license__ = 'GPLv3'
Expand Down
7 changes: 3 additions & 4 deletions piripherals/button.py
Expand Up @@ -3,7 +3,7 @@
Use GPIO pins as button inputs with debouncing and multi-click and hold-detection.
"""

from .util import not_raising
from .util import not_raising, fork, set_bcm
import atexit
from threading import Thread, Event
from functools import partial
Expand Down Expand Up @@ -263,8 +263,7 @@ def bind(self, pin, low_active=1, pullup=1, delay=0.01, count=100):
count (int): # of polls after button was released, this allows
the polling to be paused if the button is untouched
"""
GPIO.setmode(GPIO.BCM)
atexit.register(partial(GPIO.cleanup, pin))
set_bcm()
pullup = [GPIO.PUD_DOWN, GPIO.PUD_OFF, GPIO.PUD_UP][pullup + 1]
pressed = GPIO.LOW if low_active else GPIO.HIGH
edge = GPIO.FALLING if low_active else GPIO.RISING
Expand All @@ -286,7 +285,7 @@ def poll():
k -= 1
sleep(delay)

Thread(target=poll, daemon=True).start()
fork(poll)

__call__ = update
__bool__ = is_down
4 changes: 2 additions & 2 deletions piripherals/mpd.py
Expand Up @@ -39,7 +39,7 @@ def __getattr__(self, name):
if not callable(a):
return a

def a_with_reconnect(*args, **kwargs):
def with_reconnect(*args, **kwargs):
try:
return a(*args, **kwargs)
except (MPDConnectionError, ConnectionError) as e:
Expand All @@ -50,7 +50,7 @@ def a_with_reconnect(*args, **kwargs):
self.connect(*cargs, **ckwargs)
return a(*args, **kwargs)

return a_with_reconnect
return with_reconnect

def __setattr__(self, name, value):
if hasattr(self._mpd, name):
Expand Down
17 changes: 15 additions & 2 deletions piripherals/util.py
Expand Up @@ -57,6 +57,20 @@ def check():
check()


_cleanup = 0


def cleanup_at_exit():
if not _cleanup:
atexit.register(GPIO.cleanup)
_cleanup = 1


def set_bcm():
GPIO.setmode(GPIO.BCM)
cleanup_at_exit()


class IRQHandler:
"""Abstraction of an IRQ handler.
Expand All @@ -83,8 +97,7 @@ class IRQHandler:

def __init__(self, pin, callback, edge=0, pullup=1):
if pin:
GPIO.setmode(GPIO.BCM)
atexit.register(partial(GPIO.cleanup, pin))
set_bcm()
pud = [GPIO.PUD_DOWN, GPIO.PUD_OFF, GPIO.PUD_UP][pullup + 1]
reset = GPIO.LOW if edge else GPIO.HIGH
edge = GPIO.RISING if edge else GPIO.FALLING
Expand Down

0 comments on commit 9ce21e0

Please sign in to comment.