1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
3 # SPDX-License-Identifier: MIT
4 """A Pin class for use with libgpiod 2.x."""
8 # pylint: disable=too-many-branches,too-many-statements
10 """Pins dont exist in CPython so...lets make our own!"""
19 _CONSUMER = "adafruit_blinka"
25 _value_map = (gpiod.line.Value.INACTIVE, gpiod.line.Value.ACTIVE)
27 def __init__(self, pin_id):
30 if isinstance(pin_id, tuple):
31 chip_id, self._num = pin_id
32 if isinstance(chip_id, int):
33 chip_id = f"/dev/gpiochip{chip_id}"
34 self._chip = gpiod.Chip(chip_id)
35 self._line_request = None
38 if self._line_request:
39 self._line_request.release()
44 def __eq__(self, other):
45 return self.id == other
47 def init(self, mode=IN, pull=None):
48 """Initialize the Pin"""
50 if not self._line_request:
51 line_config = gpiod.LineSettings()
54 line_config.direction = gpiod.line.Direction.INPUT
56 if pull == self.PULL_UP:
57 line_config.bias = gpiod.line.Bias.PULL_UP
58 elif pull == self.PULL_DOWN:
59 line_config.bias = gpiod.line.Bias.PULL_DOWN
60 elif pull == self.PULL_NONE:
61 line_config.bias = gpiod.line.Bias.DISABLED
63 raise RuntimeError(f"Invalid pull for pin: {self.id}")
65 elif mode == self.OUT:
67 raise RuntimeError("Cannot set pull resistor on output")
68 line_config.direction = gpiod.line.Direction.OUTPUT
71 raise RuntimeError(f"Invalid mode for pin: {self.id}")
73 self._line_request = self._chip.request_lines(
74 {int(self._num): line_config},
75 consumer=self._CONSUMER,
78 def value(self, val=None):
79 """Set or return the Pin Value"""
81 return bool(self._value_map.index(self._line_request.get_value(self._num)))
83 if val in (self.LOW, self.HIGH):
85 self._line_request.set_value(self._num, self._value_map[int(val)])
87 raise RuntimeError("Invalid value for pin")