59 lines
1.7 KiB
Python
59 lines
1.7 KiB
Python
import time
|
|
import sys
|
|
import errno
|
|
|
|
GPIO_IFACE_MISSING = -1
|
|
GPIO_PIN_EXP_FAIL = -2
|
|
GPIO_DIR_CONT_FAIL = -3
|
|
GPIO_SWITCH_FAIL = -4
|
|
GPIO_PIN_UNX_NF = -5
|
|
GPIO_PIN_UNX_FAIL = -6
|
|
|
|
PINLISTMISS = -1
|
|
PINLISTTOKFAIL = -2
|
|
|
|
def preparePin(pinno):
|
|
try: x = open('/sys/class/gpio/export', 'w')
|
|
except:
|
|
return GPIO_IFACE_MISSING
|
|
else:
|
|
try:
|
|
x.write(f'{pinno}')
|
|
x.close()
|
|
except OSError as e:
|
|
if (e.errno != errno.EBUSY): # Busy devices are already exported
|
|
return GPIO_PIN_EXP_FAIL
|
|
return
|
|
for i in range(0,5):
|
|
try: g = open(f'/sys/class/gpio/gpio{pinno}/direction', 'w')
|
|
except:
|
|
if (i == 4):
|
|
return GPIO_DIR_CONT_FAIL
|
|
else: time.sleep(1)
|
|
else:
|
|
try: g.write('out')
|
|
except:
|
|
g.close()
|
|
return GPIO_SWITCH_FAIL
|
|
else:
|
|
g.close()
|
|
break
|
|
|
|
def closePin(pinno):
|
|
try: x = open('/sys/class/gpio/unexport', 'w')
|
|
except: return GPIO_PIN_UNX_NF
|
|
else:
|
|
try: x.write(pinno)
|
|
except: return GPIO_PIN_UNX_FAIL
|
|
finally: x.close()
|
|
|
|
try: preparePin(sys.argv[1])
|
|
except GPIO_SWITCH_FAIL: print(f'GPIO Pin direction couldn\'t be switched to out. {sys.argv[1]}')
|
|
except GPIO_DIR_CONT_FAIL: print(f'GPIO Pin control couldn\'t be opened. {sys.argv[1]}')
|
|
except GPIO_PIN_EXP_FAIL: print(f'GPIO Pin couldn\'t be exported. P: {sys.argv[1]}')
|
|
except GPIO_IFACE_MISSING: print(f'GPIO Export interface couldn\'t be opened. {sys.argv[1]}')
|
|
|
|
with open(f'/sys/class/gpio/gpio{sys.argv[1]}/value', 'w') as x:
|
|
if (len(sys.argv) == 3): x.write(sys.argv[2])
|
|
else: x.write('0')
|