#================================================================
#================================================================
# API-CNT(WDM) for Device with sampling function
# Counter sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ccnt
from CounterUI import CounterUI
import Mode
import Notify
import Event


#========================================
# Counter Class
#========================================
class Counter:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Macro definition
        #----------------------------------------
        self.CHANNEL_NUM = 4                                        # Maximum channel number
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()                                  # ID for device access
        self.channel_num = ctypes.c_short()                         # Total number of channels
        self.timer_running = False                                  # Timer start and stop flag
        self.count_match = (ctypes.c_ulong * self.CHANNEL_NUM)()    # Array for storing counter data
        self.pcount_callback = None                                 # Point to callback function
        self.pcount_error_callback = None                           # Point to callback function
        self.pcarray_borrow_callback = None                         # Point to callback function
        self.user_data = None                                       # User data of callback function
        self.textbox_count_value_var = [None] * self.CHANNEL_NUM    # Array for storing count value control variable
        self.textbox_count_value = [None] * self.CHANNEL_NUM        # Array for storing count value control
        self.textbox_count_status_var = [None] * self.CHANNEL_NUM   # Array for storing count status control variable
        self.textbox_count_status = [None] * self.CHANNEL_NUM       # Array for storing count status control
        #----------------------------------------
        # Recording the last settings on the NotifyWindow screen
        #----------------------------------------
        self.notify_window_textbox_compare_reg0_last_edit = ["100", "200", "300", "400"]
        self.notify_window_textbox_compare_reg1_last_edit = ["150", "250", "350", "450"]
        self.notify_window_radiobutton_error_last_selected = 1
        self.notify_window_radiobutton_carry_borrow_last_selected = 1
        #----------------------------------------
        # Recording the last settings on the EventWindow screen
        #----------------------------------------
        self.event_window_combobox_input_type_last_selected = 0
        self.event_window_combobox_input_event_rf0_last_selected = 2
        self.event_window_combobox_input_event_rf1_last_selected = 2
        self.event_window_textbox_input_preset_register_last_selected = "1000"
        self.event_window_radiobutton_output_event_type_last_selected = 1
        self.event_window_combobox_output_pulse_width_last_selected = 0
        self.event_window_textbox_output_preset_register_value_ch_last_selected = "0"
        self.event_window_textbox_output_preset_register_value_data_last_selected = "1"
        self.event_window_combobox_count_match_type_last_selected = 0
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = CounterUI()
        #----------------------------------------
        # Set the count value and instance array for the textbox
        #----------------------------------------
        self.textbox_count_value_var[0] = self.ui.textbox_ch0_value_var
        self.textbox_count_value[0] = self.ui.textbox_ch0_value
        self.textbox_count_value_var[1] = self.ui.textbox_ch1_value_var
        self.textbox_count_value[1] = self.ui.textbox_ch1_value
        self.textbox_count_value_var[2] = self.ui.textbox_ch2_value_var
        self.textbox_count_value[2] = self.ui.textbox_ch2_value
        self.textbox_count_value_var[3] = self.ui.textbox_ch3_value_var
        self.textbox_count_value[3] = self.ui.textbox_ch3_value
        #----------------------------------------
        # Set the count status and instance array for the textbox
        #----------------------------------------
        self.textbox_count_status_var[0] = self.ui.textbox_ch0_status_var
        self.textbox_count_status[0] = self.ui.textbox_ch0_status
        self.textbox_count_status_var[1] = self.ui.textbox_ch1_status_var
        self.textbox_count_status[1] = self.ui.textbox_ch1_status
        self.textbox_count_status_var[2] = self.ui.textbox_ch2_status_var
        self.textbox_count_status[2] = self.ui.textbox_ch2_status
        self.textbox_count_status_var[3] = self.ui.textbox_ch3_status_var
        self.textbox_count_status[3] = self.ui.textbox_ch3_status
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_cnt_init = self.OnClickedButtonCntInit,
            command_cnt_mode = self.OnClickedButtonCntMode,
            command_cnt_notify = self.OnClickedButtonCntNotify,
            command_cnt_event = self.OnClickedButtonCntEvent,
            command_cnt_start = self.OnClickedButtonCntStart,
            command_cnt_preset = self.OnClickedButtonCntPreset,
            command_cnt_reset = self.OnClickedButtonCntReset,
            command_cnt_stop = self.OnClickedButtonCntStop,
            command_cnt_exit = self.OnClickedButtonCntExit,
            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

    #========================================
    # HIWORD
    #========================================
    @staticmethod
    def HIWORD(dw):
        return (dw >> 16) & 0xFFFF

    #========================================
    # LOWORD
    #========================================
    @staticmethod
    def LOWORD(dw):
        return dw & 0xFFFF

    #========================================
    # Start timer
    #========================================
    def start_timer(self):
        self.timer_running = True
        self.update_timer()

    #========================================
    # Stop timer
    #========================================
    def stop_timer(self):
        self.timer_running = False

    #========================================
    # Timer process
    #========================================
    def update_timer(self, cycle=True):
        error_string = ctypes.create_string_buffer(256)        # Error code string
        lret = ctypes.c_long()                                 # For return code
        ch_no = ctypes.c_short()                               # Channel No.
        ch_no_array = (ctypes.c_short * self.CHANNEL_NUM)()    # Array for storing number of channels
        cnt_status_tmp = ctypes.c_ulong()                      # Temporary counter status
        cnt_status = (ctypes.c_ulong * self.CHANNEL_NUM)()     # Array for storing counter status
        cnt_data = (ctypes.c_ulong * self.CHANNEL_NUM)()       # Array for storing counter data

        if self.timer_running == True or cycle == False:
            #----------------------------------------
            # Set parameter
            #----------------------------------------
            for ch_no.value in range(0, self.channel_num.value):
                ch_no_array[ch_no.value] = ch_no.value
                cnt_data[ch_no.value] = 0
                cnt_status[ch_no.value] = 0
            #----------------------------------------
            # Get count value
            #----------------------------------------
            lret.value = ccnt.CntReadCount(self.id, ch_no_array, self.channel_num.value, cnt_data)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntReadCount = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                #----------------------------------------
                # Consider a device that does not have a timer notification function,
                # we use the window timer.
                # Please switch and use, according to the use.
                #----------------------------------------
                #----------------------------------------
                # Stop timer
                #----------------------------------------
                self.stop_timer()
                #----------------------------------------
                # When using the timer notification event of device,
                # please use the following function.
                #----------------------------------------
                #ccnt.CntStopNotifyTimer(self.id)
            #----------------------------------------
            # Get count status
            #----------------------------------------
            for ch_no.value in range(0, self.channel_num.value):
                lret.value = ccnt.CntReadStatusEx(self.id, ch_no, ctypes.byref(cnt_status_tmp))
                if lret.value != ccnt.CNT_ERR_SUCCESS:
                    ccnt.CntGetErrorString(lret, error_string)
                    #----------------------------------------
                    # Display the message
                    #----------------------------------------
                    text_buf = f"CntReadStatusEx = {lret.value} : {error_string.value.decode('sjis')}"
                    self.ui.textbox_return_string_var.set(text_buf)
                    #----------------------------------------
                    # Consider a device that does not have a timer notification function,
                    # we use the window timer.
                    # Please switch and use, according to the use.
                    #----------------------------------------
                    #----------------------------------------
                    # Stop timer
                    #----------------------------------------
                    self.stop_timer()
                    #----------------------------------------
                    # When using the timer notification event of device,
                    # please use the following function.
                    #----------------------------------------
                    #ccnt.CntStopNotifyTimer(self.id)
                cnt_status[ch_no.value] = cnt_status_tmp.value
            #----------------------------------------
            # Display data
            #----------------------------------------
            for ch_no in range(self.channel_num.value):
                text_buf = f"{cnt_data[ch_no]:d}"
                self.textbox_count_value_var[ch_no].set(text_buf)
                text_buf = f"{cnt_status[ch_no]:08X}"
                self.textbox_count_status_var[ch_no].set(text_buf)
            #----------------------------------------
            # In case of infinite loop, reset the timer
            #----------------------------------------
            if cycle == True:
                self.ui.root.after(100, self.update_timer)

    #========================================
    # Function name    OnClickedButtonCntInit
    # Parameter        None
    # Details          CntInit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCntInit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        ch_no = ctypes.c_short()                           # Channel No.

        #----------------------------------------
        # Get device name from screen
        #----------------------------------------
        device_name = self.ui.textbox_device_name_var.get()
        #----------------------------------------
        # Initialization
        #----------------------------------------
        lret.value = ccnt.CntInit(device_name.encode(), ctypes.byref(self.id))
        #----------------------------------------
        # Get error string
        #----------------------------------------
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntInit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            return
        #----------------------------------------
        # Get number of channels
        #----------------------------------------
        ccnt.CntGetMaxChannels(self.id, ctypes.byref(self.channel_num))
        #----------------------------------------
        # If the sample control count is exceeded, 
        # the total channel count is corrected to the control count.
        #----------------------------------------
        if self.CHANNEL_NUM < self.channel_num.value:
            self.channel_num.value = self.CHANNEL_NUM
        #----------------------------------------
        # Toggles the count value and status display according to the total number of channels.
        #----------------------------------------
        for ch_no in range(self.CHANNEL_NUM):
            #----------------------------------------
            # Disables the display when the number of loops exceeds the total number of channels.
            #----------------------------------------
            if ch_no >= self.channel_num.value:
                self.textbox_count_value[ch_no].config(state = 'disabled')
                self.textbox_count_status[ch_no].config(state = 'disabled')
            #----------------------------------------
            # Enables the display when the number of loops is less than or equal to the total number of channels.
            #----------------------------------------
            else:
                self.textbox_count_value[ch_no].config(state = 'normal')
                self.textbox_count_status[ch_no].config(state = 'normal')

    #========================================
    # Function name    OnClickedButtonCntMode
    # Parameter        None
    # Details          Counter mode setting screen display
    # Return value     None
    #========================================
    def OnClickedButtonCntMode(self):
        #----------------------------------------
        # Counter mode setting screen display
        #----------------------------------------
        Mode.ModeWindow(self)

    #========================================
    # Function name    OnClickedButtonCntNotify
    # Parameter        None
    # Details          Notification settings screen display
    # Return value     None
    #========================================
    def OnClickedButtonCntNotify(self):
        #----------------------------------------
        # Notification settings screen display
        #----------------------------------------
        Notify.NotifyWindow(self)

    #========================================
    # Function name    OnClickedButtonCntEvent
    # Parameter        None
    # Details          Event setting screen display
    # Return value     None
    #========================================
    def OnClickedButtonCntEvent(self):
        #----------------------------------------
        # Event setting screen display
        #----------------------------------------
        Event.EventWindow(self)

    #========================================
    # Function name    OnClickedButtonCntStart
    # Parameter        None
    # Details          CntStart button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCntStart(self):
        error_string = ctypes.create_string_buffer(256)        # Error code string
        lret = ctypes.c_long()                                 # For return code
        ch_no = ctypes.c_short()                               # Channel No.
        ch_no_array = (ctypes.c_short * self.CHANNEL_NUM)()    # Array for storing number of channels

        self.pcount_callback = ccnt.PCNT_MATCH_CALLBACK(self.SetCountUpCallBackProc)
        self.pcount_error_callback = ccnt.PCNT_COUNTER_ERR_CALLBACK(self.CounterErrorCallBackProc)
        self.pcarray_borrow_callback = ccnt.PCNT_CARRY_BORROW_CALLBACK(self.CarryBorrowCallBackProc)
        self.user_data = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p)
        #----------------------------------------
        # Callback routine
        #----------------------------------------
        #--------------------
        # Count match
        #--------------------
        lret.value = ccnt.CntCountUpCallbackProc(self.id, self.pcount_callback, self.user_data)
        #----------------------------------------
        # The error check is commented out for devices that do not have the event notification function
        # If you need the error check, uncomment it
        #----------------------------------------
        #if lret.value != ccnt.CNT_ERR_SUCCESS:
        #    ccnt.CntGetErrorString(lret, error_string)
        #    #----------------------------------------
        #    # Display the message
        #    #----------------------------------------
        #    text_buf = f"CntCountUpCallbackProc = {lret.value} : {error_string.value.decode('sjis')}"
        #    self.ui.textbox_return_string_var.set(text_buf)
        #    return
        #--------------------
        # Counter error
        #--------------------
        lret.value = ccnt.CntCounterErrorCallbackProc(self.id, self.pcount_error_callback, self.user_data)
        #----------------------------------------
        # The error check is commented out for devices that do not have the event notification function
        # If you need the error check, uncomment it
        #----------------------------------------
        #if lret.value != ccnt.CNT_ERR_SUCCESS:
        #    ccnt.CntGetErrorString(lret, error_string)
        #    #----------------------------------------
        #    # Display the message
        #    #----------------------------------------
        #    text_buf = f"CntCounterErrorCallbackProc = {lret.value} : {error_string.value.decode('sjis')}"
        #    self.ui.textbox_return_string_var.set(text_buf)
        #    return
        #--------------------
        # Carry/Borrow error
        #--------------------
        lret.value = ccnt.CntCarryBorrowCallbackProc(self.id, self.pcarray_borrow_callback, self.user_data)
        #----------------------------------------
        # The error check is commented out for devices that do not have the event notification function
        # If you need the error check, uncomment it
        #----------------------------------------
        #if lret.value != ccnt.CNT_ERR_SUCCESS:
        #    ccnt.CntGetErrorString(lret, error_string)
        #    #----------------------------------------
        #    # Display the message
        #    #----------------------------------------
        #    text_buf = f"CntCarryBorrowCallbackProc = {lret.value} : {error_string.value.decode('sjis')}"
        #    self.ui.textbox_return_string_var.set(text_buf)
        #    return
        #----------------------------------------
        # Set parameter
        #----------------------------------------
        for ch_no.value in range(0, self.channel_num.value):
            ch_no_array[ch_no.value] = ch_no.value
        #----------------------------------------
        # Start count
        #----------------------------------------
        lret.value = ccnt.CntStartCount(self.id, ch_no_array, self.channel_num.value)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntStartCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value == ccnt.CNT_ERR_SUCCESS:
            #----------------------------------------
            # Consider a device that does not have a timer notification function,
            # we use the window timer.
            # Please switch and use, according to the use.
            #----------------------------------------
            #----------------------------------------
            # Start timer
            #----------------------------------------
            self.start_timer()
            #----------------------------------------
            # When using the timer notification event of device,
            # please use the following function.
            #----------------------------------------
            #ccnt.CntNotifyTimer(self.id, 100, self.hwnd)

    #========================================
    # Function name    OnClickedButtonCntPreset
    # Parameter        None
    # Details          CntPreset button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCntPreset(self):
        error_string = ctypes.create_string_buffer(256)         # Error code string
        lret = ctypes.c_long()                                  # For return code
        ch_no = ctypes.c_short()                                # Channel No.
        ch_no_array = (ctypes.c_short * self.CHANNEL_NUM)()     # Array for storing number of channels
        preset_data = (ctypes.c_ulong * self.CHANNEL_NUM)()     # Array for storing counter data

        #----------------------------------------
        # Set preset values
        #----------------------------------------
        for ch_no.value in range(0, self.channel_num.value):
            ch_no_array[ch_no.value] = ch_no.value
            preset_data[ch_no.value] = ch_no.value * 100
        #----------------------------------------
        # Preset setting processing
        #----------------------------------------
        lret.value = ccnt.CntPreset(self.id, ch_no_array, self.channel_num.value, preset_data)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntPreset = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonCntReset
    # Parameter        None
    # Details          CntReset button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCntReset(self):
        error_string = ctypes.create_string_buffer(256)        # Error code string
        lret = ctypes.c_long()                                 # For return code
        ch_no = ctypes.c_short()                               # Channel No.
        ch_no_array = (ctypes.c_short * self.CHANNEL_NUM)()    # Array for storing number of channels

        #----------------------------------------
        # Set parameter
        #----------------------------------------
        for ch_no.value in range(0, self.channel_num.value):
            ch_no_array[ch_no.value] = ch_no.value
        #----------------------------------------
        # Reset counter
        #----------------------------------------
        lret.value = ccnt.CntZeroClearCount(self.id, ch_no_array, self.channel_num.value)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntZeroClearCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonCntStop
    # Parameter        None
    # Details          CntStop button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCntStop(self):
        error_string = ctypes.create_string_buffer(256)        # Error code string
        lret = ctypes.c_long()                                 # For return code
        ch_no = ctypes.c_short()                               # Channel No.
        ch_no_array = (ctypes.c_short * self.CHANNEL_NUM)()    # Array for storing number of channels

        #----------------------------------------
        # Set parameter
        #----------------------------------------
        for ch_no.value in range(0, self.channel_num.value):
            ch_no_array[ch_no.value] = ch_no.value
        #----------------------------------------
        # Stop count
        #----------------------------------------
        lret.value = ccnt.CntStopCount(self.id, ch_no_array, self.channel_num.value)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntStopCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # Consider a device that does not have a timer notification function,
        # we use the window timer.
        # Please switch and use, according to the use.
        #----------------------------------------
        #----------------------------------------
        # Stop timer
        #----------------------------------------
        self.stop_timer()
        #----------------------------------------
        # When using the timer notification event of device,
        # please use the following function.
        #----------------------------------------
        #ccnt.CntStopNotifyTimer(self.id)

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

        #----------------------------------------
        # Consider a device that does not have a timer notification function,
        # we use the window timer.
        # Please switch and use, according to the use.
        #----------------------------------------
        #----------------------------------------
        # Stop timer
        #----------------------------------------
        self.stop_timer()
        #----------------------------------------
        # When using the timer notification event of device,
        # please use the following function.
        #----------------------------------------
        #ccnt.CntStopNotifyTimer(self.id)
        #----------------------------------------
        # Counter termination processing
        #----------------------------------------
        lret.value = ccnt.CntExit(self.id)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntExit = {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):
        #----------------------------------------
        # Consider a device that does not have a timer notification function,
        # we use the window timer.
        # Please switch and use, according to the use.
        #----------------------------------------
        #----------------------------------------
        # Stop timer
        #----------------------------------------
        self.stop_timer()
        #----------------------------------------
        # When using the timer notification event of device,
        # please use the following function.
        #----------------------------------------
        #ccnt.CntStopNotifyTimer(self.id)
        #----------------------------------------
        # Exit process
        #----------------------------------------
        ccnt.CntExit(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()

    #========================================
    # Function name    SetCountUpCallBackProc
    # Parameter        id        Id get by CntInit
    # Parameter        wParam    Channel number of count match and direction
    # Parameter        lParam    Comparison Value
    # Parameter        Param     Parameter specified in the CntCountUpCallbackProc function
    # Details          Function registered with the CntCountUpCallbackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def SetCountUpCallBackProc(id, wparam, lparam, param):
        #----------------------------------------
        # Create the class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Count match: 0CH
        #----------------------------------------
        if self.LOWORD(wparam) == 0:
            self.count_match[0] = self.count_match[0] + 1
            if self.HIWORD(wparam) == 1:
                text_buf = f"Count Match! Channel No.: 0, UP, \nCount: {lparam : 08X}(Hex) Matched: {self.count_match[0]} times"
            else:
                text_buf = f"Count Match! Channel No.: 0, DOWN, \nCount: {lparam : 08X}(Hex) Matched: {self.count_match[0]} times"
            self.ui.label_notification.config(text=text_buf)
        #----------------------------------------
        # Count match: 1CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 1:
            self.count_match[1] = self.count_match[1] + 1
            if self.HIWORD(wparam) == 1:
                text_buf = f"Count Match! Channel No.: 1, UP, \nCount: {lparam : 08X}(Hex) Matched: {self.count_match[1]} times"
            else:
                text_buf = f"Count Match! Channel No.: 1, DOWN, \nCount: {lparam : 08X}(Hex) Matched: {self.count_match[1]} times"
            self.ui.label_notification.config(text=text_buf)
        #----------------------------------------
        # Count match: 2CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 2:
            self.count_match[2] = self.count_match[2] + 1
            if self.HIWORD(wparam) == 1:
                text_buf = f"Count Match! Channel No.: 2, UP, \nCount: {lparam : 08X}(Hex) Matched: {self.count_match[2]} times"
            else:
                text_buf = f"Count Match! Channel No.: 2, DOWN, \nCount: {lparam : 08X}(Hex) Matched: {self.count_match[2]} times"
            self.ui.label_notification.config(text=text_buf)
        #----------------------------------------
        # Count match: 3CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 3:
            self.count_match[3] = self.count_match[3] + 1
            if self.HIWORD(wparam) == 1:
                text_buf = f"Count Match! Channel No.: 3, UP, \nCount: {lparam : 08X}(Hex) Matched: {self.count_match[3]} times"
            else:
                text_buf = f"Count Match! Channel No.: 3, DOWN, \nCount: {lparam : 08X}(Hex) Matched: {self.count_match[3]} times"
            self.ui.label_notification.config(text=text_buf)

    #========================================
    # Function name    CounterErrorCallBackProc
    # Parameter        id        Id get by CntInit
    # Parameter        wParam    Channel Number
    # Parameter        lParam    Error Kind
    # Parameter        Param     Parameter specified in the CntCounterErrorCallbackProc function
    # Details          Function registered with the CntCounterErrorCallbackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def CounterErrorCallBackProc(id, wparam, lparam, param):
        #----------------------------------------
        # Create the class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Abnormal input
        #----------------------------------------
        if self.LOWORD(lparam) == ccnt.CNT_AI_ERROR:
            text_buf = f"Abnormal input error! Channel No.: {self.HIWORD(wparam)}"
            self.ui.label_notification.config(text=text_buf)
        #----------------------------------------
        # Filter
        #----------------------------------------
        elif self.LOWORD(lparam) == ccnt.CNT_FLT_ERROR:
            text_buf = f"Filter error! Channel No.: {self.HIWORD(wparam)}"
            self.ui.label_notification.config(text=text_buf)
        #----------------------------------------
        # Alarm
        #----------------------------------------
        elif self.LOWORD(lparam) == ccnt.CNT_ALM_ERROR:
            text_buf = f"Alarm error! Channel No.: {self.HIWORD(wparam)}"
            self.ui.label_notification.config(text=text_buf)

    #========================================
    # Function name    CarryBorrowCallBackProc
    # Parameter        id        Id get by CntInit
    # Parameter        wParam    Channel Number
    # Parameter        lParam    Notify Factor
    # Parameter        Param     Parameter specified in the CntCarryBorrowCallbackProc function
    # Details          Function registered with the CntCarryBorrowCallbackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def CarryBorrowCallBackProc(id, wparam, lparam, param):
        #----------------------------------------
        # Create the class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Carry
        #----------------------------------------
        if self.LOWORD(lparam) == ccnt.CNT_CB_CARRY:
            text_buf = f"Carry! Channel No.: {self.HIWORD(wparam)}"
            self.ui.label_notification.config(text=text_buf)
        #----------------------------------------
        # Borrow
        #----------------------------------------
        elif self.LOWORD(lparam) == ccnt.CNT_CB_BORROW:
            text_buf = f"Borrow! Channel No.: {self.HIWORD(wparam)}"
            self.ui.label_notification.config(text=text_buf)


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

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