#================================================================
#================================================================
# API-AIO(WDM)
# Timer sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import caio
from CommonFunction import *
#----------------------------------------
# Declaration of global variables
#----------------------------------------
global g_event_count    # Interval elapsed event occurrence count


#========================================
# Function name    CallBackProc
# Parameter        id          Id get by AioInit
# Parameter        tm_event    The event that occurred
# Parameter        wParam      Parameter passed from driver
# Parameter        lParam      Parameter unique to each event
# Parameter        Param       Parameter specified in the AioSetTmCallBackProc function
# Details          Function registered with the AioSetTmCallBackProc function
#                  This function is called when an event occurs
# Return value     None
#========================================
def CallBackProc(id, tm_event, wParam, lParam, Param):
    global g_event_count    # Interval elapsed event occurrence count

    #----------------------------------------
    # Event that interval elapses
    #----------------------------------------
    if tm_event == caio.AIOM_TME_INT:
        g_event_count += 1
        #----------------------------------------
        # Display the notification count
        #----------------------------------------
        text_buf = f"\nNotification Count = {g_event_count}"
        PrintOnOneLine(text_buf)
    return


ptm_callback = caio.PAIO_TM_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
    interval = ctypes.c_float()                     # Interval
    lap = ctypes.c_long()                           # Elapsed time
    global g_event_count                            # Interval elapsed event occurrence count
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the notification count in the callback
    
    #----------------------------------------
    # Initialize the variable
    #----------------------------------------
    g_info_flag.value = 0
    #----------------------------------------
    # Lock
    #----------------------------------------
    g_lock.acquire()
    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print("1 : AioInit")
        print("2 : AioResetDevice")
        print("3 : Interval Timer Operation Start")
        print("4 : Interval Timer Operation Stop")
        print("5 : Stop Watch Timer Operation Start")
        print("6 : AioLapTmCount")
        print("7 : AioResetTmCount")
        print("8 : Stop Watch Timer Operation Stop")
        print("9 : 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 notification count is 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 notification count is 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")
        #--------------------
        # 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")
        #--------------------
        # Interval Timer Operation Start
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Input the interval
            #----------------------------------------
            print("")
            while True:
                print("Please input the interval[usec] : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the notification count is 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
            interval = ctypes.c_float(float(buf))
            #----------------------------------------
            # Set the event
            #----------------------------------------
            lret.value = caio.AioSetTmCallBackProc(id, 0, ptm_callback, caio.TME_INT, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nInterval Timer Operation Start Error");
                print(f"AioSetTmCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Initialize the notification count
            #----------------------------------------
            g_event_count = 0
            #----------------------------------------
            # Start operation
            #----------------------------------------
            lret.value = caio.AioStartTmTimer(id, 0, interval)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nInterval Timer Operation Start Error")
                print(f"AioStartTmTimer Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("\nInterval Timer Operation Start : Successful completion")
            print(f"Interval = {interval.value:f}[usec]\n")
        #--------------------
        # Interval Timer Operation Stop
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # Stop operation
            #----------------------------------------
            lret.value = caio.AioStopTmTimer(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nInterval Timer Operation Stop Error")
                print(f"AioStopTmTimer Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("\nInterval Timer Operation Stop : Successful completion\n")
        #--------------------
        # Stop Watch Timer Operation Start
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Start operation
            #----------------------------------------
            lret.value = caio.AioStartTmCount(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nStop Watch Timer Operation Start Error")
                print(f"AioStartTmCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("\nStop Watch Timer Operation Start : Successful completion\n")
        #--------------------
        # AioLapTmCount
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # Get the elapsed time
            #----------------------------------------
            lret.value = caio.AioLapTmCount(id, 0, ctypes.byref(lap))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioLapTmCount Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Elapsed Time = {lap.value}[msec]")
            print("")
        #--------------------
        # AioResetTmCount
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Reset
            #----------------------------------------
            lret.value = caio.AioResetTmCount(id, 0)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioResetTmCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Stop Watch Timer Operation Stop
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Stop operation
            #----------------------------------------
            lret.value = caio.AioStopTmCount(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nStop Watch Timer Operation Stop Error")
                print(f"AioStopTmCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("\nStop Watch Timer Operation Stop : Successful completion\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # Exit process
            #----------------------------------------
            lret.value = caio.AioExit(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # 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()