mopidy-raspberrypi-gpio/mopidy_raspberry_gpio/frontend.py

83 lines
2.4 KiB
Python
Raw Normal View History

import logging
import pykka
2019-11-21 19:14:34 +01:00
from mopidy import core
logger = logging.getLogger(__name__)
2019-10-10 14:16:37 +02:00
class RaspberryGPIOFrontend(pykka.ThreadingActor, core.CoreListener):
def __init__(self, config, core):
2019-11-21 19:11:43 +01:00
super().__init__()
2019-10-10 14:16:37 +02:00
import RPi.GPIO as GPIO
2019-11-21 19:13:31 +01:00
2019-10-10 14:16:37 +02:00
self.core = core
self.config = config["raspberry-gpio"]
self.pin_settings = {}
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# Iterate through any bcmN pins in the config
# and set them up as inputs with edge detection
for key in self.config:
if key.startswith("bcm"):
pin = int(key.replace("bcm", ""))
2019-10-10 14:49:20 +02:00
settings = self.config[key]
if settings is None:
continue
2019-10-10 16:52:43 +02:00
2019-10-10 14:16:37 +02:00
pull = GPIO.PUD_UP
edge = GPIO.FALLING
2019-11-21 19:13:31 +01:00
if settings.active == "active_high":
2019-10-10 14:16:37 +02:00
pull = GPIO.PUD_DOWN
edge = GPIO.RISING
2019-11-21 19:13:31 +01:00
GPIO.setup(pin, GPIO.IN, pull_up_down=pull)
2019-10-10 14:16:37 +02:00
GPIO.add_event_detect(
pin,
edge,
callback=self.gpio_event,
2019-11-21 19:13:31 +01:00
bouncetime=settings.bouncetime,
)
2019-10-10 14:49:20 +02:00
self.pin_settings[pin] = settings
2019-10-10 14:16:37 +02:00
def gpio_event(self, pin):
settings = self.pin_settings[pin]
self.dispatch_input(settings.event)
def dispatch_input(self, event):
2019-11-21 19:11:43 +01:00
handler_name = f"handle_{event}"
2019-10-10 14:16:37 +02:00
try:
2019-10-10 14:49:20 +02:00
getattr(self, handler_name)()
2019-10-10 14:16:37 +02:00
except AttributeError:
raise RuntimeError(
2019-11-21 19:11:43 +01:00
f"Could not find input handler for event: {event}"
2019-10-10 14:16:37 +02:00
)
def handle_play_pause(self):
if self.core.playback.state.get() == core.PlaybackState.PLAYING:
self.core.playback.pause()
else:
self.core.playback.play()
def handle_next(self):
self.core.playback.next()
def handle_prev(self):
self.core.playback.previous()
def handle_volume_up(self):
volume = self.core.playback.volume.get()
2019-10-10 17:08:19 +02:00
volume += 5
volume = min(volume, 100)
2019-10-10 14:16:37 +02:00
self.core.playback.volume = volume
def handle_volume_down(self):
volume = self.core.playback.volume.get()
2019-10-10 17:08:19 +02:00
volume -= 5
volume = max(volume, 0)
2019-10-10 14:16:37 +02:00
self.core.playback.volume = volume