#!/usr/bin/python3

import time
import os

gpio_list=[21,30,7,27+64,11+32,13+32,  22,31,1,5,31+64,12+32,14+32,  24,26,28,0,6,4+64,2+64,0+64,  23,25,27,29,8,28+64,3+64,1+64   ]


def get_gpio_path(kernel_id):
	iopath="/sys/class/gpio/pio"
	if kernel_id>=0 and kernel_id<=31:
		iopath="%sA%d" % (iopath,kernel_id-0)
	if kernel_id>=32 and kernel_id<=63:
		iopath="%sB%d" % (iopath,kernel_id-32)
	if kernel_id>=64 and kernel_id<=95:
		iopath="%sC%d" % (iopath,kernel_id-64)
	return iopath	

def export_gpio(kernel_id):
	iopath=get_gpio_path(kernel_id)
	if not os.path.exists(iopath): 
		f = open('/sys/class/gpio/export','w')
		f.write(str(kernel_id))
		f.close()

def unexport_gpio(kernel_id):
	iopath=get_gpio_path(kernel_id)
	if os.path.exists(iopath): 
		f = open('/sys/class/gpio/unexport','w')
		f.write(str(kernel_id))
		f.close()

def direction_gpio(kernel_id,mode):
	iopath=get_gpio_path(kernel_id)
	if os.path.exists(iopath): 
		f = open(iopath + '/direction','w')
		f.write(mode)
		f.close()

def set_gpio(kernel_id):
	iopath=get_gpio_path(kernel_id)
	if os.path.exists(iopath): 
		f = open(iopath + '/value','w')
		f.write(str(1))
		f.close()

def clear_gpio(kernel_id):
	iopath=get_gpio_path(kernel_id)
	if os.path.exists(iopath): 
		f = open(iopath + '/value','w')
		f.write(str(0))
		f.close()

def get_gpio(kernel_id):
	if kernel_id!=-1:
		iopath=get_gpio_path(kernel_id)
		if os.path.exists(iopath): 
			f = open(iopath + '/value','r')
			a=f.read()
			f.close()
			return int(a)

for gpio_id in gpio_list:
	export_gpio(gpio_id)
	direction_gpio(gpio_id,"out")

export_gpio(17+64)
direction_gpio(17+64,"in")

usb_num=0

if os.path.exists('/dev/sda'):
    usb_num+=1

if os.path.exists('/dev/sdb'):
    usb_num+=1

if os.path.exists('/dev/sdc'):
    usb_num+=1

if usb_num!=3:
	print("ERRORE: Una USB non funziona")
	set_gpio(23)
	quit();


while True:
	for gpio_id in gpio_list:
		set_gpio(gpio_id)
		time.sleep(0.1)
		clear_gpio(gpio_id)
		if (get_gpio(17+64)==0):
			quit()

