#================================================================
#================================================================
# API-CNT(WDM) for Device with sampling function
# Counter sample
# Hardware events configuration file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ccnt
from EventUI import EventWindowUI


#========================================
# EventWindow Class
#========================================
class EventWindow:
    #========================================
    # Initialization function
    #========================================
    def __init__(self, parent):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.input_event   = (ccnt.CNT_IEVENT_GENINP,       # General Input
                              ccnt.CNT_IEVENT_STARTSTOP,    # Counter Start/Stop
                              ccnt.CNT_IEVENT_PRESET,       # Counter Preset
                              ccnt.CNT_IEVENT_CLEAR,        # Counter Clear
                              -1)                           # End
        self.count_event   = (ccnt.CNT_MATCH_NONE,          # None
                              ccnt.CNT_MATCH_PRESET,        # Preset
                              ccnt.CNT_MATCH_CLEAR,         # Clear
                              -1)                           # End
        self.rf            = (ccnt.CNT_INP_RIZE,            # Rise
                              ccnt.CNT_INP_FALL,            # Fall
                              ccnt.CNT_INP_NONE,            # None
                              -1)                           # End
        self.pulse_length  = (0x00,                         # 0x0
                              0x01,                         # 0x1
                              0x02,                         # 0x2
                              0x03,                         # 0x3
                              0x04,                         # 0x4
                              0x05,                         # 0x5
                              0x06,                         # 0x6
                              0x07,                         # 0x7
                              0x08,                         # 0x8
                              0x09,                         # 0x9
                              0x0A,                         # 0xA
                              0x0B,                         # 0xB
                              0x0C,                         # 0xC
                              0x0D,                         # 0xD
                              0x0E,                         # 0xE
                              0x0F,                         # 0xF
                              -1)                           # End 
        self.output_event = ccnt.CNT_OEVENT_GENOUT          # General-purpose output
        #----------------------------------------
        # Set the parent window
        #----------------------------------------
        self.parent = parent
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = EventWindowUI(parent)
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_select_count_match_type = self.OnSelendokComboCount,
            command_select_input_type = self.OnSelendokComboInputEvent,
            command_general_output = self.OnClickedRadioGenOutput,
            command_count_match_reg0 = self.OnClickedRadioCountMatch0,
            command_count_match_reg1 = self.OnClickedRadioCountMatch1,
            command_abnormal_input_error = self.OnClickedRadioAiError,
            command_filter_error = self.OnClickedRadioFilterError,
            command_alarm_error = self.OnClickedRadioAlarmError,
            command_signal_output = self.OnClickedButtonOutPulse,
            command_event_window_ok = self.OnOK,
            command_event_window_cancel = self.OnClickedButtonCancel
        )
        #----------------------------------------
        # Start updating the UI
        #----------------------------------------
        self._update_ui()

    #========================================
    # UI update function
    #========================================
    def _update_ui(self):
        #----------------------------------------
        # The window screen will be set to the last selected setting
        #----------------------------------------
        self.ui.combobox_input_type.current(self.parent.event_window_combobox_input_type_last_selected)
        self.ui.combobox_input_event_rf0.current(self.parent.event_window_combobox_input_event_rf0_last_selected)
        self.ui.combobox_input_event_rf1.current(self.parent.event_window_combobox_input_event_rf1_last_selected)
        self.ui.textbox_input_preset_register_value_var.set(self.parent.event_window_textbox_input_preset_register_last_selected)
        self.ui.radiobutton_output_event_type_var.set(self.parent.event_window_radiobutton_output_event_type_last_selected)
        self.ui.combobox_output_pulse_width.current(self.parent.event_window_combobox_output_pulse_width_last_selected)
        self.ui.textbox_output_preset_register_value_ch_var.set(self.parent.event_window_textbox_output_preset_register_value_ch_last_selected)
        self.ui.textbox_output_preset_register_value_data_var.set(self.parent.event_window_textbox_output_preset_register_value_data_last_selected)
        self.ui.combobox_count_match_type.current(self.parent.event_window_combobox_count_match_type_last_selected)
        self.OnSelendokComboInputEvent()
        #----------------------------------------
        # Event signal output
        #----------------------------------------
        if self.ui.radiobutton_output_event_type_var.get() == 1:
            self.output_event = ccnt.CNT_OEVENT_GENOUT
        elif self.ui.radiobutton_output_event_type_var.get() == 2:
            self.output_event = ccnt.CNT_OEVENT_MATCH0
        elif self.ui.radiobutton_output_event_type_var.get() == 3:
            self.output_event = ccnt.CNT_OEVENT_MATCH1
        elif self.ui.radiobutton_output_event_type_var.get() == 4:
            self.output_event = ccnt.CNT_OEVENT_AIERR
        elif self.ui.radiobutton_output_event_type_var.get() == 5:
            self.output_event = ccnt.CNT_OEVENT_FLTERR
        elif self.ui.radiobutton_output_event_type_var.get() == 6:
            self.output_event = ccnt.CNT_OEVENT_ALMERR
        if self.output_event == ccnt.CNT_OEVENT_GENOUT:
            self.ui.radiobutton_output_event_type_var.set(1)
            self.ui.combobox_output_pulse_width.config(state = 'disabled')
            self.ui.textbox_output_preset_register_value_ch.config(state = 'normal')
            self.ui.textbox_output_preset_register_value_data.config(state = 'normal')
            self.ui.button_signal_output.config(state = 'normal')
        if self.output_event == ccnt.CNT_OEVENT_MATCH0:
            self.ui.radiobutton_output_event_type_var.set(2)
            self.ui.combobox_output_pulse_width.config(state = 'readonly')
            self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
            self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
            self.ui.button_signal_output.config(state = 'disabled')
        if self.output_event == ccnt.CNT_OEVENT_MATCH1:
            self.ui.radiobutton_output_event_type_var.set(3)
            self.ui.combobox_output_pulse_width.config(state = 'readonly')
            self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
            self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
            self.ui.button_signal_output.config(state = 'disabled')
        if self.output_event == ccnt.CNT_OEVENT_AIERR:
            self.ui.radiobutton_output_event_type_var.set(4)
            self.ui.combobox_output_pulse_width.config(state = 'readonly')
            self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
            self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
            self.ui.button_signal_output.config(state = 'disabled')
        if self.output_event == ccnt.CNT_OEVENT_FLTERR:
            self.ui.radiobutton_output_event_type_var.set(5)
            self.ui.combobox_output_pulse_width.config(state = 'readonly')
            self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
            self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
            self.ui.button_signal_output.config(state = 'disabled')
        if self.output_event == ccnt.CNT_OEVENT_ALMERR:
            self.ui.radiobutton_output_event_type_var.set(6)
            self.ui.combobox_output_pulse_width.config(state = 'readonly')
            self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
            self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
            self.ui.button_signal_output.config(state = 'disabled')

    #========================================
    # 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    OnClickedRadioGenOutput
    # Parameter        None
    # Details          Set event signal output
    # Return value     None
    #========================================
    def OnClickedRadioGenOutput(self):
        self.ui.combobox_output_pulse_width.config(state = 'disabled')
        self.ui.textbox_output_preset_register_value_ch.config(state = 'normal')
        self.ui.textbox_output_preset_register_value_data.config(state = 'normal')
        self.ui.button_signal_output.config(state = 'normal')

    #========================================
    # Function name    OnClickedRadioCountMatch0
    # Parameter        None
    # Details          Set event signal output
    # Return value     None
    #========================================
    def OnClickedRadioCountMatch0(self):
        self.ui.combobox_output_pulse_width.config(state = 'readonly')
        self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
        self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
        self.ui.button_signal_output.config(state = 'disabled')

    #========================================
    # Function name    OnClickedRadioCountMatch1
    # Parameter        None
    # Details          Set event signal output
    # Return value     None
    #========================================
    def OnClickedRadioCountMatch1(self):
        self.ui.combobox_output_pulse_width.config(state = 'readonly')
        self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
        self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
        self.ui.button_signal_output.config(state = 'disabled')

    #========================================
    # Function name    OnClickedRadioAiError
    # Parameter        None
    # Details          Set event signal output
    # Return value     None
    #========================================
    def OnClickedRadioAiError(self):
        self.ui.combobox_output_pulse_width.config(state = 'readonly')
        self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
        self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
        self.ui.button_signal_output.config(state = 'disabled')

    #========================================
    # Function name    OnClickedRadioFilterError
    # Parameter        None
    # Details          Set event signal output
    # Return value     None
    #========================================
    def OnClickedRadioFilterError(self):
        self.ui.combobox_output_pulse_width.config(state = 'readonly')
        self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
        self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
        self.ui.button_signal_output.config(state = 'disabled')

    #========================================
    # Function name    OnClickedRadioAlarmError
    # Parameter        None
    # Details          Set event signal output
    # Return value     None
    #========================================
    def OnClickedRadioAlarmError(self):
        self.ui.combobox_output_pulse_width.config(state = 'readonly')
        self.ui.textbox_output_preset_register_value_ch.config(state = 'disabled')
        self.ui.textbox_output_preset_register_value_data.config(state = 'disabled')
        self.ui.button_signal_output.config(state = 'disabled')

    #========================================
    # Function name    OnSelendokComboInputEvent
    # Parameter        event    Event(Fixed to None)
    # Details          Set event signal input
    # Return value     None
    #========================================
    def OnSelendokComboInputEvent(self, event=None):
        #----------------------------------------
        # Get event signal input from combo box
        #----------------------------------------
        selected = self.ui.combobox_input_type.get()
        #----------------------------------------
        # Branching process by event signal input
        #----------------------------------------
        if selected == "General Input":
            self.ui.combobox_input_event_rf0.set("None")
            self.ui.combobox_input_event_rf1.set("None")
            self.ui.combobox_input_event_rf0.config(state = 'disabled')
            self.ui.combobox_input_event_rf1.config(state = 'disabled')
            self.ui.textbox_input_preset_register_value.config(state = 'disabled')
        if selected == "Counter Start/Stop":
            self.ui.combobox_input_event_rf0.config(state = 'readonly')
            self.ui.combobox_input_event_rf1.config(state = 'readonly')
            self.ui.textbox_input_preset_register_value.config(state = 'disabled')
        if selected == "Counter Preset":
            self.ui.combobox_input_event_rf0.config(state = 'readonly')
            self.ui.combobox_input_event_rf1.set("None")
            self.ui.combobox_input_event_rf1.config(state = 'disabled')
            self.ui.textbox_input_preset_register_value.config(state = 'normal')
        if selected == "Counter Clear":
            self.ui.combobox_input_event_rf0.config(state = 'readonly')
            self.ui.combobox_input_event_rf1.set("None")
            self.ui.combobox_input_event_rf1.config(state = 'disabled')
            self.ui.textbox_input_preset_register_value.config(state = 'disabled')
        #----------------------------------------
        # Get count match event from combobox
        #----------------------------------------
        selected = self.ui.combobox_count_match_type.get()
        #----------------------------------------
        # Branching by count match event
        #----------------------------------------
        if selected == "Preset":
            self.ui.textbox_input_preset_register_value.config(state = 'normal')

    #========================================
    # Function name    OnSelendokComboCount
    # Parameter        event    Event(Fixed to None)
    # Details          Set event count match
    # Return value     None
    #========================================
    def OnSelendokComboCount(self, event=None):
        self.OnSelendokComboInputEvent()

    #========================================
    # Function name    OnClickedButtonOutPulse
    # Parameter        None
    # Details          Output signal
    # Return value     None
    #========================================
    def OnClickedButtonOutPulse(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.
        data = ctypes.c_byte()                             # Output data

        buf = self.ui.textbox_output_preset_register_value_ch_var.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:
            ch_no = ctypes.c_short(int(buf))
        buf = self.ui.textbox_output_preset_register_value_data_var.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:
            data = ctypes.c_short(int(buf))
        #----------------------------------------
        # General output processing
        #----------------------------------------
        lret.value = ccnt.CntOutputDOBit(self.parent.id, ch_no.value, 0, data.value)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntOutputDOBit = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return

    #========================================
    # Function name    OnOK
    # Parameter        None
    # Details          Setting completion process
    # Return value     None
    #========================================
    def OnOK(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.
        input_event = ctypes.c_ulong()                     # Input event
        count_event = ctypes.c_ulong()                     # Count match event
        preset_reg = ctypes.c_ulong()                      # Preset register
        pulse_length = ctypes.c_short()                    # Pulse width
        rf0 = ctypes.c_short()                             # The specified event is the control input signal
        rf1 = ctypes.c_short()                             # The specified event is the control input signal

        #----------------------------------------
        # Get setting information
        #----------------------------------------
        #--------------------
        # Event signal input
        #--------------------
        input_event = ctypes.c_ulong(self.input_event[self.ui.combobox_input_type.current()])
        buf = self.ui.textbox_input_preset_register_value_var.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_reg = ctypes.c_ulong(int(buf, 16))
        rf0 = ctypes.c_short(self.rf[self.ui.combobox_input_event_rf0.current()])
        rf1 = ctypes.c_short(self.rf[self.ui.combobox_input_event_rf1.current()])
        #--------------------
        # Event signal output
        #--------------------
        self.output_event = ccnt.CNT_OEVENT_GENOUT
        if self.ui.radiobutton_output_event_type_var.get() == 2:
            self.output_event |= ccnt.CNT_OEVENT_MATCH0
        elif self.ui.radiobutton_output_event_type_var.get() == 3:
            self.output_event |= ccnt.CNT_OEVENT_MATCH1
        elif self.ui.radiobutton_output_event_type_var.get() == 4:
            self.output_event |= ccnt.CNT_OEVENT_AIERR
        elif self.ui.radiobutton_output_event_type_var.get() == 5:
            self.output_event |= ccnt.CNT_OEVENT_FLTERR
        elif self.ui.radiobutton_output_event_type_var.get() == 6:
            self.output_event |= ccnt.CNT_OEVENT_ALMERR
        pulse_length = ctypes.c_short(self.pulse_length[self.ui.combobox_output_pulse_width.current()])
        #--------------------
        # Count match event
        #--------------------
        count_event = ctypes.c_ulong(self.count_event[self.ui.combobox_count_match_type.current()])
        #----------------------------------------
        # Record last settings on screen
        #----------------------------------------
        self.parent.event_window_combobox_input_type_last_selected = self.ui.combobox_input_type.current()
        self.parent.event_window_combobox_input_event_rf0_last_selected = self.ui.combobox_input_event_rf0.current()
        self.parent.event_window_combobox_input_event_rf1_last_selected = self.ui.combobox_input_event_rf1.current()
        self.parent.event_window_textbox_input_preset_register_last_selected = self.ui.textbox_input_preset_register_value.get()
        self.parent.event_window_radiobutton_output_event_type_last_selected = self.ui.radiobutton_output_event_type_var.get()
        self.parent.event_window_combobox_output_pulse_width_last_selected = self.ui.combobox_output_pulse_width.current()
        self.parent.event_window_textbox_output_preset_register_value_ch_last_selected = self.ui.textbox_output_preset_register_value_ch_var.get()
        self.parent.event_window_textbox_output_preset_register_value_data_last_selected = self.ui.textbox_output_preset_register_value_data_var.get()
        self.parent.event_window_combobox_count_match_type_last_selected = self.ui.combobox_count_match_type.current()
        #----------------------------------------
        # Set setting information to device
        #----------------------------------------
        for ch_no.value in range(0, self.parent.channel_num.value):
            #----------------------------------------
            # Set hardware event of control input signal
            #----------------------------------------
            lret.value = ccnt.CntSetInputHardwareEvent(self.parent.id, ch_no, input_event, rf0, rf1, 0)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetInputHardwareEvent = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # Set preset register
            #----------------------------------------
            if input_event.value == ccnt.CNT_IEVENT_PRESET or count_event.value == ccnt.CNT_MATCH_PRESET:
                lret.value = ccnt.CntSetPresetRegister(self.parent.id, ch_no, preset_reg, 0)
                if lret.value != ccnt.CNT_ERR_SUCCESS:
                    ccnt.CntGetErrorString(lret, error_string)
                    #----------------------------------------
                    # Display the message
                    #----------------------------------------
                    text_buf = f"CntSetPresetRegister = {lret.value} : {error_string.value.decode('sjis')}"
                    self.ui.show_error("Error", text_buf)
                    break
            #----------------------------------------
            # Set hardware event of control output signal
            #----------------------------------------
            lret.value = ccnt.CntSetOutputHardwareEvent(self.parent.id, ch_no, 0, self.output_event, pulse_length)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetOutputHardwareEvent = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # Set hardware event of count match
            #----------------------------------------
            lret.value = ccnt.CntSetCountMatchHardwareEvent(self.parent.id, ch_no, 0, count_event, 0)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # Display the message
                #----------------------------------------
                text_buf = f"CntSetCountMatchHardwareEvent = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
        #----------------------------------------
        # Exit the window
        #----------------------------------------
        self.ui.event_window.destroy()

    #========================================
    # Function name    OnClickedButtonCancel
    # Parameter        None
    # Details          Cancel button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCancel(self):
        #----------------------------------------
        # Exit the window
        #----------------------------------------
        self.ui.event_window.destroy()