import serial
import json

HIGH = 1
LOW = 0
left = [LOW,LOW]
right = [LOW,LOW]

def isHigh(signal):
    return signal > 0.6

def isLow(signal):
    return signal < 0.4


def scale(val):
    if(val < 100):
        val = 100
    if(val > 900):
        val = 900

    val = val - 100
    return round(val / 800.0, 1)


def loop():
    left = 0
    right = 0
    i = 0
    with  serial.Serial('/dev/ttyUSB0') as ser:  # open serial port
        while True:
            try:
                i = (i+1)%100
                if(i == 0):
                    client.loop()
                changed = False
                line = ser.readline()   # read a '\n' terminated line
                eachPedal = line.decode('ascii').strip().split(',')
                parts = list(map(scale, map(int, eachPedal)))
                if(left != parts[0]):
                    print(left,parts[0])
                    left = parts[0]
                    changed = True
                if(right != parts[1]):
                    right = parts[1]
                    changed = True

                if(changed):
                    on_change({ 'left': left, 'right': right });
            except:
              print("got an error")


def processChanges(changeLeft, changeRight):
    if changeRight and right[0] == LOW and right[1] == HIGH:
        print("liga microfone")
        content = subprocess.Popen(('amixer', '-D', 'pulse', 'set', 'Capture', 'cap'), stdout=subprocess.PIPE)

    if left[1] == LOW and changeRight and right[0] == HIGH and right[1] == LOW:
        print("desliga microfone")
        content = subprocess.Popen(('amixer', '-D', 'pulse', 'set', 'Capture', 'nocap'), stdout=subprocess.PIPE)


def on_change(content):
    global left
    global right
    changeLeft = False
    changeRight = False

    if isHigh(content["left"]):
        left.append(HIGH)
        left = left[1:]
        changeLeft = True
    elif isLow(content["left"]):
        left.append(LOW)
        left = left[1:]
        changeLeft = True

    if isHigh(content["right"]):
        right.append(HIGH)
        right = right[1:]
        changeRight = True
    elif isLow(content["right"]):
        right.append(LOW)
        right = right[1:]
        changeRight = True

    processChanges(changeLeft, changeRight)

loop()