_gpio.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import pathlib
  2. import typing
  3. import gpiod
  4. ChipSelector = typing.Union[pathlib.Path, str, int]
  5. def _format_chip_selector(selector: ChipSelector) -> str:
  6. if isinstance(selector, int):
  7. return "/dev/gpiochip{}".format(selector)
  8. return str(selector)
  9. def get_line(chip_selector: ChipSelector, line_name: str) -> gpiod.line:
  10. try:
  11. chip = gpiod.chip(chip_selector)
  12. except PermissionError as exc:
  13. raise PermissionError(
  14. "Failed to access GPIO chip {}.".format(
  15. _format_chip_selector(chip_selector)
  16. )
  17. + "\nVerify that the current user has read and write access."
  18. + "\nOn some systems, like Raspberry Pi OS / Raspbian,"
  19. + "\n\tsudo usermod -a -G gpio $USER"
  20. + "\nfollowed by a re-login grants sufficient permissions."
  21. ) from exc
  22. except (FileNotFoundError, OSError, TypeError) as exc:
  23. raise FileNotFoundError(
  24. "Failed to find GPIO chip {}.".format(_format_chip_selector(chip_selector))
  25. + "\nRun command `gpiodetect` or `gpioinfo` to view available GPIO chips."
  26. ) from exc
  27. line = chip.find_line(name=line_name)
  28. try:
  29. line.name
  30. except RuntimeError as exc:
  31. raise ValueError(
  32. "Failed to find GPIO line with name {!r}.".format(line_name)
  33. + "\nRun command `gpioinfo` to view the names of all available GPIO lines."
  34. ) from exc
  35. return line