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