1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
|
# SPDX-License-Identifier: LGPL-2.1-or-later
# SPDX-FileCopyrightText: 2022 Bartosz Golaszewski <brgl@bgdev.pl>
from . import _ext
from .chip_info import ChipInfo
from .exception import ChipClosedError
from .info_event import InfoEvent
from .internal import poll_fd
from .line import Value
from .line_info import LineInfo
from .line_settings import LineSettings, _line_settings_to_ext
from .line_request import LineRequest
from collections import Counter
from collections.abc import Iterable
from datetime import timedelta
from errno import ENOENT
from select import select
from typing import Union, Optional
__all__ = "Chip"
class Chip:
"""
Represents a GPIO chip.
Chip object manages all resources associated with the GPIO chip it represents.
The gpiochip device file is opened during the object's construction. The Chip
object's constructor takes the path to the GPIO chip device file
as the only argument.
Callers must close the chip by calling the close() method when it's no longer
used.
Example::
chip = gpiod.Chip(\"/dev/gpiochip0\")
do_something(chip)
chip.close()
The gpiod.Chip class also supports controlled execution ('with' statement).
Example::
with gpiod.Chip(path="/dev/gpiochip0") as chip:
do_something(chip)
"""
def __init__(self, path: str):
"""
Open a GPIO device.
Args:
path:
Path to the GPIO character device file.
"""
self._chip = _ext.Chip(path)
self._info = None
def __bool__(self) -> bool:
"""
Boolean conversion for GPIO chips.
Returns:
True if the chip is open and False if it's closed.
"""
return True if self._chip else False
def __enter__(self):
"""
Controlled execution enter callback.
"""
self._check_closed()
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
"""
Controlled execution exit callback.
"""
self.close()
def _check_closed(self) -> None:
if not self._chip:
raise ChipClosedError()
def close(self) -> None:
"""
Close the associated GPIO chip descriptor. The chip object must no
longer be used after this method is called.
"""
self._check_closed()
self._chip.close()
self._chip = None
def get_info(self) -> ChipInfo:
"""
Get the information about the chip.
Returns:
New gpiod.ChipInfo object.
"""
self._check_closed()
if not self._info:
self._info = self._chip.get_info()
return self._info
def line_offset_from_id(self, id: Union[str, int]) -> int:
"""
Map a line's identifier to its offset within the chip.
Args:
id:
Name of the GPIO line, its offset as a string or its offset as an
integer.
Returns:
If id is an integer - it's returned as is (unless it's out of range
for this chip). If it's a string, the method tries to interpret it as
the name of the line first and tries too perform a name lookup within
the chip. If it fails, it tries to convert the string to an integer
and check if it represents a valid offset within the chip and if
so - returns it.
"""
self._check_closed()
if not isinstance(id, int):
try:
return self._chip.line_offset_from_id(id)
except OSError as ex:
if ex.errno == ENOENT:
try:
offset = int(id)
except ValueError:
raise ex
else:
raise ex
else:
offset = id
if offset >= self.get_info().num_lines:
raise ValueError("line offset of out range")
return offset
def _get_line_info(self, line: Union[int, str], watch: bool) -> LineInfo:
self._check_closed()
return self._chip.get_line_info(self.line_offset_from_id(line), watch)
def get_line_info(self, line: Union[int, str]) -> LineInfo:
"""
Get the snapshot of information about the line at given offset.
Args:
line:
Offset or name of the GPIO line to get information for.
Returns:
New LineInfo object.
"""
return self._get_line_info(line, watch=False)
def watch_line_info(self, line: Union[int, str]) -> LineInfo:
"""
Get the snapshot of information about the line at given offset and
start watching it for future changes.
Args:
line:
Offset or name of the GPIO line to get information for.
Returns:
New gpiod.LineInfo object.
"""
return self._get_line_info(line, watch=True)
def unwatch_line_info(self, line: Union[int, str]) -> None:
"""
Stop watching a line for status changes.
Args:
line:
Offset or name of the line to stop watching.
"""
self._check_closed()
return self._chip.unwatch_line_info(self.line_offset_from_id(line))
def wait_info_event(
self, timeout: Optional[Union[timedelta, float]] = None
) -> bool:
"""
Wait for line status change events on any of the watched lines on the
chip.
Args:
timeout:
Wait time limit represented as either a datetime.timedelta object
or the number of seconds stored in a float. If set to 0, the
method returns immediately, if set to None it blocks indefinitely.
Returns:
True if an info event is ready to be read from the chip, False if the
wait timed out without any events.
"""
self._check_closed()
return poll_fd(self.fd, timeout)
def read_info_event(self) -> InfoEvent:
"""
Read a single line status change event from the chip.
Returns:
New gpiod.InfoEvent object.
Note:
This function may block if there are no available events in the queue.
"""
self._check_closed()
return self._chip.read_info_event()
def request_lines(
self,
config: dict[tuple[Union[int, str]], Optional[LineSettings]],
consumer: Optional[str] = None,
event_buffer_size: Optional[int] = None,
output_values: Optional[dict[Union[int, str], Value]] = None,
) -> LineRequest:
"""
Request a set of lines for exclusive usage.
Args:
config:
Dictionary mapping offsets or names (or tuples thereof) to
LineSettings. If None is passed as the value of the mapping,
default settings are used.
consumer:
Consumer string to use for this request.
event_buffer_size:
Size of the kernel edge event buffer to configure for this request.
output_values:
Dictionary mapping offsets or names to line.Value. This can be used
to set the desired output values globally while reusing LineSettings
for more lines.
Returns:
New LineRequest object.
"""
self._check_closed()
line_cfg = _ext.LineConfig()
# Sanitize lines - don't allow offset repetitions or offset-name conflicts.
for offset, count in Counter(
[
self.line_offset_from_id(line)
for line in (
lambda t: [
j for i in (t) for j in (i if isinstance(i, tuple) else (i,))
]
)(tuple(config.keys()))
]
).items():
if count != 1:
raise ValueError(
"line must be configured exactly once - offset {} repeats".format(
offset
)
)
# If we have global output values - map line names to offsets
if output_values:
mapped_output_values = {
self.line_offset_from_id(line): value
for line, value in output_values.items()
}
else:
mapped_output_values = None
name_map = dict()
offset_map = dict()
global_output_values = list()
for lines, settings in config.items():
offsets = list()
if isinstance(lines, int) or isinstance(lines, str):
lines = (lines,)
for line in lines:
offset = self.line_offset_from_id(line)
offsets.append(offset)
# If there's a global output value for this offset, store it in the
# list for later.
if mapped_output_values:
global_output_values.append(
mapped_output_values[offset]
if offset in mapped_output_values
else Value.INACTIVE
)
if isinstance(line, str):
name_map[line] = offset
offset_map[offset] = line
line_cfg.add_line_settings(
offsets, _line_settings_to_ext(settings or LineSettings())
)
if len(global_output_values):
line_cfg.set_output_values(global_output_values)
req_internal = self._chip.request_lines(line_cfg, consumer, event_buffer_size)
request = LineRequest(req_internal)
request._chip_name = req_internal.chip_name
request._offsets = req_internal.offsets
request._name_map = name_map
request._offset_map = offset_map
request._lines = [
offset_map[off] if off in offset_map else off for off in request.offsets
]
return request
def __repr__(self) -> str:
"""
Return a string that can be used to re-create this chip object.
"""
if not self._chip:
return "<Chip CLOSED>"
return 'gpiod.Chip("{}")'.format(self.path)
def __str__(self) -> str:
"""
Return a user-friendly, human-readable description of this chip.
"""
if not self._chip:
return "<Chip CLOSED>"
return '<Chip path="{}" fd={} info={}>'.format(
self.path, self.fd, self.get_info()
)
@property
def path(self) -> str:
"""
Filesystem path used to open this chip.
"""
self._check_closed()
return self._chip.path
@property
def fd(self) -> int:
"""
File descriptor associated with this chip.
"""
self._check_closed()
return self._chip.fd
|