#================================================================
#================================================================
# API-CNT(WDM)
# Counter Sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ccnt
from CounterUI import CounterUI
import Mode
import Compare


#========================================
# Counter class
#========================================
class Counter:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()                 # ID for device access
        self.timer_running = False                 # Timer start and stop flag
        self.textbox_ch_value_var = [None] * 8     # Array for storing count value control variables
        self.textbox_ch_value = [None] * 8         # Array for storing count value controls
        self.textbox_ch_status_var = [None] * 8    # Array for storing status value control variables
        self.textbox_ch_status = [None] * 8        # Array for storing status value controls
        self.textbox_ch_preset_var = [None] * 8    # Array for storing preset value control variables
        self.textbox_ch_preset = [None] * 8        # Array for storing preset value controls
        self.channel_num = ctypes.c_short()        # Total channel number
        self.pcount_callback = None                # Point to callback function
        self.user_data = None                      # User data of callback function
        #----------------------------------------
        # Recording the last settings on the CompareWindow screen
        #----------------------------------------
        self.compare_window_textbox_ch0_last_edit = "100"
        self.compare_window_textbox_ch1_last_edit = "200"
        self.compare_window_textbox_ch2_last_edit = "300"
        self.compare_window_textbox_ch3_last_edit = "400"
        self.compare_window_textbox_ch4_last_edit = "500"
        self.compare_window_textbox_ch5_last_edit = "600"
        self.compare_window_textbox_ch6_last_edit = "700"
        self.compare_window_textbox_ch7_last_edit = "800"
        self.compare_window_radiobutton_counter_value_base_var = 1
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = CounterUI()
        #----------------------------------------
        # Set the counter value and instance array for the textbox
        #----------------------------------------
        self.textbox_ch_value_var[0] = self.ui.textbox_ch0_value_var
        self.textbox_ch_value[0] = self.ui.textbox_ch0_value
        self.textbox_ch_value_var[1] = self.ui.textbox_ch1_value_var
        self.textbox_ch_value[1] = self.ui.textbox_ch1_value
        self.textbox_ch_value_var[2] = self.ui.textbox_ch2_value_var
        self.textbox_ch_value[2] = self.ui.textbox_ch2_value
        self.textbox_ch_value_var[3] = self.ui.textbox_ch3_value_var
        self.textbox_ch_value[3] = self.ui.textbox_ch3_value
        self.textbox_ch_value_var[4] = self.ui.textbox_ch4_value_var
        self.textbox_ch_value[4] = self.ui.textbox_ch4_value
        self.textbox_ch_value_var[5] = self.ui.textbox_ch5_value_var
        self.textbox_ch_value[5] = self.ui.textbox_ch5_value
        self.textbox_ch_value_var[6] = self.ui.textbox_ch6_value_var
        self.textbox_ch_value[6] = self.ui.textbox_ch6_value
        self.textbox_ch_value_var[7] = self.ui.textbox_ch7_value_var
        self.textbox_ch_value[7] = self.ui.textbox_ch7_value
        #----------------------------------------
        # Set the counter status and instance array for the textbox
        #----------------------------------------
        self.textbox_ch_status_var[0] = self.ui.textbox_ch0_status_var
        self.textbox_ch_status[0] = self.ui.textbox_ch0_status
        self.textbox_ch_status_var[1] = self.ui.textbox_ch1_status_var
        self.textbox_ch_status[1] = self.ui.textbox_ch1_status
        self.textbox_ch_status_var[2] = self.ui.textbox_ch2_status_var
        self.textbox_ch_status[2] = self.ui.textbox_ch2_status
        self.textbox_ch_status_var[3] = self.ui.textbox_ch3_status_var
        self.textbox_ch_status[3] = self.ui.textbox_ch3_status
        self.textbox_ch_status_var[4] = self.ui.textbox_ch4_status_var
        self.textbox_ch_status[4] = self.ui.textbox_ch4_status
        self.textbox_ch_status_var[5] = self.ui.textbox_ch5_status_var
        self.textbox_ch_status[5] = self.ui.textbox_ch5_status
        self.textbox_ch_status_var[6] = self.ui.textbox_ch6_status_var
        self.textbox_ch_status[6] = self.ui.textbox_ch6_status
        self.textbox_ch_status_var[7] = self.ui.textbox_ch7_status_var
        self.textbox_ch_status[7] = self.ui.textbox_ch7_status
        #----------------------------------------
        # Set the preset value and instance array for the textbox
        #----------------------------------------
        self.textbox_ch_preset_var[0] = self.ui.textbox_ch0_preset_value_var
        self.textbox_ch_preset[0] = self.ui.textbox_ch0_preset_value
        self.textbox_ch_preset_var[1] = self.ui.textbox_ch1_preset_value_var
        self.textbox_ch_preset[1] = self.ui.textbox_ch1_preset_value
        self.textbox_ch_preset_var[2] = self.ui.textbox_ch2_preset_value_var
        self.textbox_ch_preset[2] = self.ui.textbox_ch2_preset_value
        self.textbox_ch_preset_var[3] = self.ui.textbox_ch3_preset_value_var
        self.textbox_ch_preset[3] = self.ui.textbox_ch3_preset_value
        self.textbox_ch_preset_var[4] = self.ui.textbox_ch4_preset_value_var
        self.textbox_ch_preset[4] = self.ui.textbox_ch4_preset_value
        self.textbox_ch_preset_var[5] = self.ui.textbox_ch5_preset_value_var
        self.textbox_ch_preset[5] = self.ui.textbox_ch5_preset_value
        self.textbox_ch_preset_var[6] = self.ui.textbox_ch6_preset_value_var
        self.textbox_ch_preset[6] = self.ui.textbox_ch6_preset_value
        self.textbox_ch_preset_var[7] = self.ui.textbox_ch7_preset_value_var
        self.textbox_ch_preset[7] = self.ui.textbox_ch7_preset_value
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_count_value_dec = self.OnClickedRadioCounterDec,
            command_count_value_hex = self.OnClickedRadioCounterHex,
            command_preset_value_dec = self.OnClickedRadioPresetDec,
            command_preset_value_hex = self.OnClickedRadioPresetHex,
            command_cnt_init = self.OnClickedButtonCntInit,
            command_cnt_mode = self.OnClickedButtonCntMode,
            command_cnt_compare = self.OnClickedButtonCntCompare,
            command_cnt_start = self.OnClickedButtonCntStart,
            command_cnt_preset = self.OnClickedButtonCntPreset,
            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 * 8)()               # Array for storing number of channels
        cnt_status_tmp = ctypes.c_short()                  # Temporary counter status
        cnt_status = (ctypes.c_ulong * 8)()                # Array for storing counter status
        cnt_data = (ctypes.c_ulong * 8)()                  # 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 and status
            #----------------------------------------
            lret.value = ccnt.CntReadCount(self.id, ch_no_array, self.channel_num, cnt_data)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Error process
                #----------------------------------------
                text_buf = f"CntReadCount = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            for ch_no.value in range(0, self.channel_num.value):
                lret.value = ccnt.CntReadStatus(self.id, ch_no, ctypes.byref(cnt_status_tmp))
                if lret.value != ccnt.CNT_ERR_SUCCESS:
                    ccnt.CntGetErrorString(lret, error_string)
                    #----------------------------------------
                    # Error process
                    #----------------------------------------
                    text_buf = f"CntReadStatus = {lret.value} : {error_string.value.decode('sjis')}"
                    self.ui.textbox_return_string_var.set(text_buf)
                    return
                cnt_status[ch_no.value] = cnt_status_tmp.value
            #----------------------------------------
            # Count data, status data express
            #----------------------------------------
            for ch_no.value in range(0, self.channel_num.value):
                if self.ui.radiobutton_counter_value_base_var.get() == 1:
                    self.textbox_ch_value_var[ch_no.value].set(f'{cnt_data[ch_no.value]:d}')
                else:
                    self.textbox_ch_value_var[ch_no.value].set(f'{cnt_data[ch_no.value]:08X}')
                self.textbox_ch_status_var[ch_no.value].set(f'{cnt_status[ch_no.value]:02X}')
            #----------------------------------------
            # In case of infinite loop, reset the timer
            #----------------------------------------
            if cycle == True:
                self.ui.root.after(100, self.update_timer)

    #========================================
    # Function name    OnClickedRadioCounterDec()
    # Parameter        None
    # Details          Change comparison value display(decimal)
    # Return value     None
    #========================================
    def OnClickedRadioCounterDec(self):
        self.update_timer(False)

    #========================================
    # Function name    OnClickedRadioCounterHex()
    # Parameter        None
    # Details          Change comparison value display(hexadecimal)
    # Return value     None
    #========================================
    def OnClickedRadioCounterHex(self):
        self.update_timer(False)

    #========================================
    # Function name    OnClickedRadioPresetDec()
    # Parameter        None
    # Details          Change preset value display(decimal)
    # Return value     None
    #========================================
    def OnClickedRadioPresetDec(self):
        #----------------------------------------
        # Update screen information
        #----------------------------------------
        for i in range(0, 8):
            buf = self.textbox_ch_preset_var[i].get()
            #----------------------------------------
            # Check if the input value is a number
            #----------------------------------------
            if False == self.isnum(buf, 16):
                self.ui.show_error("Error", "The input value is invalid.")
                return
            else:
                self.textbox_ch_preset_var[i].set(f"{int(buf, 16):d}")

    #========================================
    # Function name    OnClickedRadioPresetHex()
    # Parameter        None
    # Details          Change preset value display(hexadecimal)
    # Return value     None
    #========================================
    def OnClickedRadioPresetHex(self):
        #----------------------------------------
        # Update screen information
        #----------------------------------------
        for i in range(0, 8):
            buf = self.textbox_ch_preset_var[i].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:
                self.textbox_ch_preset_var[i].set(f"{int(buf):08X}")

    #========================================
    # 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

        #----------------------------------------
        # Get device name from screen
        #----------------------------------------
        device_name = self.ui.textbox_device_name_var.get()
        #----------------------------------------
        # Initialization function execute, get ID
        #----------------------------------------
        lret.value = ccnt.CntInit(device_name.encode(), ctypes.byref(self.id))
        #----------------------------------------
        # Error process
        #----------------------------------------
        ccnt.CntGetErrorString(lret, error_string)
        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 all channel number
        #-----------------------------
        ccnt.CntGetMaxChannels(self.id, ctypes.byref(self.channel_num))
        #-----------------------------
        # Disable counter, status and preset display
        #-----------------------------
        for i in range(self.channel_num.value, 8):
            self.textbox_ch_value[i].config(state = 'disabled')
            self.textbox_ch_status[i].config(state = 'disabled')
            self.textbox_ch_preset[i].config(state = 'disabled')

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

    #========================================
    # Function name    OnClickedButtonCntCompare
    # Parameter        None
    # Details          Notification settings screen display
    # Return value     None
    #========================================
    def OnClickedButtonCntCompare(self):
        Compare.CompareWindow(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 * 8)()               # Array for storing number of channels

        self.pcount_callback = ccnt.PCNT_MATCH_CALLBACK(self.SetCountUpCallBackProc)
        self.user_data = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p)
        #----------------------------------------
        # Callback routine
        #----------------------------------------
        lret.value = ccnt.CntCountUpCallbackProc(self.id, self.pcount_callback, self.user_data)
        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
        #----------------------------------------
        # 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)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Error process
        #----------------------------------------
        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:
            return
        self.start_timer()

    #========================================
    # 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 * 8)()               # Array for storing number of channels
        preset_data = (ctypes.c_ulong * 8)()               # Array for storing preset data

        #----------------------------------------
        # Get data from screen and set parameter
        #----------------------------------------
        for ch_no.value in range(0, self.channel_num.value):
            ch_no_array[ch_no.value] = ch_no.value
            if self.ui.radiobutton_preset_value_base_var.get() == 1:
                buf = self.textbox_ch_preset_var[ch_no.value].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_data[ch_no.value] = int(buf, 10)
            else:
                buf = self.textbox_ch_preset_var[ch_no.value].get()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == self.isnum(buf, 16):
                    self.ui.show_error("Error", "The input value is invalid.")
                    return
                else:
                    preset_data[ch_no.value] = int(buf, 16)
        #----------------------------------------
        # Preset
        #----------------------------------------
        lret.value = ccnt.CntPreset(self.id, ch_no_array, self.channel_num, preset_data)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Error process
        #----------------------------------------
        text_buf = f"CntPreset = {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 * 8)()               # 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
        #----------------------------------------
        # Counter stop
        #----------------------------------------
        lret.value = ccnt.CntStopCount(self.id, ch_no_array, self.channel_num)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Error process
        #----------------------------------------
        text_buf = f"CntStopCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # Timer stop
        #----------------------------------------
        self.stop_timer()

    #========================================
    # 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

        #----------------------------------------
        # Timer stop
        #----------------------------------------
        self.stop_timer()
        #----------------------------------------
        # Exit function execute
        #----------------------------------------
        lret.value = ccnt.CntExit(self.id)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Error process
        #----------------------------------------
        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):
        #----------------------------------------
        # Timer stop
        #----------------------------------------
        self.stop_timer()
        #----------------------------------------
        # 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: 
            if self.HIWORD(wparam) == 1:
                text_buf = f"Ch0 : Count={lparam:d} : UP"
            else:
                text_buf = f"Ch0 : Count={lparam:d} : DOWN"
            self.ui.textbox_compare_result_string_var.set(text_buf)
        #----------------------------------------
        # Count match: 1CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 1:
            if self.HIWORD(wparam) == 1:
                text_buf = f"Ch1 : Count={lparam:d} : UP"
            else:
                text_buf = f"Ch1 : Count={lparam:d} : DOWN"
            self.ui.textbox_compare_result_string_var.set(text_buf)
        #----------------------------------------
        # Count match: 2CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 2:
            if self.HIWORD(wparam) == 1:
                text_buf = f"Ch2 : Count={lparam:d} : UP"
            else:
                text_buf = f"Ch2 : Count={lparam:d} : DOWN"
            self.ui.textbox_compare_result_string_var.set(text_buf)
        #----------------------------------------
        # Count match: 3CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 3:
            if self.HIWORD(wparam) == 1:
                text_buf = f"Ch3 : Count={lparam:d} : UP"
            else:
                text_buf = f"Ch3 : Count={lparam:d} : DOWN"
            self.ui.textbox_compare_result_string_var.set(text_buf)
        #----------------------------------------
        # Count match: 4CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 4:
            if self.HIWORD(wparam) == 1:
                text_buf = f"Ch4 : Count={lparam:d} : UP"
            else:
                text_buf = f"Ch4 : Count={lparam:d} : DOWN"
            self.ui.textbox_compare_result_string_var.set(text_buf)
        #----------------------------------------
        # Count match: 5CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 5:
            if self.HIWORD(wparam) == 1:
                text_buf = f"Ch5 : Count={lparam:d} : UP"
            else:
                text_buf = f"Ch5 : Count={lparam:d} : DOWN"
            self.ui.textbox_compare_result_string_var.set(text_buf)
        #----------------------------------------
        # Count match: 6CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 6:
            if self.HIWORD(wparam) == 1:
                text_buf = f"Ch6 : Count={lparam:d} : UP"
            else:
                text_buf = f"Ch6 : Count={lparam:d} : DOWN"
            self.ui.textbox_compare_result_string_var.set(text_buf)
        #----------------------------------------
        # Count match: 7CH
        #----------------------------------------
        elif self.LOWORD(wparam) == 7:
            if self.HIWORD(wparam) == 1:
                text_buf = f"Ch7 : Count={lparam:d} : UP"
            else:
                text_buf = f"Ch7 : Count={lparam:d} : DOWN"
            self.ui.textbox_compare_result_string_var.set(text_buf)
        return


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

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