#================================================================
#================================================================
# API-AIO(WDM)
# Counter sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import caio
from CommonFunction import *
from CounterSetting import *
#----------------------------------------
# Declaration of global variables
#----------------------------------------
g_cnt_event_count = ctypes.c_long()    # Comparison count match event occurrence count


#========================================
# Function name    CallBackProc
# Parameter        id           Id get by AioInit
# Parameter        cnt_event    The event that occurred
# Parameter        wParam       Parameter passed from driver
# Parameter        lParam       Parameter unique to each event
# Parameter        Param        Parameter specified in the AioSetCntCallBackProc function
# Details          Function registered with the AioSetCntCallBackProc function
#                  This function is called when an event occurs
# Return value     None
#========================================
def CallBackProc(id, cnt_event, wParam, lParam, Param):
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_long()                          # For return code
    cnt_channel = ctypes.c_short()                  # Counter channel
    cnt_count = ctypes.c_long()                     # Current count value
    cnt_status = ctypes.c_long()                    # Status
    global g_cnt_channel                            # Counter channel
    global g_cnt_event_count                        # Comparison count match event occurrence count

    #----------------------------------------
    # Event that comparison count match
    #----------------------------------------
    if cnt_event == caio.AIOM_CNTE_DATA_NUM:
        #----------------------------------------
        # Get counter channel
        #----------------------------------------
        cnt_channel = ctypes.c_short(wParam)
        if cnt_channel.value == g_cnt_channel.value:
            #----------------------------------------
            # Get the count value
            #----------------------------------------
            lret.value = caio.AioGetCntCount(id, cnt_channel, ctypes.byref(cnt_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\nComparison Count Match Event Process : AioGetCntCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # Get the status
            #----------------------------------------
            lret.value = caio.AioGetCntStatus(id, cnt_channel, ctypes.byref(cnt_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\nComparison Count Match Event Process : AioGetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            cnt_status_string = GetStatusString(cnt_status)
            #----------------------------------------
            # Increment the number of the comparison count match event occurrence count
            #----------------------------------------
            g_cnt_event_count.value += 1
            #----------------------------------------
            # Reset status
            #----------------------------------------
            lret.value = caio.AioResetCntStatus(id, cnt_channel, caio.CNTS_DATA_NUM)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\nComparison Count Match Event Process : AioResetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # Display the compare match count, count value, status
            #----------------------------------------
            text_buf = f"\nCompare Match Count = {g_cnt_event_count.value:<8d} Count Value = {cnt_count.value:<8d} Status = 0x{cnt_status.value:08x}({cnt_status_string:})"
            PrintOnOneLine(text_buf)
    #----------------------------------------
    # Event that counter operation error
    #----------------------------------------
    elif cnt_event == caio.AIOM_CNTE_ERR:
        #----------------------------------------
        # Get counter channel
        #----------------------------------------
        cnt_channel = ctypes.c_short(wParam)
        if cnt_channel.value == g_cnt_channel.value:
            #----------------------------------------
            # Get the count value
            #----------------------------------------
            lret.value = caio.AioGetCntCount(id, cnt_channel, ctypes.byref(cnt_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\nCounter Operation Error Occurrence Process : AioGetCntCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # Get the status
            #----------------------------------------
            lret.value = caio.AioGetCntStatus(id, cnt_channel, ctypes.byref(cnt_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\nCounter Operation Error Occurrence Process : AioGetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            cnt_status_string = GetStatusString(cnt_status)
            #----------------------------------------
            # Display the compare match count, count value, status
            #----------------------------------------
            text_buf = f"\nCompare Match Count = {g_cnt_event_count.value:<8d} Count Value = {cnt_count.value:<8d} Status = 0x{cnt_status.value:08x}({cnt_status_string:})"
            PrintOnOneLine(text_buf)
    return

pcnt_callback = caio.PAIO_CNT_CALLBACK(CallBackProc)


#========================================
# Function name    main
# Parameter        None
# Details          Function that performs main processing
# Return value     None
#========================================
def main():
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_long()                          # For return code
    id = ctypes.c_short()                           # ID for device access
    cnt_preset_data = ctypes.c_long()               # Counter preset value
    cnt_count = ctypes.c_long()                     # Current count value
    cnt_status = ctypes.c_long()                    # Status
    cnt_max_channels = ctypes.c_short()             # Maximum number of counter channels
    initialized = 0                                 # Whether the board has been initialized
    global g_cnt_channel                            # Counter channel
    global g_cnt_event_count                        # Comparison count match event occurrence count
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the compare match count, count value, status in the callback

    #----------------------------------------
    # Initialize the variable
    #----------------------------------------
    g_info_flag.value = 0
    #----------------------------------------
    # Lock
    #----------------------------------------
    g_lock.acquire()
    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the counter channel No.
        #--------------------
        if initialized == 0:
            cnt_channel_string = "-"
        else:
            cnt_channel_string = f"{g_cnt_channel.value:d}"
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"Counter Channel No. : {cnt_channel_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu(Top)")
        print("========================================")
        print(" 1 : AioInit")
        print(" 2 : AioResetDevice")
        print(" 3 : Counter Channel No. Set")
        print(" 4 : Counter Settings")
        print(" 5 : AioPresetCnt")
        print(" 6 : Count Start")
        print(" 7 : AioGetCntCount")
        print(" 8 : AioGetCntStatus")
        print(" 9 : Count Stop")
        print("10 : AioExit")
        print(" q : Quit")
        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
        #----------------------------------------
        #--------------------
        # AioInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Input the device name
            #----------------------------------------
            print("\nPlease input the device name : ", 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
            #----------------------------------------
            # Initialization
            #----------------------------------------
            lret.value = caio.AioInit(buf.encode(), ctypes.byref(id))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioInit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            #----------------------------------------
            # Set the initialization flag
            #----------------------------------------
            if lret.value == 0:
                initialized = 1
            else:
                initialized = 0
        #--------------------
        # AioResetDevice
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # Reset the device
            #----------------------------------------
            lret.value = caio.AioResetDevice(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioResetDevice Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Counter Channel No. Set
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Get the maximum number of counter channels
            #----------------------------------------
            lret.value = caio.AioGetCntMaxChannels(id, ctypes.byref(cnt_max_channels))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCounter Channel No. Set Error")
                print(f"AioGetCntMaxChannels Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Input the counter channel No.
            #----------------------------------------
            print("")
            while True:
                print(f"Please input the counter channel No.(0-{cnt_max_channels.value - 1}) : ", 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
                #----------------------------------------
                # Counter Channel No. judgment
                #----------------------------------------
                if int(buf) >= 0 and int(buf) < cnt_max_channels.value:
                    break
            g_cnt_channel.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
            #----------------------------------------
            # Set the counter channel No.
            #----------------------------------------
            print("\nCounter Channel No. Set : Successful completion")
            print(f"Counter Channel No. = {g_cnt_channel.value}\n")
        #--------------------
        # Counter Settings
        #--------------------
        elif buf == "4":
            print("")
            #----------------------------------------
            # Display the counter settings menu
            #----------------------------------------
            CounterSetting(id)
        #--------------------
        # AioPresetCnt
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Input the counter preset value
            #----------------------------------------
            print("")
            while True:
                print("Please input the counter preset value : ", 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
            cnt_preset_data = ctypes.c_long(int(buf))
            #----------------------------------------
            # Set the preset value
            #----------------------------------------
            lret.value = caio.AioPresetCnt(id, g_cnt_channel, cnt_preset_data)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioPresetCnt Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Preset Value = {cnt_preset_data.value}")
            print("")
        #--------------------
        # Count Start
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # Set the event factor to 'Comparison count match event', 'Counter operation error'
            #----------------------------------------
            lret.value = caio.AioSetCntCallBackProc(id, g_cnt_channel, pcnt_callback, caio.CNTE_DATA_NUM | caio.CNTE_ERR, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCount Start Error")
                print(f"AioSetCntCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Reset counter status
            #----------------------------------------
            lret.value = caio.AioResetCntStatus(id, g_cnt_channel, caio.CNTE_DATA_NUM | caio.CNTS_ORERR)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCount Start Error")
                print(f"AioResetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Initialize comparison match count
            #----------------------------------------
            g_cnt_event_count.value = 0
            #----------------------------------------
            # Start the counter action
            #----------------------------------------
            lret.value = caio.AioStartCnt(id, g_cnt_channel)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCount Start Error")
                print(f"AioStartCnt Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that count start is completed
            #----------------------------------------
            print("\nCount Start : Successful completion\n")
        #--------------------
        # AioGetCntCount
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Get the current count value
            #----------------------------------------
            lret.value = caio.AioGetCntCount(id, g_cnt_channel, ctypes.byref(cnt_count))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetCntCount Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Count Value = {cnt_count.value}")
            print("")
        #--------------------
        # AioGetCntStatus
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Get the counter status
            #----------------------------------------
            lret.value = caio.AioGetCntStatus(id, g_cnt_channel, ctypes.byref(cnt_status))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                #----------------------------------------
                # Create the status string
                #----------------------------------------
                cnt_status_string = GetStatusString(cnt_status)
                print(f"Status = 0x{cnt_status.value:08x}({cnt_status_string})")
            print("")
        #--------------------
        # Count Stop
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # Stop the counter action
            #----------------------------------------
            lret.value = caio.AioStopCnt(id, g_cnt_channel)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCount Stop Error")
                print(f"AioStopCnt Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that count stop is completed
            #----------------------------------------
            print("\nCount Stop : Successful completion\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # Exit process
            #----------------------------------------
            lret.value = caio.AioExit(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            #----------------------------------------
            # Set the initialization flag
            #----------------------------------------
            if lret.value == 0:
                initialized = 0
        #--------------------
        # Quit
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    #----------------------------------------
    # Exit process
    #----------------------------------------
    caio.AioExit(id)
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_lock.release()
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


#----------------------------------------
# Call main function
#----------------------------------------
if __name__ == "__main__":
    main()