#================================================================
#================================================================
# API-CNT(WDM) for サンプリング機能搭載デバイス
# 同期サンプリングサンプル
# サンプリング条件設定ファイル(スレーブ)
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ccnt
from SSampModeUI import SSamplingModeWindowUI


#========================================
# SSamplingModeWindow クラス
#========================================
class SSamplingModeWindow:
    #========================================
    # 初期化関数
    #========================================
    def __init__(self, parent):
        #----------------------------------------
        # 変数
        #----------------------------------------
        self.CHANNEL_NUM = 8                                          # 最大チャンネル数
        self.start_trg_table = (ccnt.CNTS_START_EXTSIG_1,             # ExtSig1
                                ccnt.CNTS_START_EXTSIG_2,             # ExtSig2
                                ccnt.CNTS_START_EXTSIG_3)             # ExtSig3
        self.clock_trg_table = (ccnt.CNTS_CLOCK_EXTSIG_1,             # ExtSig1
                                ccnt.CNTS_CLOCK_EXTSIG_2,             # ExtSig2
                                ccnt.CNTS_CLOCK_EXTSIG_3)             # ExtSig3
        self.stop_trg_table =  (ccnt.CNTS_STOP_EXTSIG_1,              # ExtSig1
                                ccnt.CNTS_STOP_EXTSIG_2,              # ExtSig2
                                ccnt.CNTS_STOP_EXTSIG_3,              # ExtSig3
                                ccnt.CNTS_STOP_NUM)                   # 指定個数転送完了
        self.stop_with =       (ccnt.CNTS_STOP_CNT_NOT_WITH_SAMP,     # サンプリングとは無関係に停止
                                ccnt.CNTS_STOP_CNT_WITH_SAMP)         # サンプリングと同時に停止
        self.start_with =      (ccnt.CNTS_START_CNT_NOT_WITH_SAMP,    # サンプリングとは無関係に開始
                                ccnt.CNTS_START_CNT_WITH_SAMP)        # サンプリングと同時に開始
        #----------------------------------------
        # 親ウィンドウの設定
        #----------------------------------------
        self.parent = parent
        #----------------------------------------
        # UIの作成を開始
        #----------------------------------------
        self.ui = SSamplingModeWindowUI(parent)
        #----------------------------------------
        # UIコントロールのコールバック関数を設定
        #----------------------------------------
        self.ui.setup_commands(
            command_select_stop_condition = self.OnSelendokComboStopTrg,
            command_m_sampling_mode_window_ok = self.OnOK,
            command_m_sampling_mode_window_cancel = self.OnClickedButtonCancel
        )
        #----------------------------------------
        # UIの更新を開始
        #----------------------------------------
        self._update_ui()

    #========================================
    # UIの更新関数
    #========================================
    def _update_ui(self):
        #----------------------------------------
        # ウィンドウ画面は最後に選択した設定に設定されます
        #----------------------------------------
        self.ui.combobox_start_condition.current(self.parent.s_sampling_mode_window_combobox_start_condition_last_selected)
        self.ui.combobox_stop_condition.current(self.parent.s_sampling_mode_window_combobox_stop_condition_last_selected)
        self.ui.combobox_clock_condition.current(self.parent.s_sampling_mode_window_combobox_clock_condition_last_selected)
        self.ui.textbox_stop_number_value_var.set(self.parent.s_sampling_mode_window_textbox_stop_number_value_last_edit)
        self.ui.combobox_start_with.current(self.parent.s_sampling_mode_window_combobox_start_with_last_selected)
        self.ui.combobox_stop_with.current(self.parent.s_sampling_mode_window_combobox_stop_with_last_selected)
        self.ui.textbox_transfer_event_var.set(self.parent.s_sampling_mode_window_textbox_transfer_event_last_edit)
        self.ui.radiobutton_transfer_type.set(self.parent.s_sampling_mode_window_radiobutton_transfer_type_last_selected)
        #----------------------------------------
        # コントロールの有効、無効を設定
        #----------------------------------------
        self.OnSelendokComboStopTrg()

    #========================================
    # 関数名    OnSelendokComboStopTrg
    # 引数      event    イベント(None固定)
    # 詳細      ストップ条件設定変更
    # 戻り値    なし
    #========================================
    def OnSelendokComboStopTrg(self, event=None):
        #----------------------------------------
        # コンボボックスからストップ条件を取得
        #----------------------------------------
        selected = self.ui.combobox_stop_condition.get()
        #----------------------------------------
        # ストップ条件による分岐処理
        #----------------------------------------
        if selected == "指定個数転送完了":
            self.ui.textbox_stop_number_value.config(state = 'normal')
        else:
            self.ui.textbox_stop_number_value.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

    #========================================
    # 関数名    OnOK()
    # 引数      なし
    # 詳細      設定完了処理
    # 戻り値    なし
    #========================================
    def OnOK(self):
        error_string = ctypes.create_string_buffer(256)    # エラーコード文字列
        lret = ctypes.c_long()                             # 戻り値取得用
        start_trg = ctypes.c_short()                       # 開始トリガー
        clock_trg = ctypes.c_short()                       # クロックトリガー
        stop_trg = ctypes.c_short()                        # 停止トリガー
        start_count_mode = ctypes.c_short()                # 開始モード
        stop_count_mode = ctypes.c_short()                 # 停止モード
        stop_number = ctypes.c_ulong()                     # サンプリング停止回数
        ext_sig1 = ctypes.c_short()                        # ExtSig1の信号線に出力する信号
        ext_sig2 = ctypes.c_short()                        # ExtSig2の信号線に出力する信号
        ext_sig3 = ctypes.c_short()                        # ExtSig3の信号線に出力する信号

        #----------------------------------------
        # 表示データを取得
        #----------------------------------------
        start_trg.value = self.start_trg_table[self.ui.combobox_start_condition.current()]
        clock_trg.value = self.clock_trg_table[self.ui.combobox_clock_condition.current()]
        stop_trg.value = self.stop_trg_table[self.ui.combobox_stop_condition.current()]
        start_count_mode.value = self.start_with[self.ui.combobox_start_with.current()]
        stop_count_mode.value = self.stop_with[self.ui.combobox_stop_with.current()]
        if self.ui.radiobutton_transfer_type.get() == 1:
            self.parent.s_is_ring = ccnt.CNTS_WRITE_ONCE
        else:
            self.parent.s_is_ring = ccnt.CNTS_WRITE_RING
        #--------------------
        # サンプリング停止回数を取得
        #--------------------
        buf = self.ui.textbox_stop_number_value_var.get()
        #--------------------
        # 入力値が数値かどうかをチェック
        #--------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "入力値が無効です。")
            return
        else:
            stop_number = ctypes.c_ulong(int(buf, 10))
        #--------------------
        # 通知を行うサンプリング回数を取得
        #--------------------
        buf = self.ui.textbox_transfer_event_var.get()
        #--------------------
        # 入力値が数値かどうかをチェック
        #--------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "入力値が無効です。")
            return
        else:
            self.parent.number_of_data = ctypes.c_long(int(buf, 10))
        #----------------------------------------
        # 画面の最後の設定値を記録
        #----------------------------------------
        self.parent.s_sampling_mode_window_combobox_start_condition_last_selected = self.ui.combobox_start_condition.current()
        self.parent.s_sampling_mode_window_combobox_stop_condition_last_selected = self.ui.combobox_stop_condition.current()
        self.parent.s_sampling_mode_window_combobox_clock_condition_last_selected = self.ui.combobox_clock_condition.current()
        self.parent.s_sampling_mode_window_textbox_stop_number_value_last_edit = self.ui.textbox_stop_number_value_var.get()
        self.parent.s_sampling_mode_window_combobox_start_with_last_selected = self.ui.combobox_start_with.current()
        self.parent.s_sampling_mode_window_combobox_stop_with_last_selected = self.ui.combobox_stop_with.current()
        self.parent.s_sampling_mode_window_textbox_transfer_event_last_edit = self.ui.textbox_transfer_event_var.get()
        self.parent.s_sampling_mode_window_radiobutton_transfer_type_last_selected = self.ui.radiobutton_transfer_type.get()
        #----------------------------------------
        # サンプリング条件を設定
        #----------------------------------------
        ext_sig1.value = ext_sig2.value = ext_sig3.value = 1
        #--------------------
        # スレーブ
        #--------------------
        lret.value = ccnt.CntSetSlave(self.parent.s_id, ext_sig1, ext_sig2, ext_sig3, 1, 1)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # メッセージ表示
            #----------------------------------------
            text_buf = f"CntSetSlave = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return
        #--------------------
        # スタート条件設定
        #--------------------
        lret.value = ccnt.CntSetSamplingStartTrigger(self.parent.s_id, start_trg, start_count_mode, self.CHANNEL_NUM)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # メッセージ表示
            #----------------------------------------
            text_buf = f"CntSetSamplingStartTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return
        #--------------------
        # クロック条件設定
        #--------------------
        lret.value = ccnt.CntSetSamplingClockTrigger(self.parent.s_id, clock_trg)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # メッセージ表示
            #----------------------------------------
            text_buf = f"CntSetSamplingClockTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return
        #--------------------
        # ストップ条件設定
        #--------------------
        lret.value = ccnt.CntSetSamplingStopTrigger(self.parent.s_id, stop_trg, stop_count_mode, self.CHANNEL_NUM)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # メッセージ表示
            #----------------------------------------
            text_buf = f"CntSetSamplingStopTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_buf)
            return
        #--------------------
        # 停止個数設定
        #--------------------
        if stop_trg.value == ccnt.CNTS_STOP_NUM:
            lret.value = ccnt.CntSetSamplingStopNumber(self.parent.s_id, stop_number)
            if lret.value != ccnt.CNT_ERR_SUCCESS:
                ccnt.CntGetErrorString(lret, error_string)
                #----------------------------------------
                # メッセージ表示
                #----------------------------------------
                text_buf = f"CntSetSamplingStopNumber = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_buf)
                return
        #----------------------------------------
        # ウィンドウを終了する
        #----------------------------------------
        self.ui.s_sampling_mode_window.destroy()

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