#!/usr/bin/env python
import serial
import subprocess

ser = serial.Serial(port='/dev/ttyACM1')

ser.flushInput()
print('Begin loop')
while True:
    line = ser.readline()
    try:
        command =  (line.decode()).split()
        print('command received: {}'.format(command[0]))
    except:
        print('no valid command received')
        command = ""

    try:
        if command[0] == "mute":
            # First subprocess for toggle mote the microphone
            subprocess.run(
                ['pactl', 'set-source-mute', '@DEFAULT_SOURCE@', 'toggle'],
            )

            # Second one for check the states of microphone
            result = subprocess.run(
                ['pactl', 'get-source-mute', '@DEFAULT_SOURCE@'],
                capture_output=True
            )
            message = "mute {}\r".format(result.stdout.split()[1].decode())
            ser.write(message.encode())
            print('command sent: {}'.format(message))
    except Error as e:
        print('Error in command: {}'.format(e))       
