#================================================================
#================================================================
# API-DIO(WDM)
# Digital Input Counter Sample
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
import ctypes
import ctypes.wintypes
import sys
import cdio


#================================================================
# Command Define
#================================================================
COMMAND_DIO_INIT = 1                # DioInit
COMMAND_DIO_SETCOUNTEDGE = 2        # DioSetCountEdge
COMMAND_DIO_SETCOUNTMATCHVALUE = 3  # DioSetCountMatchValue
COMMAND_DIO_STARTCOUNT = 4          # DioStartCount
COMMAND_DIO_READCOUNT = 5           # DioReadCount
COMMAND_DIO_GETCOUTNSTATUS = 6      # DioGetCountStatus
COMMAND_DIO_COUNTPRESET = 7         # DioCountPreset
COMMAND_DIO_STOPCOUNT = 8           # DioStopCount
COMMAND_DIO_EXIT = 9                # DioExit
COMMAND_EXIT = 10                   # Exit
MAX_CHANNEL = 8                     # Maximum number of counter channels


#================================================================
# Function that checks if a string can be converted to a number
#================================================================
def isnum(str, base):
    try:
        if 16 == base:
            int(str, 16)
        else:
            int(str)
    except:
        return False
    return True


#================================================================
# main Function
#================================================================
def main():
    err_str = ctypes.create_string_buffer(256)           # Buffer for storing input string
    lret = ctypes.c_long()                               # Variable for storing function return value
    id = ctypes.c_short()                                # Variable for storing ID
    channel_num = ctypes.c_short()                       # Variable for storing the number of counter channels
    channel_no = (ctypes.c_short * MAX_CHANNEL)()        # Array for storing counter channel numbers
    count_edge = (ctypes.c_short * MAX_CHANNEL)()        # Array for storing count direction
    compare_count = (ctypes.c_uint * MAX_CHANNEL)()      # Array for storing comparison values
    compare_reg_no = (ctypes.c_short * MAX_CHANNEL)()    # Array for storing comparison registers
    preset_count = (ctypes.c_uint * MAX_CHANNEL)()       # Array for storing preset values
    count = (ctypes.c_uint * MAX_CHANNEL)()              # Array for storing count values
    count_status = (ctypes.c_uint * MAX_CHANNEL)()       # Array for storing status

    #----------------------------------------
    # Initialize the counter channel number
    #----------------------------------------
    for i in range(0, MAX_CHANNEL):
        channel_no[i] = i
    #----------------------------------------
    # Loop that Wait Input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Display Command
        #----------------------------------------
        print('1.DioInit')
        print('2.DioSetCountEdge')
        print('3.DioSetCountMatchValue')
        print('4.DioStartCount')
        print('5.DioReadCount')
        print('6.DioGetCountStatus')
        print('7.DioCountPreset')
        print('8.DioStopCount')
        print('9.DioExit')
        print('10.Exit')
        #----------------------------------------
        # Wait Input
        #----------------------------------------
        while True:
            buf = input('input command: ')
            if False == isnum(buf, 10):
                continue
            command = int(buf)
            break
        #----------------------------------------
        # Input the related information for each command
        #----------------------------------------
        #----------------------------------------
        # DioInit
        #----------------------------------------
        if command == COMMAND_DIO_INIT:
            #----------------------------------------
            # Display the selected function name
            #----------------------------------------
            print('----------------------------------------')
            print('DioInit')
            print('----------------------------------------')
            #----------------------------------------
            # Input device name
            #----------------------------------------
            buf = input('Please input a device name: ')
        #----------------------------------------
        # DioSetCountEdge
        #----------------------------------------
        elif command == COMMAND_DIO_SETCOUNTEDGE:
            #----------------------------------------
            # Display the selected function name
            #----------------------------------------
            print('----------------------------------------')
            print('DioSetCountEdge')
            print('----------------------------------------')
            #----------------------------------------
            # Input count direction
            #----------------------------------------
            while True:
                buf = input('Please input count edge: ')
                if False == isnum(buf, 10):
                    continue
                else:
                    break
        #----------------------------------------
        # DioSetCountMatchValue
        #----------------------------------------
        elif command == COMMAND_DIO_SETCOUNTMATCHVALUE:
            #----------------------------------------
            # Display the selected function name
            #----------------------------------------
            print('----------------------------------------')
            print('DioSetCountMatchValue')
            print('----------------------------------------')
            #----------------------------------------
            # Input comparison value
            #----------------------------------------
            while True:
                buf = input('Please input match value: ')
                if False == isnum(buf, 10):
                    continue
                else:
                    break
        #----------------------------------------
        # DioStartCount
        #----------------------------------------
        elif command == COMMAND_DIO_STARTCOUNT:
            #----------------------------------------
            # Display the selected function name
            #----------------------------------------
            print('----------------------------------------')
            print('DioStartCount')
            print('----------------------------------------')
        #----------------------------------------
        # DioReadCount
        #----------------------------------------
        elif command == COMMAND_DIO_READCOUNT:
            #----------------------------------------
            # Display the selected function name
            #----------------------------------------
            print('----------------------------------------')
            print('DioReadCount')
            print('----------------------------------------')
        #----------------------------------------
        # DioGetCountStatus
        #----------------------------------------
        elif command == COMMAND_DIO_GETCOUTNSTATUS:
            #----------------------------------------
            # Display the selected function name
            #----------------------------------------
            print('----------------------------------------')
            print('DioGetCountStatus')
            print('----------------------------------------')
        #----------------------------------------
        # DioCountPreset
        #----------------------------------------
        elif command == COMMAND_DIO_COUNTPRESET:
            #----------------------------------------
            # Display the selected function name
            #----------------------------------------
            print('----------------------------------------')
            print('DioCountPreset')
            print('----------------------------------------')
            #----------------------------------------
            # Input preset value
            #----------------------------------------
            while True:
                buf = input('Please input preset: ')
                if False == isnum(buf, 10):
                    continue
                else:
                    break
        #----------------------------------------
        # DioStopCount
        #----------------------------------------
        elif command == COMMAND_DIO_STOPCOUNT:
            #----------------------------------------
            # Display the selected function name
            #----------------------------------------
            print('----------------------------------------')
            print('DioStopCount')
            print('----------------------------------------')
        #----------------------------------------
        # DioExit
        #----------------------------------------
        elif command == COMMAND_DIO_EXIT:
            #----------------------------------------
            # Display the selected function name
            #----------------------------------------
            print('----------------------------------------')
            print('DioExit')
            print('----------------------------------------')
        #----------------------------------------
        # Execute Command and Display Result
        #----------------------------------------
        #----------------------------------------
        # DioInit
        #----------------------------------------
        if command == COMMAND_DIO_INIT:
            #----------------------------------------
            # Execute DioInit
            #----------------------------------------
            lret.value = cdio.DioInit(buf.encode(), ctypes.byref(id))
            #----------------------------------------
            # Get the error code string
            #----------------------------------------
            cdio.DioGetErrorString(lret, err_str)
            #----------------------------------------
            # Display the execution result of the function
            #----------------------------------------
            print(f"DioInit = {lret.value}: {err_str.value.decode('sjis')}")
            #----------------------------------------
            # If DioInit is in error, return to command input
            #----------------------------------------
            if lret.value != cdio.DIO_ERR_SUCCESS:
                print('')
                continue
            #----------------------------------------
            # Execute DioGetMaxCountChannels
            #----------------------------------------
            lret.value = cdio.DioGetMaxCountChannels(id, ctypes.byref(channel_num))
            #----------------------------------------
            # If DioGetMaxCountChannels is in error, return to command input
            #----------------------------------------
            if lret.value != cdio.DIO_ERR_SUCCESS:
                #----------------------------------------
                # Get the error code string
                #----------------------------------------
                cdio.DioGetErrorString(lret, err_str)
                #----------------------------------------
                # Display the execution result of the function
                #----------------------------------------
                print(f"DioGetMaxCountChannels = {lret.value}: {err_str.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # If the number of counter channels is larger than the maximum number of channels,
            # update to the maximum number of channels
            #----------------------------------------
            if channel_num.value > MAX_CHANNEL:
                channel_num.value = MAX_CHANNEL
            print('')
        #----------------------------------------
        # DioSetCountEdge
        #----------------------------------------
        elif command == COMMAND_DIO_SETCOUNTEDGE:
            #----------------------------------------
            # Store the count direction in an array
            #----------------------------------------
            for i in range(0, channel_num.value):
                count_edge[i] = ctypes.c_short(int(buf))
            #----------------------------------------
            # Execute DioSetCountEdge
            #----------------------------------------
            lret.value = cdio.DioSetCountEdge(id, channel_no, channel_num, count_edge)
            #----------------------------------------
            # Get the error code string
            #----------------------------------------
            cdio.DioGetErrorString(lret, err_str)
            #----------------------------------------
            # Display the execution result of the function
            #----------------------------------------
            print(f"DioSetCountEdge = {lret.value}: {err_str.value.decode('sjis')}\n")
        #----------------------------------------
        # DioSetCountMatchValue
        #----------------------------------------
        elif command == COMMAND_DIO_SETCOUNTMATCHVALUE:
            #----------------------------------------
            # Store the comparison values in an array
            #----------------------------------------
            for i in range(0, channel_num.value):
                compare_reg_no[i] = 0
                compare_count[i] = ctypes.c_uint(int(buf))
            #----------------------------------------
            # Execute DioSetCountMatchValue
            #----------------------------------------
            lret.value = cdio.DioSetCountMatchValue(id, channel_no, channel_num, compare_reg_no, compare_count)
            #----------------------------------------
            # Get the error code string
            #----------------------------------------
            cdio.DioGetErrorString(lret, err_str)
            #----------------------------------------
            # Display the execution result of the function
            #----------------------------------------
            print(f"DioSetCountMatchValue = {lret.value}: {err_str.value.decode('sjis')}\n")
        #----------------------------------------
        # DioStartCount
        #----------------------------------------
        elif command == COMMAND_DIO_STARTCOUNT:
            #----------------------------------------
            # Execute DioStartCount
            #----------------------------------------
            lret.value = cdio.DioStartCount(id, channel_no, channel_num)
            #----------------------------------------
            # Get the error code string
            #----------------------------------------
            cdio.DioGetErrorString(lret, err_str)
            #----------------------------------------
            # Display the execution result of the function
            #----------------------------------------
            print(f"DioStartCount = {lret.value}: {err_str.value.decode('sjis')}\n")
        #----------------------------------------
        # DioReadCount
        #----------------------------------------
        elif command == COMMAND_DIO_READCOUNT:
            #----------------------------------------
            # Execute DioReadCount
            #----------------------------------------
            lret.value = cdio.DioReadCount(id, channel_no, channel_num, count)
            #----------------------------------------
            # Get the error code string
            #----------------------------------------
            cdio.DioGetErrorString(lret, err_str)
            #----------------------------------------
            # Display the execution result of the function
            #----------------------------------------
            print(f"DioReadCount = {lret.value}: {err_str.value.decode('sjis')}")
            #----------------------------------------
            # If DioReadCount is in error, return to command input
            #----------------------------------------
            if lret.value != cdio.DIO_ERR_SUCCESS:
                print('')
                continue
            #----------------------------------------
            # Display count value
            #----------------------------------------
            print('====================')
            print('Input Data (Decimal)')
            print('====================')
            for i in range(0, channel_num.value):
                print(f"Channel{i}: {count[i]}")
            print('')
        #----------------------------------------
        # DioGetCountStatus
        #----------------------------------------
        elif command == COMMAND_DIO_GETCOUTNSTATUS:
            #----------------------------------------
            # Execute DioGetCountStatus
            #----------------------------------------
            lret.value = cdio.DioGetCountStatus(id, channel_no, channel_num, count_status)
            #----------------------------------------
            # Get the error code string
            #----------------------------------------
            cdio.DioGetErrorString(lret, err_str)
            #----------------------------------------
            # Display the execution result of the function
            #----------------------------------------
            print(f"DioGetCountStatus = {lret.value}: {err_str.value.decode('sjis')}")
            #----------------------------------------
            # If DioGetCountStatus is in error, return to command input
            #----------------------------------------
            if lret.value != cdio.DIO_ERR_SUCCESS:
                print('')
                continue
            #----------------------------------------
            # Display status
            #----------------------------------------
            print('====================')
            print('Status')
            print('====================')
            for i in range(0, channel_num.value):
                print(f"Channel{i}: {count_status[i]:x}")
            print('')
        #----------------------------------------
        # DioCountPreset
        #----------------------------------------
        elif command == COMMAND_DIO_COUNTPRESET:
            #----------------------------------------
            # Store the preset values in an array
            #----------------------------------------
            for i in range(0, channel_num.value):
                preset_count[i] = ctypes.c_uint(int(buf))
            #----------------------------------------
            # Execute DioCountPreset
            #----------------------------------------
            lret.value = cdio.DioCountPreset(id, channel_no, channel_num, preset_count)
            #----------------------------------------
            # Get the error code string
            #----------------------------------------
            cdio.DioGetErrorString(lret, err_str)
            #----------------------------------------
            # Display the execution result of the function
            #----------------------------------------
            print(f"DioCountPreset = {lret.value}: {err_str.value.decode('sjis')}\n")
        #----------------------------------------
        # DioStopCount
        #----------------------------------------
        elif command == COMMAND_DIO_STOPCOUNT:
            #----------------------------------------
            # Execute DioStopCount
            #----------------------------------------
            lret.value = cdio.DioStopCount(id, channel_no, channel_num)
            #----------------------------------------
            # Get the error code string
            #----------------------------------------
            cdio.DioGetErrorString(lret, err_str)
            #----------------------------------------
            # Display the execution result of the function
            #----------------------------------------
            print(f"DioStopCount = {lret.value}: {err_str.value.decode('sjis')}\n")
        #----------------------------------------
        # DioExit
        #----------------------------------------
        elif command == COMMAND_DIO_EXIT:
            #----------------------------------------
            # Execute DioExit
            #----------------------------------------
            lret.value = cdio.DioExit(id)
            #----------------------------------------
            # Get the error code string
            #----------------------------------------
            cdio.DioGetErrorString(lret, err_str)
            #----------------------------------------
            # Display the execution result of the function
            #----------------------------------------
            print(f"DioExit = {lret.value}: {err_str.value.decode('sjis')}\n")
        #----------------------------------------
        # Exit when the Exit command is selected
        #----------------------------------------
        if command == COMMAND_EXIT:
            break
    sys.exit()


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

