#================================================================
#================================================================
# API-AIO(WDM)
# Counter sample
# Counter setting file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import caio
from CommonFunction import *
#----------------------------------------
# Declaration of global variables
#----------------------------------------
g_cnt_channel = ctypes.c_short()                                  # Counter channel
g_cnt_mode_comparison_number = ctypes.c_long()                    # Total number of comparison count data to be set
g_cnt_mode_comparison_data_type = ctypes.c_long * 8               # Create the array type (Comparison count data)
g_cnt_mode_comparison_data = g_cnt_mode_comparison_data_type()    # Comparison count data
g_cnt_mode_comparison_repeat = ctypes.c_short()                   # Repeat setting of comparison count data array
g_cnt_mode_preset_number = ctypes.c_long()                        # Total number of the preset data to be set
g_cnt_mode_preset_data_type = ctypes.c_long * 8                   # Create the array type (Counter preset data)
g_cnt_mode_preset_data = g_cnt_mode_preset_data_type()            # Counter preset data
g_cnt_mode_preset_repeat = ctypes.c_short()                       # Repeat setting of preset data array


#========================================
# Function name    CounterSetting
# Parameter        id    Id get by AioInit
# Details          Function that display and process the counter set menu
# Return value     None
#========================================
def CounterSetting(id):
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_long()                          # For return code
    cnt_mode = ctypes.c_short()                     # Operation mode
    cnt_mode_comparison = ctypes.c_short()          # Load the comparison count value
    cnt_mode_preset = ctypes.c_short()              # Load the preset count value
    cnt_mode_comparison_data_string = []            # Comparison count string list
    cnt_mode_preset_data_string = []                # Counter preset string list
    global g_cnt_channel                            # Counter channel
    global g_cnt_mode_comparison_number             # Total number of comparison count data to be set
    global g_cnt_mode_comparison_data               # Comparison count data
    global g_cnt_mode_comparison_repeat             # Repeat setting of comparison count data array
    global g_cnt_mode_preset_number                 # Total number of the preset data to be set
    global g_cnt_mode_preset_data                   # Counter preset data
    global g_cnt_mode_preset_repeat                 # Repeat setting of preset data array
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the compare match count, count value, status in the callback

    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the counter operation as comparison count match occurs
        #--------------------
        lret.value = caio.AioGetCntComparisonMode(id, g_cnt_channel, ctypes.byref(cnt_mode))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            print("Counter Settings Error")
            print(f"AioGetCntComparisonMode Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            return
        else:
            if (cnt_mode.value & caio.CNT_LOADCOMP) == caio.CNT_LOADCOMP:
                cnt_mode_comparison.value = 1
                cnt_mode_comparison_string = "1 (Valid)"
            else:
                cnt_mode_comparison.value = 0
                cnt_mode_comparison_string = "0 (Invalid)"
            if (cnt_mode.value & caio.CNT_LOADPRESET) == caio.CNT_LOADPRESET:
                cnt_mode_preset.value = 1
                cnt_mode_preset_string = "1 (Valid)"
            else:
                cnt_mode_preset.value = 0
                cnt_mode_preset_string = "0 (Invalid)"
        #--------------------
        # When the comparison count value load is valid
        #--------------------
        if cnt_mode_comparison.value == 1:
            cnt_mode_comparison_number_string = f"{g_cnt_mode_comparison_number.value:d}"
            cnt_mode_comparison_data_string.clear()
            for i in range(0, g_cnt_mode_comparison_number.value):
                cnt_mode_comparison_data_string.append(f"{g_cnt_mode_comparison_data[i]:d}")
            cnt_mode_comparison_repeat_string = f"{g_cnt_mode_comparison_repeat.value:d}"
        #--------------------
        # When the preset count value load is valid
        #--------------------
        if cnt_mode_preset.value == 1:
            cnt_mode_preset_number_string = f"{g_cnt_mode_preset_number.value:d}"
            cnt_mode_preset_data_string.clear()
            for i in range(0, g_cnt_mode_preset_number.value):
                cnt_mode_preset_data_string.append(f"{g_cnt_mode_preset_data[i]:d}")
            cnt_mode_preset_repeat_string = f"{g_cnt_mode_preset_repeat.value:d}"
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"Comparison Count Set           : {cnt_mode_comparison_string}")
        if cnt_mode_comparison.value == 1:
            print(f"  Number of Setting Data       : {cnt_mode_comparison_number_string}")
            for i in range(0, g_cnt_mode_comparison_number.value):
                print(f"  Comparison Count Data[{i}]     : {cnt_mode_comparison_data_string[i]}")
            print(f"  Repeat Setting               : {cnt_mode_comparison_repeat_string}")
        print(f"Comparison Match Preset Set    : {cnt_mode_preset_string}")
        if cnt_mode_preset.value == 1:
            print(f"  Number of Setting Data       : {cnt_mode_preset_number_string}")
            for i in range(0, g_cnt_mode_preset_number.value):
                print(f"  Preset Data[{i}]               : {cnt_mode_preset_data_string[i]}")
            print(f"  Repeat Setting               : {cnt_mode_preset_repeat_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu(Top > Counter Settings)")
        print("========================================")
        print("1 : Comparison Count Set")
        print("2 : Comparison Match Preset Set")
        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 compare match count, count value, 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
        #----------------------------------------
        #--------------------
        # Comparison Count Set
        #--------------------
        if buf == "1":
            print("\n----------------------------------------")
            print("Start Comparison Count Setting")
            print("----------------------------------------")
            #----------------------------------------
            # Input invalid/valid of comparison count setting
            #----------------------------------------
            print("----------------------------------------")
            print("Parameter(Invalid/valid of comparison count setting)")
            print("----------------------------------------")
            print("0 : Invalid")
            print("1 : Valid")
            while True:
                print("Please input the invalid/valid of comparison count setting : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the compare match count, count value, 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
                #----------------------------------------
                # Range judgment
                #----------------------------------------
                if int(buf) >= 0 and int(buf) <= 1:
                    break
            cnt_mode_comparison = ctypes.c_short(int(buf))
            #----------------------------------------
            # Invalid/valid comparison count setting
            #----------------------------------------
            if cnt_mode_comparison.value == 0:
                cnt_mode.value = cnt_mode.value & (~caio.CNT_LOADCOMP)
            elif cnt_mode_comparison.value == 1:
                cnt_mode.value = cnt_mode.value | caio.CNT_LOADCOMP
            lret.value = caio.AioSetCntComparisonMode(id, g_cnt_channel, cnt_mode)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                #----------------------------------------
                # If the compare match count, count value, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                print("\nComparison Count Set Error")
                print(f"AioSetCntComparisonMode Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # When the comparison count setting is valid
            #----------------------------------------
            if cnt_mode_comparison.value == 1:
                #----------------------------------------
                # If the compare match count, count value, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # Input the number of setting data
                #----------------------------------------
                print("")
                while True:
                    print("Please input the number of setting data (1-5) : ", end='', flush=True)
                    #----------------------------------------
                    # Unlock
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Lock
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # If the compare match count, count value, 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
                    #----------------------------------------
                    # Range judgment
                    #----------------------------------------
                    if int(buf) >= 1 and int(buf) <= 5:
                        break
                g_cnt_mode_comparison_number.value = int(buf)
                #----------------------------------------
                # If the compare match count, count value, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # Input the comparison count data
                #----------------------------------------
                print("")
                print("Please input the comparison count data")
                for i in range(0, g_cnt_mode_comparison_number.value):
                    while True:
                        print(f"Comparison Count Data[{i}] : ", end='', flush=True)
                        #----------------------------------------
                        # Unlock
                        #----------------------------------------
                        g_lock.release()
                        #----------------------------------------
                        # Waiting for input
                        #----------------------------------------
                        buf = input()
                        #----------------------------------------
                        # Lock
                        #----------------------------------------
                        g_lock.acquire()
                        #----------------------------------------
                        # If the compare match count, count value, 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
                    g_cnt_mode_comparison_data[i] = int(buf)
                #----------------------------------------
                # Input the repeat setting
                #----------------------------------------
                print("\n----------------------------------------")
                print("Parameter(Repeat setting)")
                print("----------------------------------------")
                print("0 : Not repeat")
                print("1 : Repeat")
                while True:
                    print(f"Please input the repeat setting : ", end='', flush=True)
                    #----------------------------------------
                    # Unlock
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Lock
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # If the compare match count, count value, 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
                    #----------------------------------------
                    # Range judgment
                    #----------------------------------------
                    if int(buf) >= 0 and int(buf) <= 1:
                        break
                g_cnt_mode_comparison_repeat.value = int(buf)
                #----------------------------------------
                # Set the next comparison count value loaded after comparison count match
                #----------------------------------------
                lret.value = caio.AioSetCntComparisonReg(id, g_cnt_channel, g_cnt_mode_comparison_number, g_cnt_mode_comparison_data, g_cnt_mode_comparison_repeat)
                if lret.value != 0:
                    caio.AioGetErrorString(lret, error_buf)
                    #----------------------------------------
                    # If the compare match count, count value, status are displayed in the callback, output a new line
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    print("\nComparison Count Set Error")
                    print(f"AioSetCntComparisonReg Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
            #----------------------------------------
            # If the compare match count, count value, status are displayed in the callback, output a new line
            #----------------------------------------
            if g_info_flag.value == 1:
                print("")
                g_info_flag.value = 0
            print("\nComparison Count Set : Successful completion\n")
        #--------------------
        # Comparison Match Preset Set
        #--------------------
        elif buf == "2":
            print("\n----------------------------------------")
            print("Start Comparison Match Preset Setting")
            print("----------------------------------------")
            #----------------------------------------
            # Input invalid/valid of comparison match preset setting
            #----------------------------------------
            print("----------------------------------------")
            print("Parameter(Invalid/valid of comparison match preset setting)")
            print("----------------------------------------")
            print("0 : Invalid")
            print("1 : Valid")
            while True:
                print("Please input the invalid/valid of comparison match preset setting : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the compare match count, count value, 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
                #----------------------------------------
                # Range judgment
                #----------------------------------------
                if int(buf) >= 0 and int(buf) <= 1:
                    break
            cnt_mode_preset = ctypes.c_short(int(buf))
            #----------------------------------------
            # Invalid/valid comparison match preset setting
            #----------------------------------------
            if cnt_mode_preset.value == 0:
                cnt_mode.value = cnt_mode.value & (~caio.CNT_LOADPRESET)
            elif cnt_mode_preset.value == 1:
                cnt_mode.value = cnt_mode.value | caio.CNT_LOADPRESET
            lret.value = caio.AioSetCntComparisonMode(id, g_cnt_channel, cnt_mode)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                #----------------------------------------
                # If the compare match count, count value, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                print("\nComparison Match Preset Set Error")
                print(f"AioSetCntComparisonMode Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # When the comparison match preset setting is valid
            #----------------------------------------
            if cnt_mode_preset.value == 1:
                #----------------------------------------
                # If the compare match count, count value, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # Input the number of setting data
                #----------------------------------------
                print("")
                while True:
                    print("Please input the number of setting data (1-5) : ", end='', flush=True)
                    #----------------------------------------
                    # Unlock
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Lock
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # If the compare match count, count value, 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
                    #----------------------------------------
                    # Range judgment
                    #----------------------------------------
                    if int(buf) >= 1 and int(buf) <= 5:
                        break
                g_cnt_mode_preset_number.value = int(buf)
                #----------------------------------------
                # If the compare match count, count value, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # Input the preset data
                #----------------------------------------
                print("")
                print("Please input the preset data")
                for i in range(0, g_cnt_mode_preset_number.value):
                    while True:
                        print(f"Preset Data[{i}] : ", end='', flush=True)
                        #----------------------------------------
                        # Unlock
                        #----------------------------------------
                        g_lock.release()
                        #----------------------------------------
                        # Waiting for input
                        #----------------------------------------
                        buf = input()
                        #----------------------------------------
                        # Lock
                        #----------------------------------------
                        g_lock.acquire()
                        #----------------------------------------
                        # If the compare match count, count value, 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
                    g_cnt_mode_preset_data[i] = int(buf)
                #----------------------------------------
                # Input the repeat setting
                #----------------------------------------
                print("\n----------------------------------------")
                print("Parameter(Repeat setting)")
                print("----------------------------------------")
                print("0 : Not repeat")
                print("1 : Repeat")
                while True:
                    print(f"Please input the repeat setting : ", end='', flush=True)
                    #----------------------------------------
                    # Unlock
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Lock
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # If the compare match count, count value, 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
                    #----------------------------------------
                    # Range judgment
                    #----------------------------------------
                    if int(buf) >= 0 and int(buf) <= 1:
                        break
                g_cnt_mode_preset_repeat.value = int(buf)
                #----------------------------------------
                # Set the preset value loaded after the comparison count match
                #----------------------------------------
                lret.value = caio.AioSetCntPresetReg(id, g_cnt_channel, g_cnt_mode_preset_number, g_cnt_mode_preset_data, g_cnt_mode_preset_repeat)
                if lret.value != 0:
                    caio.AioGetErrorString(lret, error_buf)
                    #----------------------------------------
                    # If the compare match count, count value, status are displayed in the callback, output a new line
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    print("\nComparison Match Preset Set Error")
                    print(f"AioSetCntPresetReg Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # If the compare match count, count value, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
            print("\nComparison Match Preset Set : Successful completion\n")
        #--------------------
        # Back
        #--------------------
        elif buf == "b":
            print("")
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue