_gpio.py 1.7 KB

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