]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/generic_linux/libgpiod_pin.py
51b87f9190823cb570647d5be436b20a80413a50
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / generic_linux / libgpiod_pin.py
1 try:
2     import gpiod
3 except ImportError:
4     raise ImportError("libgpiod Python bindings not found, please install and try again! See https://github.com/adafruit/Raspberry-Pi-Installer-Scripts/blob/master/libgpiod.sh")
5
6 # Pins dont exist in CPython so...lets make our own!
7 class Pin:
8     IN = 0
9     OUT = 1
10     LOW = 0
11     HIGH = 1
12     PULL_NONE = 0
13     PULL_UP = 1
14     PULL_DOWN = 2
15     _CONSUMER = 'adafruit_blinka'
16
17     id = None
18     _value = LOW
19     _mode = IN
20
21     def __init__(self, pin_number, gpiod_chipname="gpiochip0"):
22         self.id = int(pin_number)
23         # FIXME: Presumably this might vary by system:
24         self._chip = gpiod.Chip(gpiod_chipname, gpiod.Chip.OPEN_BY_NAME)
25         self._line = None
26
27     def __repr__(self):
28         return str(self.id)
29
30     def __eq__(self, other):
31         return self.id == other
32
33     def init(self, mode=IN, pull=None):
34         if not self._line:
35             self._line = self._chip.get_line(int(self.id))
36             print("init line: ", int(self.id), self._line)
37
38         if mode != None:
39             if mode == self.IN:
40                 flags = 0
41                 if pull != None:
42                     if pull == self.PULL_UP:
43                         flags |= gpiod.LINE_REQ_FLAG_ACTIVE_LOW
44                     elif pull == self.PULL_DOWN:
45                         flags |= gpiod.LINE_REQ_FLAG_ACTIVE_HIGH
46                     else:
47                         raise RuntimeError("Invalid pull for pin: %s" % self.id)
48
49                 self._mode = self.IN
50                 self._line.release()
51                 self._line.request(consumer=self._CONSUMER,
52                                    type=gpiod.LINE_REQ_DIR_IN,
53                                    flags=flags)
54
55             elif mode == self.OUT:
56                 if pull != None:
57                     raise RuntimeError("Cannot set pull resistor on output")
58                 self._mode = self.OUT
59                 self._line.release()
60                 self._line.request(consumer=self._CONSUMER,
61                                    type=gpiod.LINE_REQ_DIR_OUT)
62
63             else:
64                 raise RuntimeError("Invalid mode for pin: %s" % self.id)
65
66     def value(self, val=None):
67         if val != None:
68             if val in (self.LOW, self.HIGH):
69                 self._value = val
70                 self._line.set_value(val)
71             else:
72                 raise RuntimeError("Invalid value for pin")
73         else:
74             return self._line.get_value()