forked from vitiral/gpio
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gpio.py
201 lines (153 loc) · 4.75 KB
/
gpio.py
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
# -*- coding: utf-8 -*-
__version__ = '0.2.0'
import threading
import os
import sys
import traceback
import pdb
import logging
# logging.basicConfig(level=logging.ERROR)
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)
def except_hook(exctype, value, tb):
traceback.print_tb(tb)
print(repr(value))
pdb.post_mortem(tb)
class PinState(object):
"""An ultra simple pin-state object.
Keeps track data related to each pin.
Args:
value: the file pointer to set/read value of pin.
direction: the file pointer to set/read direction of the pin.
"""
def __init__(self, value, direction):
self.value = value
self.direction = direction
sys.excepthook = except_hook
path = os.path
pjoin = os.path.join
gpio_root = '/sys/class/gpio'
gpiopath = lambda pin: os.path.join(gpio_root, 'gpio{0}'.format(pin))
_export_lock = threading.Lock()
_pyset = set
_open = dict()
FMODE = 'w+'
IN, OUT = 'in', 'out'
LOW, HIGH = 'low', 'high'
def _write(f, v):
log.debug("writing: {0}: {1}".format(f, v))
f.write(str(v))
f.flush()
def _read(f):
log.debug("Reading: {0}".format(f))
f.seek(0)
return f.read().strip()
def _verify(function):
"""decorator to ensure pin is properly set up"""
# @functools.wraps
def wrapped(pin, *args, **kwargs):
pin = int(pin)
if pin not in _open:
ppath = gpiopath(pin)
if not os.path.exists(ppath):
log.debug("Creating Pin {0}".format(pin))
with _export_lock:
with open(pjoin(gpio_root, 'export'), 'w') as f:
_write(f, pin)
value = open(pjoin(ppath, 'value'), FMODE)
direction = open(pjoin(ppath, 'direction'), FMODE)
_open[pin] = PinState(value=value, direction=direction)
return function(pin, *args, **kwargs)
return wrapped
def cleanup(pin=None, assert_exists=False):
"""Cleanup the pin by closing and unexporting it.
Args:
pin (int, optional): either the pin to clean up or None (default).
If None, clean up all pins.
assert_exists: if True, raise a ValueError if the pin was not
setup. Otherwise, this function is a NOOP.
"""
if pin is None:
# Take a list of keys because we will be deleting from _open
for pin in list(_open):
cleanup(pin)
return
if not isinstance(pin, int):
raise TypeError("pin must be an int, got: {}".format(pin))
state = _open.get(pin)
if state is None:
if assert_exists:
raise ValueError("pin {} was not setup".format(pin))
return
state.value.close()
state.direction.close()
if os.path.exists(gpiopath(pin)):
log.debug("Unexporting pin {0}".format(pin))
with _export_lock:
with open(pjoin(gpio_root, 'unexport'), 'w') as f:
_write(f, pin)
del _open[pin]
@_verify
def setup(pin, mode, pullup=None, initial=False):
'''Setup pin with mode IN or OUT.
Args:
pin (int):
mode (str): use either gpio.OUT or gpio.IN
pullup (None): rpio compatibility. If anything but None, raises
value Error
pullup (bool, optional): Initial pin value. Default is False
'''
if pullup is not None:
raise ValueError("sysfs does not support pullups")
if mode not in (IN, OUT, LOW, HIGH):
raise ValueError(mode)
log.debug("Setup {0}: {1}".format(pin, mode))
f = _open[pin].direction
_write(f, mode)
if mode == OUT:
if initial:
set(pin, 1)
else:
set(pin, 0)
@_verify
def mode(pin):
'''get the pin mode
Returns:
str: "in" or "out"
'''
f = _open[pin].direction
return _read(f)
@_verify
def read(pin):
'''read the pin value
Returns:
bool: 0 or 1
'''
f = _open[pin].value
out = int(_read(f))
log.debug("Read {0}: {1}".format(pin, out))
return out
@_verify
def set(pin, value):
'''set the pin value to 0 or 1'''
if value is LOW:
value = 0
value = int(bool(value))
log.debug("Write {0}: {1}".format(pin, value))
f = _open[pin].value
_write(f, value)
@_verify
def input(pin):
'''read the pin. Same as read'''
return read(pin)
@_verify
def output(pin, value):
'''set the pin. Same as set'''
return set(pin, value)
def setwarnings(value):
'''exists for rpio compatibility'''
pass
def setmode(value):
'''exists for rpio compatibility'''
pass
BCM = None # rpio compatibility