#================================================================
#================================================================
# API-CNT(WDM)
# Counter Sample
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
import ctypes
import ctypes.wintypes
import sys
import ccnt


#================================================================
# Macro definition
#================================================================
MENU_NUM_MAIN = 0               # Main menu
MENU_NUM_CHMAX = 1              # The number acquisition of use channels
MENU_NUM_ZMODE = 2              # Set the Z phase mode
MENU_NUM_ZLOGIC = 3             # Set the Z phase logic
MENU_NUM_CHANNELSIGNAL = 4      # Set the external signal source
MENU_NUM_COUNTDIRECTION = 5     # Set the direction of count
MENU_NUM_DIGITALFILTER = 6      # Set digital filter
MENU_NUM_PHASE = 7              # Number of phases
MENU_NUM_MUL = 8                # Multiply
MENU_NUM_CLR = 9                # Clear method
MENU_NUM_PRESET = 10            # Preset
MENU_MODE_SET = 1               # Setting
MENU_START_COUNT = 2            # Count start
MENU_READ_COUNT = 3             # Counter value acquisition
MENU_READ_STATUS = 4            # Status acquisition
MENU_PRESET = 5                 # Preset
MENU_STOP_COUNT = 6             # Count stop
MENU_END = 999                  # Menu end


#================================================================
# External variables
#================================================================
MaxChannels = 0                 # Total of 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


#================================================================
# Process the input data from keyboard
#================================================================
def input_data(MenuNum):
    if MenuNum == MENU_NUM_CHMAX:
        print(f"(1-{MaxChannels}):", end='')
    input_str = input()
    return input_str


#================================================================
# Function that menu is displayed
#================================================================
def menu(MenuNum):
    #----------------------------------------
    # Initialize the menu
    #----------------------------------------
    MenuDat = [
        #----------------------------------------
        # Main Menu Data
        #----------------------------------------
        {
            #----------------------------------------
            # Use line..1   Not use..0
            #----------------------------------------
            'Line':1,
            #----------------------------------------
            # Title
            #----------------------------------------
            'StrMenu':'Menu',
            #----------------------------------------
            # Number of items
            #----------------------------------------
            'ItemCount':7,
            #----------------------------------------
            # Item    #Menu item     #Macro that correspond with the menu
            #----------------------------------------
            'Item':[{'Str':'(1).Set', 'Num':MENU_MODE_SET},
                    {'Str':'(2).CntStartCount', 'Num':MENU_START_COUNT},
                    {'Str':'(3).CntReadCount', 'Num':MENU_READ_COUNT},
                    {'Str':'(4).CntReadStatus', 'Num':MENU_READ_STATUS},
                    {'Str':'(5).CntPreset', 'Num':MENU_PRESET},
                    {'Str':'(6).CntStopCount', 'Num':MENU_STOP_COUNT},
                    {'Str':'(q).Exit', 'Num':MENU_END}],
            #----------------------------------------
            # Question
            #----------------------------------------
            'Question':'Please select the executing command.',
            #----------------------------------------
            # Prompt
            #----------------------------------------
            'Prompt':'(1-6 or q):',
        },
        #----------------------------------------
        # Mode Setting--1 Menu Data
        #----------------------------------------
        {
            'Line':0,
            'StrMenu':'',
            'ItemCount':0,
            'Item':[],
            'Question':'Please specify the using number of channels\n(Set the same setting to all channels.)',
            'Prompt':'',
        },
        #----------------------------------------
        # Mode Setting--2 Menu Data
        #----------------------------------------
        {
            'Line':1,
            'StrMenu':'Set the Z phase mode',
            'ItemCount':3,
            'Item':[{'Str':'(1).Not Use', 'Num':ccnt.CNT_ZPHASE_NOT_USE},
                    {'Str':'(2).One Time', 'Num':ccnt.CNT_ZPHASE_NEXT_ONE},
                    {'Str':'(3).Every Time', 'Num':ccnt.CNT_ZPHASE_EVERY_TIME}],
            'Question':'Please input the setting number.',
            'Prompt':'(1-3):',
        },
        #----------------------------------------
        # Mode Setting--3 Menu Data
        #----------------------------------------
        {
            'Line':1,
            'StrMenu':'Set the Z phase logic',
            'ItemCount':2,
            'Item':[{'Str':'(1).Positive Logic', 'Num':ccnt.CNT_ZLOGIC_POSITIVE},
                    {'Str':'(2).Negative Logic', 'Num':ccnt.CNT_ZLOGIC_NEGATIVE}],
            'Question':'Please input the setting number.',
            'Prompt':'(1-2):',
        },
        #----------------------------------------
        # Mode Setting--4 Menu Data
        #----------------------------------------
        {
            'Line':1,
            'StrMenu':'Set the external signal source',
            'ItemCount':3,
            'Item':[{'Str':'(1).Photo Coupler', 'Num':ccnt.CNT_SIGTYPE_ISOLATE},
                    {'Str':'(2).TTL', 'Num':ccnt.CNT_SIGTYPE_TTL},
                    {'Str':'(3).Differential', 'Num':ccnt.CNT_SIGTYPE_LINERECEIVER}],
            'Question':'Please input the setting number.',
            'Prompt':'(1-3):',
        },
        #----------------------------------------
        # Mode Setting--5 Menu Data
        #----------------------------------------
        {
            'Line':1,
            'StrMenu':'Set the count direction',
            'ItemCount':2,
            'Item':[{'Str':'(1).DOWN Count', 'Num':ccnt.CNT_DIR_DOWN},
                    {'Str':'(2).UP Count', 'Num':ccnt.CNT_DIR_UP}],
            'Question':'Please input the setting number.',
            'Prompt':'(1-2):',
        },
        #----------------------------------------
        # Mode Setting--6 Menu Data
        #----------------------------------------
        {
            'Line':0,
            'StrMenu':'',
            'ItemCount':0,
            'Item':[],
            'Question':'Please input the digital filter coefficient',
            'Prompt':'(0-F):',
        },
        #----------------------------------------
        # Mode Setting--7	Menu Data
        #----------------------------------------
        {
            'Line':1,
            'StrMenu':'Set the operation mode',
            'ItemCount':3,
            'Item':[{'Str':'(1).Single phase input', 'Num':ccnt.CNT_MODE_1PHASE},
                    {'Str':'(2).2-phase input', 'Num':ccnt.CNT_MODE_2PHASE},
                    {'Str':'(3).Single phase input with gate control', 'Num':ccnt.CNT_MODE_GATECONTROL}],
            'Question':'Please input the setting number.',
            'Prompt':'(1-3):',
        },
        #----------------------------------------
        # Mode Setting--8 Menu Data
        #----------------------------------------
        {
            'Line':1,
            'StrMenu':'Set the operation mode',
            'ItemCount':3,
            'Item':[{'Str':'(1).1X', 'Num':ccnt.CNT_MUL_X1},
                    {'Str':'(2).2X', 'Num':ccnt.CNT_MUL_X2},
                    {'Str':'(3).4X', 'Num':ccnt.CNT_MUL_X4}],
            'Question':'Please input the setting number.',
            'Prompt':'(1-3):',
        },
        #----------------------------------------
        # Mode Setting--9 Menu Data
        #----------------------------------------
        {
            'Line':1,
            'StrMenu':'Set the operation mode',
            'ItemCount':2,
            'Item':[{'Str':'(1).Async Clear', 'Num':ccnt.CNT_CLR_ASYNC},
                    {'Str':'(2).Sync Clear', 'Num':ccnt.CNT_CLR_SYNC}],
            'Question':'Please input the setting number.',
            'Prompt':'(1-2):',
        },
        #----------------------------------------
        # (5) Menu Data
        #----------------------------------------
        {
            'Line':0,
            'StrMenu':'',
            'ItemCount':0,
            'Item':[],
            'Question':'Set the same value to all channels.\nPlease input the preset data.',
            'Prompt':'Data (Decimal):',
        }]

    #----------------------------------------
    # Display the Menu and acquisition of input data
    #----------------------------------------
    while True:
        if MenuDat[MenuNum]['Line'] != 0:
            print("\n===================================")
            print(f"{MenuDat[MenuNum]['StrMenu']}")
            print("===================================")
            print("-----------------------------------")
            for i in range(0, (MenuDat[MenuNum]['ItemCount'])):
                print(f"{MenuDat[MenuNum]['Item'][i]['Str']}")  # Display Item
            print("-----------------------------------\n")
            print(f"{MenuDat[MenuNum]['Question']}")    
            print(f"{MenuDat[MenuNum]['Prompt']}", end='')
        else:
            print(f"{MenuDat[MenuNum]['Question']}")
            print(f"{MenuDat[MenuNum]['Prompt']}", end='')
        #----------------------------------------
        # Get the input data
        #----------------------------------------
        input_str = input_data(MenuNum)
        #----------------------------------------
        # Check the input data
        #----------------------------------------
        #----------------------------------------
        # The end macro is returned if the item of end is selected
        #----------------------------------------
        if MenuNum == 0:
            if input_str == 'q' or input_str == 'Q':
                return MENU_END
        #----------------------------------------
        # The input data is returned if the menu item is 0
        #----------------------------------------
        if MenuDat[MenuNum]['ItemCount'] == 0:
            if MenuNum == MENU_NUM_DIGITALFILTER:
                if False == isnum(input_str, 16):
                    continue
                return int(input_str, 16)
            else:
                if False == isnum(input_str, 10):
                    continue
                return int(input_str)
        #----------------------------------------
        # Check whether the input data is outside of the number of items
        #----------------------------------------
        if False == isnum(input_str, 10):
            continue
        if 0 < int(input_str) and int(input_str) <= MenuDat[MenuNum]['ItemCount']:
            return MenuDat[MenuNum]['Item'][int(input_str) - 1]['Num']
        print("\nThe used range is outside.\nPlease input once again.")


#================================================================
# Main function
#================================================================
def main():
    input_data = ctypes.c_short()                   # Return value of menu function
    buf = ctypes.create_string_buffer(256)          # Error string
    lret = ctypes.c_long()                          # Return value
    cnt_id = ctypes.c_short()
    sts = ctypes.c_short()                          # Buffer for status
    input_preset = ctypes.c_ulong()                 # Specify preset data
    preset_data_type = ctypes.c_ulong * 10          # Create array type
    preset_data = preset_data_type()
    device_name = ctypes.create_string_buffer(50)   # Device name
    ch_no = ctypes.c_short()                        # Channel No.
    ch_no_array_type = ctypes.c_short * 10          # Create array type
    ch_no_array = ch_no_array_type()                # Array for storing number of channels
    ch_max = ctypes.c_short()                       # Using number of channels
    cnt_data_type = ctypes.c_ulong * 10             # Create array type
    cnt_data = cnt_data_type()                      # Array for storing counter data
    phase = ctypes.c_short()                        # Specify the number of phases
    mul = ctypes.c_short()                          # Specify multiply
    sync_clr = ctypes.c_short()                     # Specify synchronization clear, asynchronization clear

    print("<<< Counter Sample Program >>>")
    device_name = input("Please input the device name of using board.\nDevice Name:")
    lret.value = ccnt.CntInit(device_name.encode(), ctypes.byref(cnt_id))
    ccnt.CntGetErrorString(lret, buf)
    print(f"CntInit RetCode = {lret.value}: {buf.value.decode('sjis')}")
    if lret.value != ccnt.CNT_ERR_SUCCESS:
        sys.exit()
    lret.value = ccnt.CntGetMaxChannels(cnt_id, ctypes.byref(ch_max))
    #----------------------------------------
    # Update the External variables
    #----------------------------------------
    global MaxChannels
    MaxChannels = ch_max.value
    #----------------------------------------
    # Execute command and display the result
    #----------------------------------------
    while True:
        input_data.value = menu( MENU_NUM_MAIN)
        if input_data.value == MENU_END:
            ccnt.CntExit(cnt_id)
            break
        #----------------------------------------
        # Set mode
        #----------------------------------------
        if input_data.value == MENU_MODE_SET:    
            #----------------------------------------
            # Using the number of channels
            #----------------------------------------
            input_data.value = menu( MENU_NUM_CHMAX)
            ch_max.value = input_data.value
            for ch_no.value in range(0, ch_max.value):
                ch_no_array[ch_no.value] = ch_no.value
            #----------------------------------------
            # Set the Z phase mode
            #----------------------------------------
            input_data.value = menu( MENU_NUM_ZMODE)
            for ch_no.value in range(0, ch_max.value):
                lret.value = ccnt.CntSetZMode(cnt_id, ch_no, input_data)
                ccnt.CntGetErrorString(lret, buf)
                print(f"Ch{ch_no.value} CntSetZMode RetCode = {lret.value}: {buf.value.decode('sjis')}")
                if lret.value != ccnt.CNT_ERR_SUCCESS:
                    break
            #----------------------------------------
            # Set the Z phase logic
            #----------------------------------------
            input_data.value = menu( MENU_NUM_ZLOGIC)
            for ch_no.value in range(0, ch_max.value):
                lret.value = ccnt.CntSetZLogic(cnt_id, ch_no, input_data)
                ccnt.CntGetErrorString(lret, buf)
                print(f"Ch{ch_no.value} CntSetZLogic RetCode = {lret.value}: {buf.value.decode('sjis')}")
                if lret.value != ccnt.CNT_ERR_SUCCESS:
                    break
            #----------------------------------------
            # Set the external signal source
            #----------------------------------------
            input_data.value = menu( MENU_NUM_CHANNELSIGNAL)
            for ch_no.value in range(0, ch_max.value):
                lret.value = ccnt.CntSelectChannelSignal(cnt_id, ch_no, input_data)
                ccnt.CntGetErrorString(lret, buf)
                print(f"Ch{ch_no.value} CntSelectChannelSignal RetCode = {lret.value}: {buf.value.decode('sjis')}")
                if lret.value != ccnt.CNT_ERR_SUCCESS:
                    break
            #----------------------------------------
            # Set the direction of count
            #----------------------------------------
            input_data.value = menu( MENU_NUM_COUNTDIRECTION)
            for ch_no.value in range(0, ch_max.value):
                lret.value = ccnt.CntSetCountDirection(cnt_id, ch_no, input_data)
                ccnt.CntGetErrorString(lret, buf)
                print(f"Ch{ch_no.value} CntSetCountDirection RetCode = {lret.value}: {buf.value.decode('sjis')}")
                if lret.value != ccnt.CNT_ERR_SUCCESS:
                    break
            #----------------------------------------
            # Digital filter coefficient
            #----------------------------------------
            input_data.value = menu( MENU_NUM_DIGITALFILTER)
            for ch_no.value in range(0, ch_max.value):
                lret.value = ccnt.CntSetDigitalFilter(cnt_id, ch_no, input_data)
                ccnt.CntGetErrorString(lret, buf)
                print(f"Ch{ch_no.value} CntSetDigitalFilter RetCode = {lret.value}: {buf.value.decode('sjis')}")
                if lret.value != ccnt.CNT_ERR_SUCCESS:
                    break
            #----------------------------------------
            # Set operation mode
            #----------------------------------------
            phase.value = menu( MENU_NUM_PHASE)
            mul.value = menu( MENU_NUM_MUL)
            sync_clr.value = menu( MENU_NUM_CLR)
            for ch_no.value in range(0, ch_max.value):
                lret.value = ccnt.CntSetOperationMode(cnt_id, ch_no, phase, mul, sync_clr)
                ccnt.CntGetErrorString(lret, buf)
                print(f"Ch{ch_no.value} CntSetOperationMode RetCode = {lret.value}: {buf.value.decode('sjis')}")
                if lret.value != ccnt.CNT_ERR_SUCCESS:
                    break
        #----------------------------------------
        # Counter start
        #----------------------------------------
        elif input_data.value == MENU_START_COUNT:
            lret.value = ccnt.CntStartCount(cnt_id, ch_no_array, ch_max)
            ccnt.CntGetErrorString(lret, buf)
            print(f"CntStartCount RetCode = {lret.value}: {buf.value.decode('sjis')}")
        #----------------------------------------
        # Get count value
        #----------------------------------------
        elif input_data.value == MENU_READ_COUNT:    
            lret.value = ccnt.CntReadCount(cnt_id, ch_no_array, ch_max, cnt_data)
            if lret.value == ccnt.CNT_ERR_SUCCESS:
                print("===================================")
                print("    Input Data (Decimal)")
                print("===================================")
                for ch_no.value in range(0, ch_max.value):
                    print(f"Channal{ch_no.value}: {cnt_data[ch_no.value]}")
            ccnt.CntGetErrorString(lret, buf)
            print(f"CntReadCount RetCode = {lret.value}: {buf.value.decode('sjis')}")
        #----------------------------------------
        # Get status
        #----------------------------------------
        elif input_data.value == MENU_READ_STATUS:
            print("===================================")
            print("    Status")
            print("===================================")
            for ch_no.value in range(0, ch_max.value):                
                lret.value = ccnt.CntReadStatus(cnt_id, ch_no, ctypes.byref(sts))
                if lret.value == ccnt.CNT_ERR_SUCCESS:
                    print(f"Channal{ch_no.value}: {sts.value:x}h")
                ccnt.CntGetErrorString(lret, buf)
                print(f"CntReadStatus RetCode = {lret.value}: {buf.value.decode('sjis')}")
        #----------------------------------------
        # Set preset
        #----------------------------------------
        elif input_data.value == MENU_PRESET:
            input_preset.value = menu( MENU_NUM_PRESET)
            for ch_no.value in range(0, ch_max.value):
                preset_data[ch_no.value] = input_preset.value
            lret.value = ccnt.CntPreset(cnt_id, ch_no_array, ch_max, preset_data)
            ccnt.CntGetErrorString(lret, buf)
            print(f"CntPreset RetCode = {lret.value}: {buf.value.decode('sjis')}")
        #----------------------------------------
        # Counter stop
        #----------------------------------------
        elif input_data.value == MENU_STOP_COUNT:
            lret.value = ccnt.CntStopCount(cnt_id, ch_no_array, ch_max)
            ccnt.CntGetErrorString(lret, buf)
            print(f"CntStopCount RetCode = {lret.value}: {buf.value.decode('sjis')}")
    sys.exit()


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