import sys, pygame, os, serial, random,time,glob


#setup resources
pygame.init()
#hardcode serial port
#ser = serial.Serial('/dev/ttyUSB1',57600,timeout=1)
#OR, just open first USB serial port
ports = glob.glob('/dev/ttyU[A-Za-z]*')
ser=serial.Serial(ports[0],57600,timeout=1)

print(ports)

#globals
iNumSensors = 4
iMinTrigger=499
iMaxTrigger=512
iMinSecBetweenSamples=5
lasttime=time.time()
filelist = []

#play a sample associated with a given sensor
def playsample( iSensor ):
   if iSensor < iNumSensors and iSensor >= 0 and len(filelist[iSensor])>0:
       strSampleFileName=random.choice(filelist[iSensor])
       print(strSampleFileName)
       pygame.mixer.music.load(strSampleFileName)
       pygame.mixer.music.play(0)
   return;

#build list of available samples
from os import listdir
from os.path import isfile, join

for x in range(0, iNumSensors):
    foldername = 'sensor%d' % x
    filelist.append([])
    print(foldername)
    for f in listdir('./'+foldername+'/'):
        if isfile(join('./'+foldername+'/', f)) and (f.lower().find('.mp3')>0 or f.lower().find('.wav')>0):
            print (f)
            filelist[x].append('./'+foldername+'/'+f)

#read input from hall effect sensors then call playsample when sensor triggered
while 1:
    strRawData = ser.readline().decode("utf-8") 
    print(strRawData)
    if strRawData.startswith('start,'):
        strRawData = strRawData.replace('start,','')
        strData=strRawData.split(',')
        for sensor in range(0, min(iNumSensors,len(strData))):
            sensorValue = int(strData[sensor])
            print("sensor %d sensorValue %d" % (sensor, sensorValue))
            if sensorValue < iMinTrigger or sensorValue > iMaxTrigger:
                print("%d sensor triggered" % sensor)
                if (time.time()-lasttime)<iMinSecBetweenSamples:
                   print("not enough time elapsed")
                else:
                    lasttime=time.time()
                    playsample(sensor)





