-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpioService.py
71 lines (59 loc) · 2.66 KB
/
gpioService.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from gpiozero import Button, RotaryEncoder, DigitalOutputDevice
from enum import Enum
class GPIODevice(Enum):
ROTARY_ENCODER=1
ROTARY_ENCODER_CW=2
ROTARY_ENCODER_CCW=3
ENCODER_SWITCH=4
SHUTTER=5
class GPIOService:
def __init__(self):
self.__setupShutterButton(19)
self.__setupRotaryEncoder(cwPin=13, ccwPin=6, switchPin=5, powerPin=12)
def __setupShutterButton(self, pin: int):
self.shutter = Button(pin)
self.shutterSubscribers = {}
self.shutter.when_pressed = self.__handler_generator(self.shutterSubscribers)
def __setupRotaryEncoder(self, cwPin: int, ccwPin: int, switchPin: int, powerPin: int=None):
if powerPin != None:
self.power = DigitalOutputDevice(powerPin)
self.power.on()
self.rotor = RotaryEncoder(cwPin, ccwPin)
self.rotorSubscribers = {}
self.cwSubscribers = {}
self.ccwSubscribers = {}
self.rotor.when_rotated = self.__handler_generator(self.rotorSubscribers)
self.rotor.when_rotated_clockwise = self.__handler_generator(self.cwSubscribers)
self.rotor.when_rotated_counter_clockwise = self.__handler_generator(self.ccwSubscribers)
self.switch = Button(switchPin)
self.switchSubscribers = {}
self.switch.when_pressed = self.__handler_generator(self.switchSubscribers)
def __handler_generator(self, subscribers):
def handle():
for callback in subscribers.values():
callback()
return handle
def subscribe(self, device: GPIODevice, callback) -> int:
subRef = id(callback)
if device == GPIODevice.ROTARY_ENCODER:
self.rotorSubscribers[subRef] = callback
elif device == GPIODevice.ROTARY_ENCODER_CW:
self.cwSubscribers[subRef] = callback
elif device == GPIODevice.ROTARY_ENCODER_CCW:
self.ccwSubscribers[subRef] = callback
elif device == GPIODevice.ENCODER_SWITCH:
self.switchSubscribers[subRef] = callback
elif device == GPIODevice.SHUTTER:
self.shutterSubscribers[subRef] = callback
return subRef
def unsubscribe(self, device: GPIODevice, subRef: int):
if device == GPIODevice.ROTARY_ENCODER:
del self.rotorSubscribers[subRef]
elif device == GPIODevice.ROTARY_ENCODER_CW:
del self.cwSubscribers[subRef]
elif device == GPIODevice.ROTARY_ENCODER_CCW:
del self.ccwSubscribers[subRef]
elif device == GPIODevice.ENCODER_SWITCH:
del self.switchSubscribers[subRef]
elif device == GPIODevice.SHUTTER:
del self.shutterSubscribers[subRef]