1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
 
   3 # SPDX-License-Identifier: MIT
 
   4 """A Pin class for use with libgpiod."""
 
   9         "libgpiod Python bindings not found, please install and try again! See "
 
  10         "https://github.com/adafruit/Raspberry-Pi-Installer-Scripts/blob/master/libgpiod.sh"
 
  15     """Pins dont exist in CPython so...lets make our own!"""
 
  24     _CONSUMER = "adafruit_blinka"
 
  30     def __init__(self, pin_id):
 
  32         if isinstance(pin_id, tuple):
 
  33             self._num = int(pin_id[1])
 
  34             self._chip = gpiod.chip(str(pin_id[0]), gpiod.chip.OPEN_BY_NUMBER)
 
  36             self._num = int(pin_id)
 
  37             self._chip = gpiod.chip("gpiochip0", gpiod.chip.OPEN_BY_NAME)
 
  43     def __eq__(self, other):
 
  44         return self.id == other
 
  46     def init(self, mode=IN, pull=None):
 
  47         """Initialize the Pin"""
 
  49             self._line = self._chip.get_line(int(self._num))
 
  50             # print("init line: ", self.id, self._line)
 
  56                     if pull == self.PULL_UP:
 
  57                         raise NotImplementedError(
 
  58                             "Internal pullups not supported in libgpiod, "
 
  59                             "use physical resistor instead!"
 
  61                     if pull == self.PULL_DOWN:
 
  62                         raise NotImplementedError(
 
  63                             "Internal pulldowns not supported in libgpiod, "
 
  64                             "use physical resistor instead!"
 
  66                     raise RuntimeError("Invalid pull for pin: %s" % self.id)
 
  71                     consumer=self._CONSUMER, type=gpiod.LINE_REQ_DIR_IN, flags=flags
 
  74             elif mode == self.OUT:
 
  76                     raise RuntimeError("Cannot set pull resistor on output")
 
  79                 self._line.request(consumer=self._CONSUMER, type=gpiod.LINE_REQ_DIR_OUT)
 
  82                 raise RuntimeError("Invalid mode for pin: %s" % self.id)
 
  84     def value(self, val=None):
 
  85         """Set or return the Pin Value"""
 
  87             return self._line.get_value()
 
  89         if val in (self.LOW, self.HIGH):
 
  91             self._line.set_value(val)
 
  93         raise RuntimeError("Invalid value for pin")