2023-08-18 07:32:23 +08:00
|
|
|
import os
|
2023-07-24 02:54:51 +08:00
|
|
|
from functools import lru_cache
|
2023-04-06 07:35:27 +08:00
|
|
|
from typing import Optional, List
|
2022-09-01 14:12:26 +08:00
|
|
|
|
2022-04-27 02:02:40 +08:00
|
|
|
def gpio_init(pin: int, output: bool) -> None:
|
2020-08-24 22:56:29 +08:00
|
|
|
try:
|
|
|
|
with open(f"/sys/class/gpio/gpio{pin}/direction", 'wb') as f:
|
|
|
|
f.write(b"out" if output else b"in")
|
|
|
|
except Exception as e:
|
|
|
|
print(f"Failed to set gpio {pin} direction: {e}")
|
|
|
|
|
2022-04-27 02:02:40 +08:00
|
|
|
def gpio_set(pin: int, high: bool) -> None:
|
2020-08-24 22:56:29 +08:00
|
|
|
try:
|
|
|
|
with open(f"/sys/class/gpio/gpio{pin}/value", 'wb') as f:
|
|
|
|
f.write(b"1" if high else b"0")
|
|
|
|
except Exception as e:
|
|
|
|
print(f"Failed to set gpio {pin} value: {e}")
|
2022-09-01 14:12:26 +08:00
|
|
|
|
|
|
|
def gpio_read(pin: int) -> Optional[bool]:
|
|
|
|
val = None
|
|
|
|
try:
|
|
|
|
with open(f"/sys/class/gpio/gpio{pin}/value", 'rb') as f:
|
|
|
|
val = bool(int(f.read().strip()))
|
|
|
|
except Exception as e:
|
|
|
|
print(f"Failed to set gpio {pin} value: {e}")
|
|
|
|
|
|
|
|
return val
|
2023-04-06 07:35:27 +08:00
|
|
|
|
2023-07-27 07:01:26 +08:00
|
|
|
def gpio_export(pin: int) -> None:
|
2023-08-18 07:32:23 +08:00
|
|
|
if os.path.isdir(f"/sys/class/gpio/gpio{pin}"):
|
|
|
|
return
|
|
|
|
|
2023-07-27 06:12:01 +08:00
|
|
|
try:
|
|
|
|
with open("/sys/class/gpio/export", 'w') as f:
|
|
|
|
f.write(str(pin))
|
|
|
|
except Exception:
|
|
|
|
print(f"Failed to export gpio {pin}")
|
|
|
|
|
2023-07-24 02:54:51 +08:00
|
|
|
@lru_cache(maxsize=None)
|
2023-07-23 08:15:58 +08:00
|
|
|
def get_irq_action(irq: int) -> List[str]:
|
|
|
|
try:
|
|
|
|
with open(f"/sys/kernel/irq/{irq}/actions") as f:
|
2023-04-06 07:35:27 +08:00
|
|
|
actions = f.read().strip().split(',')
|
2023-07-23 08:15:58 +08:00
|
|
|
return actions
|
|
|
|
except FileNotFoundError:
|
|
|
|
return []
|
|
|
|
|
|
|
|
def get_irqs_for_action(action: str) -> List[str]:
|
|
|
|
ret = []
|
|
|
|
with open("/proc/interrupts") as f:
|
|
|
|
for l in f.readlines():
|
|
|
|
irq = l.split(':')[0].strip()
|
|
|
|
if irq.isdigit() and action in get_irq_action(irq):
|
2023-04-06 07:35:27 +08:00
|
|
|
ret.append(irq)
|
|
|
|
return ret
|