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