_gpio.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # python-cc1101 - Python Library to Transmit RF Signals via CC1101 Transceivers
  2. #
  3. # Copyright (C) 2021 Fabian Peter Hammerle <fabian@hammerle.me>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import pathlib
  18. import typing
  19. ChipSelector = typing.Union[pathlib.Path, str, int]
  20. def _format_chip_selector(selector: ChipSelector) -> str:
  21. if isinstance(selector, int):
  22. return "/dev/gpiochip{}".format(selector)
  23. return str(selector)
  24. def get_line(chip_selector: ChipSelector, line_name: str) -> "gpiod.line": # type: ignore
  25. # lazy import to protect stable API against incompatilibities in hhk7734/python3-gpiod
  26. # e.g., incompatibility of v1.5.0 with python3.5&3.6 (python_requires not set)
  27. import gpiod # pylint: disable=import-outside-toplevel
  28. try:
  29. chip = gpiod.chip(chip_selector)
  30. except PermissionError as exc:
  31. raise PermissionError(
  32. "Failed to access GPIO chip {}.".format(
  33. _format_chip_selector(chip_selector)
  34. )
  35. + "\nVerify that the current user has read and write access."
  36. + "\nOn some systems, like Raspberry Pi OS / Raspbian,"
  37. + "\n\tsudo usermod -a -G gpio $USER"
  38. + "\nfollowed by a re-login grants sufficient permissions."
  39. ) from exc
  40. except (FileNotFoundError, OSError, TypeError) as exc:
  41. raise FileNotFoundError(
  42. "Failed to find GPIO chip {}.".format(_format_chip_selector(chip_selector))
  43. + "\nRun command `gpiodetect` or `gpioinfo` to view available GPIO chips."
  44. ) from exc
  45. line = chip.find_line(name=line_name)
  46. try:
  47. line.name
  48. except RuntimeError as exc:
  49. raise ValueError(
  50. "Failed to find GPIO line with name {!r}.".format(line_name)
  51. + "\nRun command `gpioinfo` to view the names of all available GPIO lines."
  52. ) from exc
  53. return line