import itertools as itt
import sys
import time
import datetime
import serial
import win32event
import win32file
import win32api
import pywintypes
import subprocess
import numpy as np

res = 0

# autoconsole.py <sync_file> <sync_serial_port> <adc_file> <adc_trig_direction = {0; 1}> <rf_file> <rf_freq> <rf_rate> <rf_ampl = {0; 1}> <rf_gain>

try:
    res = subprocess.run(["Sync.exe", sys.argv[1], "--debug", "-p", sys.argv[2]], stdout=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
except subprocess.CalledProcessError as e:
    if res != 0:
        print(f"Error at Sync.exe! Return: {e.returncode}")
        sys.exit(1)

try:
    ser = serial.Serial("COM" + str(sys.argv[2]), 9600)
    ser.write(bytes('e', 'utf-8'))
except serial.SerialException as e:
    print(f"Error at serial port: {e}")
    sys.exit(1)

sem = win32event.CreateSemaphore(None, 0, 1, "wait-semaphore-5d95950d-a278-4733-a041-ee9fb05ad4e4")
if sem == None:
    print(f"Error at semaphore: cannot create!")
    win32event.CloseHandle(sem)
    sys.exit(1)

if sys.argv[4]:
    pargs = ["pico_test_00_second_copy.exe", sys.argv[3], "--below"] # Не ставьте --debug, будут очень мусорные логи на сотни мегабайт!
else:
    pargs = ["pico_test_00_second_copy.exe", sys.argv[3]]

# Using Popen for asynchronous running
try:
    picoproc = subprocess.Popen(pargs, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
    print(f"Pico process PID: {picoproc.pid}")
except subprocess.SubprocessError as e:
    print(f"Error at Pico! Return: {e.returncode}")
    picoproc.kill()
    sys.exit(1)

ret = win32event.WaitForSingleObject(sem, 20000)
if ret == win32event.WAIT_TIMEOUT:
    print("Pico timeout!")
    win32event.ReleaseSemaphore(sem, 1)
    win32file.CloseHandle(sem)
    sys.exit(1)

try:
    res = subprocess.run(["hackrftrans00.exe", "-t", sys.argv[5], "-f", sys.argv[6], "-s", sys.argv[7], "-a", sys.argv[8], "-x", sys.argv[9]])
except subprocess.CalledProcessError as e:
    if res != 0:
        print(f"Error at HackRF! Return: {e.returncode}")
        sys.exit(1)