#================================================================
#================================================================
# API-CNT(WDM) for サンプリング機能搭載デバイス
# カウンタサンプル
# ハードウェアイベント設定ファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ccnt
from EventUI import EventWindowUI


#========================================
# EventWindow クラス
#========================================
class EventWindow:
    #========================================
    # 初期化関数
    #========================================
    def __init__(self, parent):
        #----------------------------------------
        # 変数
        #----------------------------------------
        self.input_event   = (ccnt.CNT_IEVENT_GENINP,       # 汎用入力
                              ccnt.CNT_IEVENT_STARTSTOP,    # カウンタ 開始/停止
                              ccnt.CNT_IEVENT_PRESET,       # カウンタ プリセット
                              ccnt.CNT_IEVENT_CLEAR,        # カウンタ クリア
                              -1)                           # End
        self.count_event   = (ccnt.CNT_MATCH_NONE,          # なし
                              ccnt.CNT_MATCH_PRESET,        # プリセット
                              ccnt.CNT_MATCH_CLEAR,         # クリア
                              -1)                           # End
        self.rf            = (ccnt.CNT_INP_RIZE,            # 立ち上
                              ccnt.CNT_INP_FALL,            # 立ち下
                              ccnt.CNT_INP_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          # 出力イベント
        #----------------------------------------
        # 親ウィンドウの設定
        #----------------------------------------
        self.parent = parent
        #----------------------------------------
        # UIの作成を開始
        #----------------------------------------
        self.ui = EventWindowUI(parent)
        #----------------------------------------
        # UIコントロールのコールバック関数を設定
        #----------------------------------------
        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
        )
        #----------------------------------------
        # UIの更新を開始
        #----------------------------------------
        self._update_ui()

    #========================================
    # UIの更新関数
    #========================================
    def _update_ui(self):
        #----------------------------------------
        # ウィンドウ画面は最後に選択した設定に設定されます
        #----------------------------------------
        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()
        #----------------------------------------
        # イベント信号出力
        #----------------------------------------
        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')

    #========================================
    # 関数名    isnum
    # 引数      str     文字列
    # 引数      base    ベース
    # 詳細      文字列を数値に変換できるかどうか確認する関数
    # 戻り値    True : 変換できる
    #           False : 変換できない
    #========================================
    @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

    #========================================
    # 関数名    OnClickedRadioGenOutput
    # 引数      なし
    # 詳細      イベント信号出力 設定
    # 戻り値    なし
    #========================================
    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')

    #========================================
    # 関数名    OnClickedRadioCountMatch0
    # 引数      なし
    # 詳細      イベント信号出力 設定
    # 戻り値    なし
    #========================================
    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')

    #========================================
    # 関数名    OnClickedRadioCountMatch1
    # 引数      なし
    # 詳細      イベント信号出力 設定
    # 戻り値    なし
    #========================================
    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')

    #========================================
    # 関数名    OnClickedRadioAiError
    # 引数      なし
    # 詳細      イベント信号出力 設定
    # 戻り値    なし
    #========================================
    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')

    #========================================
    # 関数名    OnClickedRadioFilterError
    # 引数      なし
    # 詳細      イベント信号出力 設定
    # 戻り値    なし
    #========================================
    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')

    #========================================
    # 関数名    OnClickedRadioAlarmError
    # 引数      なし
    # 詳細      イベント信号出力 設定
    # 戻り値    なし
    #========================================
    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')

    #========================================
    # 関数名    OnSelendokComboInputEvent
    # 引数      event    イベント(None固定)
    # 詳細      イベント信号入力 設定
    # 戻り値    なし
    #========================================
    def OnSelendokComboInputEvent(self, event=None):
        #----------------------------------------
        # コンボボックスからイベント信号入力を取得
        #----------------------------------------
        selected = self.ui.combobox_input_type.get()
        #----------------------------------------
        # イベント信号入力による分岐処理
        #----------------------------------------
        if selected == "汎用入力":
            self.ui.combobox_input_event_rf0.set("なし")
            self.ui.combobox_input_event_rf1.set("なし")
            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 == "カウンタ 開始/停止":
            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 == "カウンタ プリセット":
            self.ui.combobox_input_event_rf0.config(state = 'readonly')
            self.ui.combobox_input_event_rf1.set("なし")
            self.ui.combobox_input_event_rf1.config(state = 'disabled')
            self.ui.textbox_input_preset_register_value.config(state = 'normal')
        if selected == "カウンタ クリア":
            self.ui.combobox_input_event_rf0.config(state = 'readonly')
            self.ui.combobox_input_event_rf1.set("なし")
            self.ui.combobox_input_event_rf1.config(state = 'disabled')
            self.ui.textbox_input_preset_register_value.config(state = 'disabled')
        #----------------------------------------
        # コンボボックスからカウント一致イベントを取得
        #----------------------------------------
        selected = self.ui.combobox_count_match_type.get()
        #----------------------------------------
        # カウント一致イベントによる分岐処理
        #----------------------------------------
        if selected == "プリセット":
            self.ui.textbox_input_preset_register_value.config(state = 'normal')

    #========================================
    # 関数名    OnSelendokComboCount
    # 引数      event    イベント(None固定)
    # 詳細      カウント一致イベント 設定
    # 戻り値    なし
    #========================================
    def OnSelendokComboCount(self, event=None):
        self.OnSelendokComboInputEvent()

    #========================================
    # 関数名    OnClickedButtonOutPulse
    # 引数      なし
    # 詳細      信号出力 処理
    # 戻り値    なし
    #========================================
    def OnClickedButtonOutPulse(self):
        error_string = ctypes.create_string_buffer(256)    # エラーコード文字列
        lret = ctypes.c_long()                             # 戻り値取得用
        ch_no = ctypes.c_short()                           # チャネルナンバー
        data = ctypes.c_byte()                             # 出力データ

        buf = self.ui.textbox_output_preset_register_value_ch_var.get()
        #----------------------------------------
        # 入力値が数値かどうかをチェック
        #----------------------------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "入力値が無効です。")
            return
        else:
            ch_no = ctypes.c_short(int(buf))
        buf = self.ui.textbox_output_preset_register_value_data_var.get()
        #----------------------------------------
        # 入力値が数値かどうかをチェック
        #----------------------------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "入力値が無効です。")
            return
        else:
            data = ctypes.c_short(int(buf))
        #----------------------------------------
        # 汎用出力処理
        #----------------------------------------
        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)
            #----------------------------------------
            # メッセージ表示
            #----------------------------------------
            text_buf = f"CntOutputDOBit = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return

    #========================================
    # 関数名    OnOK
    # 引数      なし
    # 詳細      設定完了処理
    # 戻り値    なし
    #========================================
    def OnOK(self):
        error_string = ctypes.create_string_buffer(256)    # エラーコード文字列
        lret = ctypes.c_long()                             # 戻り値取得用
        ch_no = ctypes.c_short()                           # チャネルナンバー
        input_event = ctypes.c_ulong()                     # 入力イベント
        count_event = ctypes.c_ulong()                     # カウントマッチイベント
        preset_reg = ctypes.c_ulong()                      # プリセットレジスタ
        pulse_length = ctypes.c_short()                    # パルス幅
        rf0 = ctypes.c_short()                             # 指定したイベントが制御入力信号
        rf1 = ctypes.c_short()                             # 指定したイベントが制御入力信号

        #----------------------------------------
        # 設定情報取得
        #----------------------------------------
        #--------------------
        # イベント信号入力
        #--------------------
        input_event = ctypes.c_ulong(self.input_event[self.ui.combobox_input_type.current()])
        buf = self.ui.textbox_input_preset_register_value_var.get()
        #--------------------
        # 入力値が数値かどうかをチェック
        #--------------------
        if False == self.isnum(buf, 16):
            self.ui.show_error("Error", "入力値が無効です。")
            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()])
        #--------------------
        # イベント信号出力
        #--------------------
        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_event = ctypes.c_ulong(self.count_event[self.ui.combobox_count_match_type.current()])
        #----------------------------------------
        # 画面の最後の設定値を記録
        #----------------------------------------
        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()
        #----------------------------------------
        # 設定情報をデバイスへセット
        #----------------------------------------
        for ch_no.value in range(0, self.parent.channel_num.value):
            #----------------------------------------
            # 制御入力信号のハードウェアイベント設定
            #----------------------------------------
            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)
                #----------------------------------------
                # メッセージ表示
                #----------------------------------------
                text_buf = f"CntSetInputHardwareEvent = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # プリセットレジスタの設定
            #----------------------------------------
            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)
                    #----------------------------------------
                    # メッセージ表示
                    #----------------------------------------
                    text_buf = f"CntSetPresetRegister = {lret.value} : {error_string.value.decode('sjis')}"
                    self.ui.show_error("Error", text_buf)
                    break
            #----------------------------------------
            # 制御出力信号のハードウェアイベント設定
            #----------------------------------------
            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)
                #----------------------------------------
                # メッセージ表示
                #----------------------------------------
                text_buf = f"CntSetOutputHardwareEvent = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
            #----------------------------------------
            # カウント一致のハードウェアイベント設定
            #----------------------------------------
            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)
                #----------------------------------------
                # メッセージ表示
                #----------------------------------------
                text_buf = f"CntSetCountMatchHardwareEvent = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                break
        #----------------------------------------
        # ウィンドウを終了する
        #----------------------------------------
        self.ui.event_window.destroy()

    #========================================
    # 関数名    OnClickedButtonCancel
    # 引数      なし
    # 詳細      Cancelボタンクリックイベント関数
    # 戻り値    なし
    #========================================
    def OnClickedButtonCancel(self):
        #----------------------------------------
        # ウィンドウを終了する
        #----------------------------------------
        self.ui.event_window.destroy()