File: gpio.py

package info (click to toggle)
python-periphery 2.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 424 kB
  • sloc: python: 3,496; makefile: 21
file content (370 lines) | stat: -rw-r--r-- 9,960 bytes parent folder | download
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
365
366
367
368
369
370
import collections
import os
import select


class GPIOError(IOError):
    """Base class for GPIO errors."""
    pass


class EdgeEvent(collections.namedtuple('EdgeEvent', ['edge', 'timestamp'])):
    def __new__(cls, edge, timestamp):
        """EdgeEvent containing the event edge and event time reported by Linux.

        Args:
            edge (str): event edge, either "rising" or "falling".
            timestamp (int): event time in nanoseconds.
        """
        return super(EdgeEvent, cls).__new__(cls, edge, timestamp)


class GPIO(object):
    def __new__(cls, *args, **kwargs):
        if len(args) > 2:
            return CdevGPIO.__new__(cls, *args, **kwargs)
        else:
            return SysfsGPIO.__new__(cls, *args, **kwargs)

    def __del__(self):
        self.close()

    def __enter__(self):
        return self

    def __exit__(self, t, value, traceback):
        self.close()

    # Methods

    def read(self):
        """Read the state of the GPIO.

        Returns:
            bool: ``True`` for high state, ``False`` for low state.

        Raises:
            GPIOError: if an I/O or OS error occurs.

        """
        raise NotImplementedError()

    def write(self, value):
        """Set the state of the GPIO to `value`.

        Args:
            value (bool): ``True`` for high state, ``False`` for low state.

        Raises:
            GPIOError: if an I/O or OS error occurs.
            TypeError: if `value` type is not bool.

        """
        raise NotImplementedError()

    def poll(self, timeout=None):
        """Poll a GPIO for the edge event configured with the .edge property
        with an optional timeout.

        For character device GPIOs, the edge event should be consumed with
        `read_event()`. For sysfs GPIOs, the edge event should be consumed with
        `read()`.

        `timeout` can be a positive number for a timeout in seconds, zero for a
        non-blocking poll, or negative or None for a blocking poll. Default is
        a blocking poll.

        Args:
            timeout (int, float, None): timeout duration in seconds.

        Returns:
            bool: ``True`` if an edge event occurred, ``False`` on timeout.

        Raises:
            GPIOError: if an I/O or OS error occurs.
            TypeError: if `timeout` type is not None or int.

        """
        raise NotImplementedError()

    def read_event(self):
        """Read the edge event that occurred with the GPIO.

        This method is intended for use with character device GPIOs and is
        unsupported by sysfs GPIOs.

        Returns:
            EdgeEvent: a namedtuple containing the string edge event that
            occurred (either ``"rising"`` or ``"falling"``), and the event time
            reported by Linux in nanoseconds.

        Raises:
            GPIOError: if an I/O or OS error occurs.
            NotImplementedError: if called on a sysfs GPIO.

        """
        raise NotImplementedError()

    @staticmethod
    def poll_multiple(gpios, timeout=None):
        """Poll multiple GPIOs for the edge event configured with the .edge
        property with an optional timeout.

        For character device GPIOs, the edge event should be consumed with
        `read_event()`. For sysfs GPIOs, the edge event should be consumed with
        `read()`.

        `timeout` can be a positive number for a timeout in seconds, zero for a
        non-blocking poll, or negative or None for a blocking poll. Default is
        a blocking poll.

        Args:
            gpios (list): list of GPIO objects to poll.
            timeout (int, float, None): timeout duration in seconds.

        Returns:
            list: list of GPIO objects for which an edge event occurred.

        Raises:
            GPIOError: if an I/O or OS error occurs.
            TypeError: if `timeout` type is not None or int.

        """
        if not isinstance(timeout, (int, float, type(None))):
            raise TypeError("Invalid timeout type, should be integer, float, or None.")

        # Setup poll
        p = select.poll()

        # Register GPIO file descriptors and build map of fd to object
        fd_gpio_map = {}
        for gpio in gpios:
            if isinstance(gpio, SysfsGPIO):
                p.register(gpio.fd, select.POLLPRI | select.POLLERR)
            else:
                p.register(gpio.fd, select.POLLIN | select.POLLRDNORM)

            fd_gpio_map[gpio.fd] = gpio

        # Scale timeout to milliseconds
        if isinstance(timeout, (int, float)) and timeout > 0:
            timeout *= 1000

        # Poll
        events = p.poll(timeout)

        # Gather GPIOs that had edge events occur
        results = []
        for (fd, _) in events:
            gpio = fd_gpio_map[fd]

            results.append(gpio)

            if isinstance(gpio, SysfsGPIO):
                # Rewind for read
                try:
                    os.lseek(fd, 0, os.SEEK_SET)
                except OSError as e:
                    raise GPIOError(e.errno, "Rewinding GPIO: " + e.strerror)

        return results

    def close(self):
        """Close the GPIO.

        Raises:
            GPIOError: if an I/O or OS error occurs.

        """
        raise NotImplementedError()

    # Immutable properties

    @property
    def devpath(self):
        """Get the device path of the underlying GPIO device.

        :type: str
        """
        raise NotImplementedError()

    @property
    def fd(self):
        """Get the line file descriptor of the GPIO object.

        :type: int
        """
        raise NotImplementedError()

    @property
    def line(self):
        """Get the GPIO object's line number.

        :type: int
        """
        raise NotImplementedError()

    @property
    def name(self):
        """Get the line name of the GPIO.

        This method is intended for use with character device GPIOs and always
        returns the empty string for sysfs GPIOs.

        :type: str
        """
        raise NotImplementedError()

    @property
    def label(self):
        """Get the line consumer label of the GPIO.

        This method is intended for use with character device GPIOs and always
        returns the empty string for sysfs GPIOs.

        :type: str
        """
        raise NotImplementedError()

    @property
    def chip_fd(self):
        """Get the GPIO chip file descriptor of the GPIO object.

        This method is intended for use with character device GPIOs and is unsupported by sysfs GPIOs.

        Raises:
            NotImplementedError: if accessed on a sysfs GPIO.

        :type: int
        """
        raise NotImplementedError()

    @property
    def chip_name(self):
        """Get the name of the GPIO chip associated with the GPIO.

        :type: str
        """
        raise NotImplementedError()

    @property
    def chip_label(self):
        """Get the label of the GPIO chip associated with the GPIO.

        :type: str
        """
        raise NotImplementedError()

    # Mutable properties

    def _get_direction(self):
        raise NotImplementedError()

    def _set_direction(self, direction):
        raise NotImplementedError()

    direction = property(_get_direction, _set_direction)
    """Get or set the GPIO's direction. Can be "in", "out", "high", "low".

    Direction "in" is input; "out" is output, initialized to low; "high" is
    output, initialized to high; and "low" is output, initialized to low.

    Raises:
        GPIOError: if an I/O or OS error occurs.
        TypeError: if `direction` type is not str.
        ValueError: if `direction` value is invalid.

    :type: str
    """

    def _get_edge(self):
        raise NotImplementedError()

    def _set_edge(self, edge):
        raise NotImplementedError()

    edge = property(_get_edge, _set_edge)
    """Get or set the GPIO's interrupt edge. Can be "none", "rising",
    "falling", "both".

    Raises:
        GPIOError: if an I/O or OS error occurs.
        TypeError: if `edge` type is not str.
        ValueError: if `edge` value is invalid.

    :type: str
    """

    def _get_bias(self):
        raise NotImplementedError()

    def _set_bias(self, bias):
        raise NotImplementedError()

    bias = property(_get_bias, _set_bias)
    """Get or set the GPIO's line bias. Can be "default", "pull_up",
    "pull_down", "disable".

    This property is not supported by sysfs GPIOs.

    Raises:
        GPIOError: if an I/O or OS error occurs.
        TypeError: if `bias` type is not str.
        ValueError: if `bias` value is invalid.

    :type: str
    """

    def _get_drive(self):
        raise NotImplementedError()

    def _set_drive(self, drive):
        raise NotImplementedError()

    drive = property(_get_drive, _set_drive)
    """Get or set the GPIO's line drive. Can be "default" (for push-pull),
    "open_drain", "open_source".

    This property is not supported by sysfs GPIOs.

    Raises:
        GPIOError: if an I/O or OS error occurs.
        TypeError: if `drive` type is not str.
        ValueError: if `drive` value is invalid.

    :type: str
    """

    def _get_inverted(self):
        raise NotImplementedError()

    def _set_inverted(self, inverted):
        raise NotImplementedError()

    inverted = property(_get_inverted, _set_inverted)
    """Get or set the GPIO's inverted (active low) property.

    Raises:
        GPIOError: if an I/O or OS error occurs.
        TypeError: if `inverted` type is not bool.

    :type: bool
    """

    # String representation

    def __str__(self):
        """Get the string representation of the GPIO.

        :type: str
        """
        raise NotImplementedError()


# Assign GPIO classes
from . import gpio_cdev1
from . import gpio_cdev2
from . import gpio_sysfs

CdevGPIO = gpio_cdev2.Cdev2GPIO if gpio_cdev2.Cdev2GPIO.SUPPORTED else gpio_cdev1.Cdev1GPIO
SysfsGPIO = gpio_sysfs.SysfsGPIO