summaryrefslogtreecommitdiff
path: root/kvmd/gpio.py
blob: deb583ca07a51fca1c64edd4134e5b18d0614cfb (plain)
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
import contextlib

from typing import Generator

from RPi import GPIO

from .logging import get_logger


# =====
@contextlib.contextmanager
def bcm() -> Generator[None, None, None]:
    logger = get_logger(2)
    GPIO.setmode(GPIO.BCM)
    logger.info("Configured GPIO mode as BCM")
    try:
        yield
    finally:
        GPIO.cleanup()
        logger.info("GPIO cleaned")


def set_output(pin: int, initial: bool=False) -> int:
    GPIO.setup(pin, GPIO.OUT, initial=initial)
    return pin


def set_input(pin: int) -> int:
    GPIO.setup(pin, GPIO.IN)
    return pin


def read(pin: int) -> bool:
    return bool(GPIO.input(pin))


def write(pin: int, flag: bool) -> None:
    GPIO.output(pin, flag)