cloudform

linux gpio

Mar 6th, 2015
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. import functools
  2. import threading
  3. import os
  4.  
  5. path = os.path
  6. pjoin = os.path.join
  7.  
  8. gpio_root = '/sys/class/gpio'
  9. gpiopath = lambda pin: os.path.join(gpio_root, 'gpio{}'.format(pin))
  10. _export_lock = threading.Lock()
  11.  
  12. _pyset = set
  13.  
  14. _open = dict()
  15. FMODE = 'w+'
  16.  
  17. IN, OUT = 'in', 'out'
  18.  
  19.  
  20. def _write(f, v):
  21. f.write(str(v))
  22.  
  23.  
  24. def _read(f):
  25. f.seek(0)
  26. return f.read()
  27.  
  28.  
  29. def _verify(function):
  30. """decorator to ensure pin is properly set up"""
  31. @functools.wraps
  32. def wrapped(pin, *args, **kwargs):
  33. pin = int(pin)
  34. if pin not in _open:
  35. ppath = gpiopath(pin)
  36. if not os.path.exists(ppath):
  37. with _export_lock:
  38. with open(pjoin(gpio_root, 'export'), 'w') as f:
  39. _write(f, pin)
  40. _open[pin] = {
  41. 'value': open(pjoin(ppath, 'value'), FMODE),
  42. 'direction': open(pjoin(ppath, 'direction'), FMODE),
  43. 'drive': open(pjoin(ppath, 'drive'), FMODE)
  44. }
  45. return function(pin, *args, **kwargs)
  46. return wrapped
  47.  
  48.  
  49. @_verify
  50. def setup(pin, mode, pullup=None):
  51. if mode not in {IN, OUT}:
  52. raise ValueError(mode)
  53. f = _open[pin]['direction']
  54. _write(f, mode)
  55.  
  56.  
  57. @_verify
  58. def mode(pin):
  59. '''get the pin mode'''
  60. f = _open[pin]['direction']
  61. return _read(f)
  62.  
  63.  
  64. @_verify
  65. def read(pin):
  66. '''read the pin value
  67.  
  68. Returns:
  69. bool: 0 or 1
  70. '''
  71. f = _open[pin]['value']
  72. return _read(f)
  73.  
  74.  
  75. @_verify
  76. def set(pin, value):
  77. '''set the pin value to 0 or 1'''
  78. value = int(value)
  79. f = _open[pin]['value']
  80. _write(f, value)
  81.  
  82.  
  83. @_verify
  84. def input(pin):
  85. '''read the pin. Same as read'''
  86. return read(pin)
  87.  
  88.  
  89. @_verify
  90. def output(pin, value):
  91. '''set the pin. Same as set'''
  92. return set(pin)
Advertisement
Add Comment
Please, Sign In to add comment