#================================================================
#================================================================
# API-DIO(WDM)
# Digital Input Counter Sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import cdio
from DiCounterUI import DiCounterUI


#========================================
# DiCounter class
#========================================
class DiCounter:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Macro definition
        #----------------------------------------
        self.MAX_COUNT_CH = 16                                               # Max number of channels
        self.DISP_MAX_COUNT_CH = 8                                           # Max number of channels to display
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()                                           # ID for device access
        self.count_ch_num = ctypes.c_short()                                 # Number of counter channels in the device
        self.combobox_count_edge = [None] * self.MAX_COUNT_CH                # Array for storing count edge control
        self.textbox_compare_count_value_var = [None] * self.MAX_COUNT_CH    # Array for storing comparison count value control variable
        self.textbox_compare_count_value = [None] * self.MAX_COUNT_CH        # Array for storing comparison count value control
        self.textbox_preset_value_var = [None] * self.MAX_COUNT_CH           # Array for storing preset value control variable
        self.textbox_preset_value = [None] * self.MAX_COUNT_CH               # Array for storing preset value control
        self.textbox_count_value_var = [None] * self.MAX_COUNT_CH            # Array for storing count value control variable
        self.textbox_count_value = [None] * self.MAX_COUNT_CH                # Array for storing count value control
        self.textbox_count_status_var = [None] * self.MAX_COUNT_CH           # Array for storing count status control variable
        self.textbox_count_status = [None] * self.MAX_COUNT_CH               # Array for storing count status control
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = DiCounterUI()
        #----------------------------------------
        # Set the instance array for the combobox
        #----------------------------------------
        self.combobox_count_edge[0] = self.ui.combobox_count_edge0
        self.combobox_count_edge[1] = self.ui.combobox_count_edge1
        self.combobox_count_edge[2] = self.ui.combobox_count_edge2
        self.combobox_count_edge[3] = self.ui.combobox_count_edge3
        self.combobox_count_edge[4] = self.ui.combobox_count_edge4
        self.combobox_count_edge[5] = self.ui.combobox_count_edge5
        self.combobox_count_edge[6] = self.ui.combobox_count_edge6
        self.combobox_count_edge[7] = self.ui.combobox_count_edge7
        #----------------------------------------
        # Set the comparison count value and instance array for the textbox
        #----------------------------------------
        self.textbox_compare_count_value_var[0] = self.ui.textbox_compare_count_value0_var
        self.textbox_compare_count_value[0] = self.ui.textbox_compare_count_value0
        self.textbox_compare_count_value_var[1] = self.ui.textbox_compare_count_value1_var
        self.textbox_compare_count_value[1] = self.ui.textbox_compare_count_value1
        self.textbox_compare_count_value_var[2] = self.ui.textbox_compare_count_value2_var
        self.textbox_compare_count_value[2] = self.ui.textbox_compare_count_value2
        self.textbox_compare_count_value_var[3] = self.ui.textbox_compare_count_value3_var
        self.textbox_compare_count_value[3] = self.ui.textbox_compare_count_value3
        self.textbox_compare_count_value_var[4] = self.ui.textbox_compare_count_value4_var
        self.textbox_compare_count_value[4] = self.ui.textbox_compare_count_value4
        self.textbox_compare_count_value_var[5] = self.ui.textbox_compare_count_value5_var
        self.textbox_compare_count_value[5] = self.ui.textbox_compare_count_value5
        self.textbox_compare_count_value_var[6] = self.ui.textbox_compare_count_value6_var
        self.textbox_compare_count_value[6] = self.ui.textbox_compare_count_value6
        self.textbox_compare_count_value_var[7] = self.ui.textbox_compare_count_value7_var
        self.textbox_compare_count_value[7] = self.ui.textbox_compare_count_value7
        #----------------------------------------
        # Set preset values and instance arrays for the textbox
        #----------------------------------------
        self.textbox_preset_value_var[0] = self.ui.textbox_preset_value0_var
        self.textbox_preset_value[0] = self.ui.textbox_preset_value0
        self.textbox_preset_value_var[1] = self.ui.textbox_preset_value1_var
        self.textbox_preset_value[1] = self.ui.textbox_preset_value1
        self.textbox_preset_value_var[2] = self.ui.textbox_preset_value2_var
        self.textbox_preset_value[2] = self.ui.textbox_preset_value2
        self.textbox_preset_value_var[3] = self.ui.textbox_preset_value3_var
        self.textbox_preset_value[3] = self.ui.textbox_preset_value3
        self.textbox_preset_value_var[4] = self.ui.textbox_preset_value4_var
        self.textbox_preset_value[4] = self.ui.textbox_preset_value4
        self.textbox_preset_value_var[5] = self.ui.textbox_preset_value5_var
        self.textbox_preset_value[5] = self.ui.textbox_preset_value5
        self.textbox_preset_value_var[6] = self.ui.textbox_preset_value6_var
        self.textbox_preset_value[6] = self.ui.textbox_preset_value6
        self.textbox_preset_value_var[7] = self.ui.textbox_preset_value7_var
        self.textbox_preset_value[7] = self.ui.textbox_preset_value7
        #----------------------------------------
        # Set the count value and instance array for the textbox
        #----------------------------------------
        self.textbox_count_value_var[0] = self.ui.textbox_count_value0_var
        self.textbox_count_value[0] = self.ui.textbox_count_value0
        self.textbox_count_value_var[1] = self.ui.textbox_count_value1_var
        self.textbox_count_value[1] = self.ui.textbox_count_value1
        self.textbox_count_value_var[2] = self.ui.textbox_count_value2_var
        self.textbox_count_value[2] = self.ui.textbox_count_value2
        self.textbox_count_value_var[3] = self.ui.textbox_count_value3_var
        self.textbox_count_value[3] = self.ui.textbox_count_value3
        self.textbox_count_value_var[4] = self.ui.textbox_count_value4_var
        self.textbox_count_value[4] = self.ui.textbox_count_value4
        self.textbox_count_value_var[5] = self.ui.textbox_count_value5_var
        self.textbox_count_value[5] = self.ui.textbox_count_value5
        self.textbox_count_value_var[6] = self.ui.textbox_count_value6_var
        self.textbox_count_value[6] = self.ui.textbox_count_value6
        self.textbox_count_value_var[7] = self.ui.textbox_count_value7_var
        self.textbox_count_value[7] = self.ui.textbox_count_value7
        #----------------------------------------
        # Set the count status and instance array for the textbox
        #----------------------------------------
        self.textbox_count_status_var[0] = self.ui.textbox_count_status0_var
        self.textbox_count_status[0] = self.ui.textbox_count_status0
        self.textbox_count_status_var[1] = self.ui.textbox_count_status1_var
        self.textbox_count_status[1] = self.ui.textbox_count_status1
        self.textbox_count_status_var[2] = self.ui.textbox_count_status2_var
        self.textbox_count_status[2] = self.ui.textbox_count_status2
        self.textbox_count_status_var[3] = self.ui.textbox_count_status3_var
        self.textbox_count_status[3] = self.ui.textbox_count_status3
        self.textbox_count_status_var[4] = self.ui.textbox_count_status4_var
        self.textbox_count_status[4] = self.ui.textbox_count_status4
        self.textbox_count_status_var[5] = self.ui.textbox_count_status5_var
        self.textbox_count_status[5] = self.ui.textbox_count_status5
        self.textbox_count_status_var[6] = self.ui.textbox_count_status6_var
        self.textbox_count_status[6] = self.ui.textbox_count_status6
        self.textbox_count_status_var[7] = self.ui.textbox_count_status7_var
        self.textbox_count_status[7] = self.ui.textbox_count_status7
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_dio_init=self.OnClickedButtonDioInit,
            command_dio_set_count_edge=self.OnClickedButtonDioSetCountEdge,
            command_dio_set_count_match_value=self.OnClickedButtonDioSetCountMatchValue,
            command_dio_start_count=self.OnClickedButtonDioStartCount,
            command_dio_read_count=self.OnClickedButtonDioReadCount,
            command_dio_get_count_status=self.OnClickedButtonDioGetCountStatus,
            command_dio_count_preset=self.OnClickedButtonDioCountPreset,
            command_dio_stop_count=self.OnClickedButtonDioStopCount,
            command_dio_exit=self.OnClickedButtonDioExit,
            command_exit=self.OnClickedButtonExit
        )

    #========================================
    # Function name    isnum
    # Parameter        str     String
    # Parameter        base    Base
    # Details          Function to check if a string can be converted to a number
    # Return value     True: Can be converted
    #                  False: Can not be converted
    #========================================
    @staticmethod
    def isnum(str, base):
        try:
            if 10 == base:
                int(str, 10)
            elif 16 == base:
                int(str, 16)
            else:
                float(str)
        except:
            return False
        return True

    #========================================
    # Function name    OnClickedButtonDioInit
    # Parameter        None
    # Details          DioInit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioInit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get device name from screen
        #----------------------------------------
        device_name = self.ui.textbox_device_name_var.get()
        #----------------------------------------
        # Execute initialization function and get ID
        #----------------------------------------
        lret.value = cdio.DioInit(device_name.encode(), ctypes.byref(self.id))
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioInit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # Get number of channels
        #----------------------------------------
        lret.value = cdio.DioGetMaxCountChannels(self.id, ctypes.byref(self.count_ch_num))
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioGetMaxCountChannels = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Disable controls for channels not present in device
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value, self.DISP_MAX_COUNT_CH):
            #----------------------------------------
            # Count edge control
            #----------------------------------------
            self.combobox_count_edge[ch_no].config(state = 'disabled')
            #----------------------------------------
            # Comparison count value control
            #----------------------------------------
            self.textbox_compare_count_value[ch_no].config(state = 'disabled')
            #----------------------------------------
            # Preset value control
            #----------------------------------------
            self.textbox_preset_value[ch_no].config(state = 'disabled')
            #----------------------------------------
            # Count value control
            #----------------------------------------
            self.textbox_count_value[ch_no].config(state = 'disabled')
            #----------------------------------------
            # Count status control
            #----------------------------------------
            self.textbox_count_status[ch_no].config(state = 'disabled')
        #----------------------------------------
        # Correct the number of count channels to the maximum number of channels that can be displayed
        #----------------------------------------
        if self.DISP_MAX_COUNT_CH < self.count_ch_num.value:
            self.count_ch_num.value = self.DISP_MAX_COUNT_CH

    #========================================
    # Function name    OnClickedButtonDioSetCountEdge
    # Parameter        None
    # Details          DioSetCountEdge button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioSetCountEdge(self):
        error_string = ctypes.create_string_buffer(256)         # Error code string
        lret = ctypes.c_long()                                  # For return code
        ch_no_array = (ctypes.c_short * self.MAX_COUNT_CH)()    # Pointer to channel number storage area
        count_edge = (ctypes.c_short * self.MAX_COUNT_CH)()     # Pointer to count edge storage area

        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value):
            #----------------------------------------
            # Save channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
            #----------------------------------------
            # Get the specified count edge value
            #----------------------------------------
            if self.combobox_count_edge[ch_no].get() == 'Rising':
                count_edge[ch_no] = cdio.DIO_COUNT_EDGE_UP
            elif self.combobox_count_edge[ch_no].get() == 'Falling':
                count_edge[ch_no] = cdio.DIO_COUNT_EDGE_DOWN
            else:
                count_edge[ch_no] = cdio.DIO_COUNT_EDGE_UP | cdio.DIO_COUNT_EDGE_DOWN
        #----------------------------------------
        # Set count edge
        #----------------------------------------
        lret.value = cdio.DioSetCountEdge(self.id, ch_no_array, self.count_ch_num, count_edge)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioSetCountEdge = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioSetCountMatchValue
    # Parameter        None
    # Details          DioSetCountMatchValue button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioSetCountMatchValue(self):
        error_string = ctypes.create_string_buffer(256)                     # Error code string
        lret = ctypes.c_long()                                              # For return code
        ch_no_array = (ctypes.c_short * self.MAX_COUNT_CH)()                # Pointer to channel number storage area
        count_match_register_no = (ctypes.c_short * self.MAX_COUNT_CH)()    # Pointer to comparison register number storage area
        count_match_value = (ctypes.c_ulong * self.MAX_COUNT_CH)()          # Pointer to comparison count value storage area

        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value):
            #----------------------------------------
            # Save channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
            #----------------------------------------
            # Save comparison register number
            #----------------------------------------
            count_match_register_no[ch_no] = 0
            #----------------------------------------
            # Get the specified comparison count value
            #----------------------------------------
            buf = self.textbox_compare_count_value_var[ch_no].get()
            #----------------------------------------
            # Check if the input value is a number
            #----------------------------------------
            if False == self.isnum(buf, 10):
                self.ui.show_error("Error", "The input value is invalid.")
                return
            else:
                count_match_value[ch_no] = ctypes.c_ulong(int(buf, 10))
        #----------------------------------------
        # Set comparison register
        #----------------------------------------
        lret.value = cdio.DioSetCountMatchValue(self.id, ch_no_array, self.count_ch_num, count_match_register_no, count_match_value)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioSetCountMatchValue = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioStartCount
    # Parameter        None
    # Details          DioStartCount button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioStartCount(self):
        error_string = ctypes.create_string_buffer(256)         # Error code string
        lret = ctypes.c_long()                                  # For return code
        ch_no_array = (ctypes.c_short * self.MAX_COUNT_CH)()    # Pointer to channel number storage area

        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value):
            #----------------------------------------
            # Save channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
        #----------------------------------------
        # Start count
        #----------------------------------------
        lret.value = cdio.DioStartCount(self.id, ch_no_array, self.count_ch_num)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioStartCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioReadCount
    # Parameter        None
    # Details          DioReadCount button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioReadCount(self):
        error_string = ctypes.create_string_buffer(256)         # Error code string
        lret = ctypes.c_long()                                  # For return code
        ch_no_array = (ctypes.c_short * self.MAX_COUNT_CH)()    # Pointer to channel number storage area
        count = (ctypes.c_ulong * self.MAX_COUNT_CH)()          # Pointer to count value storage area

        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value):
            #----------------------------------------
            # Save channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
        #----------------------------------------
        # Read count value
        #----------------------------------------
        lret.value = cdio.DioReadCount(self.id, ch_no_array, self.count_ch_num, count)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioReadCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value):
            #----------------------------------------
            # Update the display of count value
            #----------------------------------------
            text_buf = f"{count[ch_no]}"
            self.textbox_count_value_var[ch_no].set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioGetCountStatus
    # Parameter        None
    # Details          DioGetCountStatus button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioGetCountStatus(self):
        error_string = ctypes.create_string_buffer(256)          # Error code string
        lret = ctypes.c_long()                                   # For return code
        ch_no_array = (ctypes.c_short * self.MAX_COUNT_CH)()     # Pointer to channel number storage area
        count_status = (ctypes.c_ulong * self.MAX_COUNT_CH)()    # Pointer to count status storage area

        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value):
            #----------------------------------------
            # Save channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
        #----------------------------------------
        # Read count status
        #----------------------------------------
        lret.value = cdio.DioGetCountStatus(self.id, ch_no_array, self.count_ch_num, count_status)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioGetCountStatus = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value):
            #----------------------------------------
            # Update the display of count status
            #----------------------------------------
            text_buf = f"{count_status[ch_no]:x}"
            self.textbox_count_status_var[ch_no].set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioCountPreset
    # Parameter        None
    # Details          DioCountPreset button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioCountPreset(self):
        error_string = ctypes.create_string_buffer(256)          # Error code string
        lret = ctypes.c_long()                                   # For return code
        ch_no_array = (ctypes.c_short * self.MAX_COUNT_CH)()     # Pointer to channel number storage area
        preset_count = (ctypes.c_ulong * self.MAX_COUNT_CH)()    # Pointer to preset value storage area

        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value):
            #----------------------------------------
            # Save channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
            #----------------------------------------
            # Get the specified preset count value
            #----------------------------------------
            buf = self.textbox_preset_value_var[ch_no].get()
            #----------------------------------------
            # Check if the input value is a number
            #----------------------------------------
            if False == self.isnum(buf, 10):
                self.ui.show_error("Error", "The input value is invalid.")
                return
            else:
                preset_count[ch_no] = ctypes.c_ulong(int(buf, 10))
        #----------------------------------------
        # Preset count value
        #----------------------------------------
        lret.value = cdio.DioCountPreset(self.id, ch_no_array, self.count_ch_num, preset_count)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioCountPreset = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioStopCount
    # Parameter        None
    # Details          DioStopCount button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioStopCount(self):
        error_string = ctypes.create_string_buffer(256)         # Error code string
        lret = ctypes.c_long()                                  # For return code
        ch_no_array = (ctypes.c_short * self.MAX_COUNT_CH)()    # Pointer to channel number storage area

        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(self.count_ch_num.value):
            #----------------------------------------
            # Save channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
        #----------------------------------------
        # Stop count
        #----------------------------------------
        lret.value = cdio.DioStopCount(self.id, ch_no_array, self.count_ch_num)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioStopCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioExit
    # Parameter        None
    # Details          DioExit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioExit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Exit process
        #----------------------------------------
        lret.value = cdio.DioExit(self.id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioExit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonExit
    # Parameter        None
    # Details          Exit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonExit(self):
        #----------------------------------------
        # Exit process
        #----------------------------------------
        cdio.DioExit(self.id)
        #----------------------------------------
        # Exit the window
        #----------------------------------------
        self.ui.root.destroy()

    #========================================
    # Function name    run
    # Parameter        None
    # Details          A function that runs the application
    # Return value     None
    #========================================
    def run(self):
        self.ui.run()


#========================================
# main function
#========================================
def main():
    #----------------------------------------
    # Create and Run DiCounter 
    #----------------------------------------
    instance = DiCounter()
    instance.run()

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