#================================================================
#================================================================
# API-AIO(WDM)
# Infinite generating using device buffer sample
# Condition setting file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import caio
from CommonFunction import *


#========================================
# Function name    GeneratingSetting
# Parameter        id    Id get by AioInit
# Details          Function that displays and processes the condition set menu
# Return value     None
#========================================
def GeneratingSetting(id):
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_long()                          # For return code
    ao_start_trigger = ctypes.c_short()             # Conversion start condition
    ao_clock_type = ctypes.c_short()                # Clock type
    ao_generating_clock = ctypes.c_float()          # Generating clock
    ao_clock_edge = ctypes.c_short()                # Timing of the external clock input
    ao_stop_trigger = ctypes.c_short()              # Conversion stop condition
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the total generating count, setting generating count, status in the callback

    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the conversion start condition
        #--------------------
        lret.value = caio.AioGetAoStartTrigger(id, ctypes.byref(ao_start_trigger))
        if lret.value != 0:
            ao_start_trigger_string = "-"
        else:
            ao_start_trigger_string = GetStartTriggerString(ao_start_trigger)
        #--------------------
        # Get the generating clock condition
        #--------------------
        lret.value = caio.AioGetAoClockType(id, ctypes.byref(ao_clock_type))
        if lret.value != 0:
            ao_clock_type_string = "-"
        else:
            ao_clock_type_string = GetClockTypeString(ao_clock_type)
        #--------------------
        # For generating clock condition is Internal clock
        #--------------------
        if ao_clock_type.value == 0:
            #--------------------
            # Get the generating clock period
            #--------------------
            lret.value = caio.AioGetAoSamplingClock(id, ctypes.byref(ao_generating_clock))
            if lret.value != 0:
                ao_generating_clock_string = "-"
            else:
                ao_generating_clock_string = f"{ao_generating_clock.value}[usec]"
        #--------------------
        # For generating clock condition is External clock
        #--------------------
        elif ao_clock_type.value == 1:
            #--------------------
            # Get the timing of external clock input
            #--------------------
            lret.value = caio.AioGetAoClockEdge(id, ctypes.byref(ao_clock_edge))
            if lret.value != 0:
                ao_clock_edge_string = "-"
            else:
                ao_clock_edge_string = GetClockEdgeString(ao_clock_edge)
        #--------------------
        # Get the conversion stop condition
        #--------------------
        lret.value = caio.AioGetAoStopTrigger(id, ctypes.byref(ao_stop_trigger))
        if lret.value != 0:
            ao_stop_trigger_string = "-"
        else:
            ao_stop_trigger_string = GetStopTriggerString(ao_stop_trigger)
        #--------------------
        # For stop condition is 'Stop conversion by the specified times', set 'External trigger rising edge' as the stop condition and retrieve it
        #--------------------
        if ao_stop_trigger.value == 0:
            lret.value = caio.AioSetAoStopTrigger(id, 1)
            if lret.value == 0:
                #--------------------
                # Get the conversion stop condition
                #--------------------
                lret.value = caio.AioGetAoStopTrigger(id, ctypes.byref(ao_stop_trigger))
                if lret.value != 0:
                    ao_stop_trigger_string = "-"
                else:
                    ao_stop_trigger_string = GetStopTriggerString(ao_stop_trigger)
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"Start Condition                : {ao_start_trigger_string}")
        print(f"Generating Clock Condition     : {ao_clock_type_string}")
        if ao_clock_type.value == 0:
            print(f"Generating Clock Period        : {ao_generating_clock_string}")
        elif ao_clock_type.value == 1:
            print(f"Timing of External Clock Input : {ao_clock_edge_string}")
        print(f"Stop Condition                 : {ao_stop_trigger_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu(Top > Condition Set)")
        print("========================================")
        print("1 : Start Condition")
        print("2 : Generating Clock Condition")
        print("3 : Stop Condition")
        print("b : Back")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Unlock
        #----------------------------------------
        g_lock.release()
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Lock
        #----------------------------------------
        g_lock.acquire()
        #----------------------------------------
        # If the total generating count, setting generating count, status are displayed in the callback, output a new line
        #----------------------------------------
        if g_info_flag.value == 1:
            print("")
            g_info_flag.value = 0
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # Start Condition
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Input the start condition
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Start condition)")
            print("----------------------------------------")
            print("0 : Software")
            print("1 : External trigger rising edge")
            print("2 : External trigger falling edge")
            while True:
                print("Please input the start condition : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the total generating count, setting generating count, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_start_trigger = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the start condition
            #----------------------------------------
            lret.value = caio.AioSetAoStartTrigger(id, ao_start_trigger)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nStart Condition Error")
                print(f"AioSetAoStartTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("\nStart Condition : Successful completion\n")
        #--------------------
        # Generating Clock Condition
        #--------------------
        elif buf == "2":
            print("\n----------------------------------------")
            print("Start the generating clock condition setting")
            print("----------------------------------------")
            #----------------------------------------
            # Input the generating clock type
            #----------------------------------------
            print("----------------------------------------")
            print("Parameter(Generating clock type)")
            print("----------------------------------------")
            print("0 : Internal clock")
            print("1 : External clock")
            while True:
                print("Please input the generating clock type : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the total generating count, setting generating count, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_clock_type = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the generating clock type
            #----------------------------------------
            lret.value = caio.AioSetAoClockType(id, ao_clock_type)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating Clock Condition Error")
                print(f"AioSetAoClockType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # For generating clock type is Internal clock
            #----------------------------------------
            if ao_clock_type.value == 0:
                #----------------------------------------
                # Input the generating clock period
                #----------------------------------------
                print("")
                while True:
                    print("Please input the generating clock period[usec] : ", end='', flush=True)
                    #----------------------------------------
                    # Unlock
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Lock
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # If the total generating count, setting generating count, status are displayed in the callback, output a new line
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    #----------------------------------------
                    # Check if the input value is a number
                    #----------------------------------------
                    if False == isnum(buf, 0):
                        continue
                    break
                ao_generating_clock = ctypes.c_float(float(buf))
                #----------------------------------------
                # Set the generating clock period
                #----------------------------------------
                lret.value = caio.AioSetAoSamplingClock(id, ao_generating_clock)
                if lret.value != 0:
                    caio.AioGetErrorString(lret, error_buf)
                    print("\nGenerating Clock Condition Error")
                    print(f"AioSetAoSamplingClock Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
            #----------------------------------------
            # For generating clock type is External clock
            #----------------------------------------
            elif ao_clock_type.value == 1:
                #----------------------------------------
                # Input the timing of external clock input
                #----------------------------------------
                print("\n----------------------------------------")
                print("Parameter(Timing of external clock input)")
                print("----------------------------------------")
                print("0 : External input falling edge")
                print("1 : External input rising edge")
                while True:
                    print("Please input the timing of external clock input : ", end='', flush=True)
                    #----------------------------------------
                    # Unlock
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Lock
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # If the total generating count, setting generating count, status are displayed in the callback, output a new line
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    #----------------------------------------
                    # Check if the input value is a number
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    break
                ao_clock_edge = ctypes.c_short(int(buf))
                #----------------------------------------
                # Set the timing of external clock input
                #----------------------------------------
                lret.value = caio.AioSetAoClockEdge(id, ao_clock_edge)
                #--------------------
                # Exit the process if not completed successfully
                #--------------------
                if lret.value != 0 and lret.value != 20001:
                    caio.AioGetErrorString(lret, error_buf)
                    print("\nGenerating Clock Condition Error")
                    print(f"AioSetAoClockEdge Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
            print("\nGenerating Clock Condition : Successful completion\n")
        #--------------------
        # Stop Condition
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Input the stop condition
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Stop condition)")
            print("----------------------------------------")
            print("1 : External trigger rising edge")
            print("2 : External trigger falling edge")
            while True:
                print("Please input the stop condition : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the total generating count, setting generating count, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_stop_trigger = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the stop condition
            #----------------------------------------
            lret.value = caio.AioSetAoStopTrigger(id, ao_stop_trigger)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nStop Condition Error")
                print(f"AioSetAoStopTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("\nStop Condition : Successful completion\n")
        #--------------------
        # Back
        #--------------------
        elif buf == "b":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue