_gpio.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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 ctypes
  18. import ctypes.util
  19. import errno
  20. import functools
  21. # could not find Debian's python3-libgpiod on pypi.org
  22. # https://salsa.debian.org/debian/libgpiod does not provide setup.py or setup.cfg
  23. @functools.lru_cache(maxsize=1)
  24. def _load_libgpiod() -> ctypes.CDLL:
  25. filename = ctypes.util.find_library("gpiod")
  26. if not filename:
  27. raise FileNotFoundError(
  28. "Failed to find libgpiod."
  29. "\nOn Debian-based systems, like Raspberry Pi OS / Raspbian,"
  30. " libgpiod can be installed via"
  31. "\n\tsudo apt-get install --no-install-recommends libgpiod2"
  32. )
  33. return ctypes.CDLL(filename, use_errno=True)
  34. class _c_timespec(ctypes.Structure):
  35. """
  36. struct timespec {
  37. time_t tv_sec;
  38. long tv_nsec;
  39. };
  40. """
  41. # pylint: disable=too-few-public-methods,invalid-name; struct
  42. _fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)]
  43. class GPIOLine:
  44. def __init__(self, pointer: ctypes.c_void_p) -> None:
  45. assert pointer != 0
  46. self._pointer = pointer
  47. @classmethod
  48. def find(cls, name: bytes) -> "GPIOLine":
  49. # > If this routine succeeds, the user must manually close the GPIO chip
  50. # > owning this line to avoid memory leaks.
  51. pointer = _load_libgpiod().gpiod_line_find(name) # type: int
  52. # > If the line could not be found, this functions sets errno to ENOENT.
  53. if pointer == 0:
  54. err = ctypes.get_errno()
  55. if err == errno.EACCES:
  56. # > [PermissionError] corresponds to errno EACCES and EPERM.
  57. raise PermissionError(
  58. "Failed to access GPIO line {!r}.".format(name.decode())
  59. + "\nVerify that the current user has read and write access for /dev/gpiochip*."
  60. + "\nOn some systems, like Raspberry Pi OS / Raspbian,"
  61. + "\n\tsudo usermod -a -G gpio $USER"
  62. + "\nfollowed by a re-login grants sufficient permissions."
  63. )
  64. if err == errno.ENOENT:
  65. # > [FileNotFoundError] corresponds to errno ENOENT.
  66. # https://docs.python.org/3/library/exceptions.html#FileNotFoundError
  67. raise FileNotFoundError(
  68. "GPIO line {!r} does not exist.".format(name.decode())
  69. + "\nRun command `gpioinfo` to get a list of all available GPIO lines."
  70. )
  71. raise OSError(
  72. "Failed to open GPIO line {!r}: {}".format(
  73. name.decode(),
  74. errno.errorcode[err],
  75. )
  76. )
  77. return cls(pointer=ctypes.c_void_p(pointer))
  78. def __del__(self):
  79. # > Close a GPIO chip owning this line and release all resources.
  80. # > After this function returns, the line must no longer be used.
  81. if self._pointer:
  82. _load_libgpiod().gpiod_line_close_chip(self._pointer)
  83. # might make debugging easier in case someone calls __del__ twice
  84. self._pointer = None
  85. def wait_for_rising_edge(self, consumer: bytes, timeout_seconds: int) -> bool:
  86. """
  87. Return True, if an event occured; False on timeout.
  88. """
  89. if (
  90. _load_libgpiod().gpiod_line_request_rising_edge_events(
  91. self._pointer, consumer
  92. )
  93. != 0
  94. ):
  95. err = ctypes.get_errno()
  96. raise OSError(
  97. "Request for rising edge event notifications failed ({}).".format(
  98. errno.errorcode[err]
  99. )
  100. + ("\nBlocked by another process?" if err == errno.EBUSY else "")
  101. )
  102. timeout = _c_timespec(timeout_seconds, 0)
  103. result = _load_libgpiod().gpiod_line_event_wait(
  104. self._pointer, ctypes.pointer(timeout)
  105. ) # type: int
  106. _load_libgpiod().gpiod_line_release(self._pointer)
  107. if result == -1:
  108. raise OSError("Failed to wait for rising edge event notification.")
  109. return result == 1