#!/usr/bin/env python
import pigpio
import time
import datetime
import asyncio
import os

PTT_IS_ON = False
modulations = {
    "ssb":"./modulations/ssb.sh",
    "fmrds":"./modulations/fmrds.sh"    
}


# init GPIO
pi = pigpio.pi()
# button pin
pi.set_mode(10, pigpio.INPUT)

async def run_command(*args):
    process = await asyncio.create_subprocess_exec(*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    print("Started: %s, pid=%s" % (args, process.pid), flush=True)


async def button_press(gpio:int, level) -> bool:
    global PTT_IS_ON
    while True:
        if(pi.read(gpio)!=0):
            PTT_IS_ON = True
        if(pi.read(gpio)==0):
            PTT_IS_ON = False
        await asyncio.sleep(.5)

async def main(mod, freq:float):
    asyncio.create_task(button_press(10, pigpio.EITHER_EDGE))
    global PTT_IS_ON
    task_created = False 
    print("Ready")
    while True:
        if (PTT_IS_ON and not task_created):
                asyncio.create_task(run_command(modulations[mod], str(freq)))
                task_created = True
        elif (task_created and not PTT_IS_ON):
            await asyncio.sleep(1)
            asyncio.create_task(run_command("./kill.sh"))
            task_created = False
        await asyncio.sleep(.5)

if __name__ == "__main__":
    try:
        asyncio.run(main("fmrds", 430))
    except KeyboardInterrupt:
        print("\n")