#================================================================
#================================================================
# API-AIO(WDM)
# カウンタサンプル
# カウンタ設定ファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ctypes.wintypes
import caio
from CommonFunction import *
#----------------------------------------
# グローバル変数
#----------------------------------------
g_cnt_channel = ctypes.c_short()                                  # カウンタのチャネル番号
g_cnt_mode_comparison_number = ctypes.c_long()                    # 設定する比較カウントデータの総数
g_cnt_mode_comparison_data_type = ctypes.c_long * 8               # 配列タイプを作成(比較カウント値)
g_cnt_mode_comparison_data = g_cnt_mode_comparison_data_type()    # 比較カウント値
g_cnt_mode_comparison_repeat = ctypes.c_short()                   # 比較カウント値データ配列の繰り返し設定
g_cnt_mode_preset_number = ctypes.c_long()                        # 設定するプリセットデータの総数
g_cnt_mode_preset_data_type = ctypes.c_long * 8                   # 配列タイプを作成(カウンタのプリセット値)
g_cnt_mode_preset_data = g_cnt_mode_preset_data_type()            # カウンタのプリセット値
g_cnt_mode_preset_repeat = ctypes.c_short()                       # プリセットデータ配列の繰り返し設定


#========================================
# 関数名    CounterSetting
# 引数      id    AioInitで取得したid
# 詳細      カウンタ設定メニューの表示と処理を行う関数になります
# 戻り値    なし
#========================================
def CounterSetting(id):
    error_buf = ctypes.create_string_buffer(256)    # エラーコード文字列
    lret = ctypes.c_long()                          # 戻り値取得用
    cnt_mode = ctypes.c_short()                     # 比較カウント一致が発生したときのカウンタの動作
    cnt_mode_comparison = ctypes.c_short()          # 比較カウント値のロード
    cnt_mode_preset = ctypes.c_short()              # プリセットカウント値のロード
    cnt_mode_comparison_data_string = []            # 比較カウント文字列配列
    cnt_mode_preset_data_string = []                # カウンタのプリセット文字列配列
    global g_cnt_channel                            # カウンタのチャネル番号
    global g_cnt_mode_comparison_number             # 設定する比較カウントデータの総数
    global g_cnt_mode_comparison_data               # 比較カウント値
    global g_cnt_mode_comparison_repeat             # 比較カウント値データ配列の繰り返し設定
    global g_cnt_mode_preset_number                 # 設定するプリセットデータの総数
    global g_cnt_mode_preset_data                   # カウンタのプリセット値
    global g_cnt_mode_preset_repeat                 # プリセットデータ配列の繰り返し設定
    global g_lock                                   # ミューテックス
    global g_info_flag                              # コールバックで比較一致回数、カウント値、ステータスが表示されているフラグ

    #----------------------------------------
    # 入力待ちループ
    #----------------------------------------
    while True:
        #----------------------------------------
        # 設定パラメータの取得
        #----------------------------------------
        #--------------------
        # 比較カウント一致が発生したときのカウンタの動作を取得
        #--------------------
        lret.value = caio.AioGetCntComparisonMode(id, g_cnt_channel, ctypes.byref(cnt_mode))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            print("カウンタ設定 エラー")
            print(f"AioGetCntComparisonMode Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            return
        else:
            if (cnt_mode.value & caio.CNT_LOADCOMP) == caio.CNT_LOADCOMP:
                cnt_mode_comparison.value = 1
                cnt_mode_comparison_string = "1 (有効)"
            else:
                cnt_mode_comparison.value = 0
                cnt_mode_comparison_string = "0 (無効)"
            if (cnt_mode.value & caio.CNT_LOADPRESET) == caio.CNT_LOADPRESET:
                cnt_mode_preset.value = 1
                cnt_mode_preset_string = "1 (有効)"
            else:
                cnt_mode_preset.value = 0
                cnt_mode_preset_string = "0 (無効)"
        #--------------------
        # 比較カウント設定が有効の場合
        #--------------------
        if cnt_mode_comparison.value == 1:
            cnt_mode_comparison_number_string = f"{g_cnt_mode_comparison_number.value:d}"
            cnt_mode_comparison_data_string.clear()
            for i in range(0, g_cnt_mode_comparison_number.value):
                cnt_mode_comparison_data_string.append(f"{g_cnt_mode_comparison_data[i]:d}")
            cnt_mode_comparison_repeat_string = f"{g_cnt_mode_comparison_repeat.value:d}"
        #--------------------
        # 比較一致プリセット設定が有効の場合
        #--------------------
        if cnt_mode_preset.value == 1:
            cnt_mode_preset_number_string = f"{g_cnt_mode_preset_number.value:d}"
            cnt_mode_preset_data_string.clear()
            for i in range(0, g_cnt_mode_preset_number.value):
                cnt_mode_preset_data_string.append(f"{g_cnt_mode_preset_data[i]:d}")
            cnt_mode_preset_repeat_string = f"{g_cnt_mode_preset_repeat.value:d}"
        #----------------------------------------
        # 設定パラメータの表示
        #----------------------------------------
        print("========================================")
        print("設定パラメータ")
        print("========================================")
        print(f"比較カウント設定          : {cnt_mode_comparison_string}")
        if cnt_mode_comparison.value == 1:
            print(f"  設定データ数            : {cnt_mode_comparison_number_string}")
            for i in range(0, g_cnt_mode_comparison_number.value):
                print(f"  比較カウント値[{i}]       : {cnt_mode_comparison_data_string[i]}")
            print(f"  繰り返し設定            : {cnt_mode_comparison_repeat_string}")
        print(f"比較一致プリセット設定    : {cnt_mode_preset_string}")
        if cnt_mode_preset.value == 1:
            print(f"  設定データ数            : {cnt_mode_preset_number_string}")
            for i in range(0, g_cnt_mode_preset_number.value):
                print(f"  プリセット値[{i}]         : {cnt_mode_preset_data_string[i]}")
            print(f"  繰り返し設定            : {cnt_mode_preset_repeat_string}")
        #----------------------------------------
        # コマンドの表示
        #----------------------------------------
        print("========================================")
        print("メニュー(トップ > カウンタ設定)")
        print("========================================")
        print("1 : 比較カウント設定")
        print("2 : 比較一致プリセット設定")
        print("b : 戻る")
        print("コマンドを入力してください : ", end='', flush=True)
        #----------------------------------------
        # ロック解除
        #----------------------------------------
        g_lock.release()
        #----------------------------------------
        # 入力待ち
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # ロック
        #----------------------------------------
        g_lock.acquire()
        #----------------------------------------
        # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
        #----------------------------------------
        if g_info_flag.value == 1:
            print("")
            g_info_flag.value = 0
        #----------------------------------------
        # コマンドの識別
        #----------------------------------------
        #--------------------
        # 比較カウント設定
        #--------------------
        if buf == "1":
            print("\n----------------------------------------")
            print("比較カウント設定を開始します")
            print("----------------------------------------")
            #----------------------------------------
            # 比較カウント設定の無効／有効を入力
            #----------------------------------------
            print("----------------------------------------")
            print("パラメータ(比較カウント設定の無効/有効)")
            print("----------------------------------------")
            print("0 : 無効")
            print("1 : 有効")
            while True:
                print("比較カウント設定の無効／有効を入力してください : ", end='', flush=True)
                #----------------------------------------
                # ロック解除
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # ロック
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                #----------------------------------------
                # 範囲判断
                #----------------------------------------
                if int(buf) >= 0 and int(buf) <= 1:
                    break
            cnt_mode_comparison = ctypes.c_short(int(buf))
            #----------------------------------------
            # 比較カウント設定の無効／有効設定
            #----------------------------------------
            if cnt_mode_comparison.value == 0:
                cnt_mode.value = cnt_mode.value & (~caio.CNT_LOADCOMP)
            elif cnt_mode_comparison.value == 1:
                cnt_mode.value = cnt_mode.value | caio.CNT_LOADCOMP
            lret.value = caio.AioSetCntComparisonMode(id, g_cnt_channel, cnt_mode)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                #----------------------------------------
                # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                print("\n比較カウント設定 エラー")
                print(f"AioSetCntComparisonMode Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # 比較カウント設定が有効の場合
            #----------------------------------------
            if cnt_mode_comparison.value == 1:
                #----------------------------------------
                # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # 設定データ数を入力
                #----------------------------------------
                print("")
                while True:
                    print("設定データ数を入力してください(1～5) : ", end='', flush=True)
                    #----------------------------------------
                    # ロック解除
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # 入力待ち
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # ロック
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    #----------------------------------------
                    # 入力値が数値かとうかをチェック
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    #----------------------------------------
                    # 範囲判断
                    #----------------------------------------
                    if int(buf) >= 1 and int(buf) <= 5:
                        break
                g_cnt_mode_comparison_number.value = int(buf)
                #----------------------------------------
                # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # 比較カウント値を入力
                #----------------------------------------
                print("")
                print("比較カウント値を入力してください")
                for i in range(0, g_cnt_mode_comparison_number.value):
                    while True:
                        print(f"比較カウント値[{i}] : ", end='', flush=True)
                        #----------------------------------------
                        # ロック解除
                        #----------------------------------------
                        g_lock.release()
                        #----------------------------------------
                        # 入力待ち
                        #----------------------------------------
                        buf = input()
                        #----------------------------------------
                        # ロック
                        #----------------------------------------
                        g_lock.acquire()
                        #----------------------------------------
                        # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                        #----------------------------------------
                        if g_info_flag.value == 1:
                            print("")
                            g_info_flag.value = 0
                        #----------------------------------------
                        # 入力値が数値かとうかをチェック
                        #----------------------------------------
                        if False == isnum(buf, 10):
                           continue
                        break
                    g_cnt_mode_comparison_data[i] = int(buf)
                #----------------------------------------
                # 繰り返し設定を入力
                #----------------------------------------
                print("\n----------------------------------------")
                print("パラメータ(繰り返し設定)")
                print("----------------------------------------")
                print("0 : 繰り返し設定なし")
                print("1 : 繰り返し設定あり")
                while True:
                    print(f"繰り返し設定を入力してください : ", end='', flush=True)
                    #----------------------------------------
                    # ロック解除
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # 入力待ち
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # ロック
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    #----------------------------------------
                    # 入力値が数値かとうかをチェック
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    #----------------------------------------
                    # 範囲判断
                    #----------------------------------------
                    if int(buf) >= 0 and int(buf) <= 1:
                        break
                g_cnt_mode_comparison_repeat.value = int(buf)
                #----------------------------------------
                # 比較カウント一致後にロードされる次回の比較カウント値設定
                #----------------------------------------
                lret.value = caio.AioSetCntComparisonReg(id, g_cnt_channel, g_cnt_mode_comparison_number, g_cnt_mode_comparison_data, g_cnt_mode_comparison_repeat)
                if lret.value != 0:
                    caio.AioGetErrorString(lret, error_buf)
                    #----------------------------------------
                    # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    print("\n比較カウント設定 エラー")
                    print(f"AioSetCntComparisonReg Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
            #----------------------------------------
            # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
            #----------------------------------------
            if g_info_flag.value == 1:
                print("")
                g_info_flag.value = 0
            print("\n比較カウント設定 正常終了\n")
        #--------------------
        # 比較一致プリセット設定
        #--------------------
        elif buf == "2":
            print("\n----------------------------------------")
            print("比較一致プリセット設定を開始します")
            print("----------------------------------------")
            #----------------------------------------
            # 比較一致プリセット設定の無効／有効を入力
            #----------------------------------------
            print("----------------------------------------")
            print("パラメータ(比較一致プリセット設定の無効/有効)")
            print("----------------------------------------")
            print("0 : 無効")
            print("1 : 有効")
            while True:
                print("比較一致プリセット設定の無効／有効を入力してください : ", end='', flush=True)
                #----------------------------------------
                # ロック解除
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # ロック
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                #----------------------------------------
                # 範囲判断
                #----------------------------------------
                if int(buf) >= 0 and int(buf) <= 1:
                    break
            cnt_mode_preset = ctypes.c_short(int(buf))
            #----------------------------------------
            # 比較一致プリセット設定の無効／有効設定
            #----------------------------------------
            if cnt_mode_preset.value == 0:
                cnt_mode.value = cnt_mode.value & (~caio.CNT_LOADPRESET)
            elif cnt_mode_preset.value == 1:
                cnt_mode.value = cnt_mode.value | caio.CNT_LOADPRESET
            lret.value = caio.AioSetCntComparisonMode(id, g_cnt_channel, cnt_mode)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                #----------------------------------------
                # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                print("\n比較一致プリセット設定 エラー")
                print(f"AioSetCntComparisonMode Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # 比較一致プリセット設定が有効の場合
            #----------------------------------------
            if cnt_mode_preset.value == 1:
                #----------------------------------------
                # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # 設定データ数を入力
                #----------------------------------------
                print("")
                while True:
                    print("設定データ数を入力してください(1～5) : ", end='', flush=True)
                    #----------------------------------------
                    # ロック解除
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # 入力待ち
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # ロック
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    #----------------------------------------
                    # 入力値が数値かとうかをチェック
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    #----------------------------------------
                    # 範囲判断
                    #----------------------------------------
                    if int(buf) >= 1 and int(buf) <= 5:
                        break
                g_cnt_mode_preset_number.value = int(buf)
                #----------------------------------------
                # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # プリセット値を入力
                #----------------------------------------
                print("")
                print("プリセット値を入力してください")
                for i in range(0, g_cnt_mode_preset_number.value):
                    while True:
                        print(f"プリセット値[{i}] : ", end='', flush=True)
                        #----------------------------------------
                        # ロック解除
                        #----------------------------------------
                        g_lock.release()
                        #----------------------------------------
                        # 入力待ち
                        #----------------------------------------
                        buf = input()
                        #----------------------------------------
                        # ロック
                        #----------------------------------------
                        g_lock.acquire()
                        #----------------------------------------
                        # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                        #----------------------------------------
                        if g_info_flag.value == 1:
                            print("")
                            g_info_flag.value = 0
                        #----------------------------------------
                        # 入力値が数値かとうかをチェック
                        #----------------------------------------
                        if False == isnum(buf, 10):
                            continue
                        break
                    g_cnt_mode_preset_data[i] = int(buf)
                #----------------------------------------
                # 繰り返し設定を入力
                #----------------------------------------
                print("\n----------------------------------------")
                print("パラメータ(繰り返し設定)")
                print("----------------------------------------")
                print("0 : 繰り返し設定なし")
                print("1 : 繰り返し設定あり")
                while True:
                    print(f"繰り返し設定を入力してください : ", end='', flush=True)
                    #----------------------------------------
                    # ロック解除
                    #----------------------------------------
                    g_lock.release()
                    #----------------------------------------
                    # 入力待ち
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # ロック
                    #----------------------------------------
                    g_lock.acquire()
                    #----------------------------------------
                    # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    #----------------------------------------
                    # 入力値が数値かとうかをチェック
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    #----------------------------------------
                    # 範囲判断
                    #----------------------------------------
                    if int(buf) >= 0 and int(buf) <= 1:
                        break
                g_cnt_mode_preset_repeat.value = int(buf)
                #----------------------------------------
                # 比較カウント一致後にロードされるプリセット値を設定
                #----------------------------------------
                lret.value = caio.AioSetCntPresetReg(id, g_cnt_channel, g_cnt_mode_preset_number, g_cnt_mode_preset_data, g_cnt_mode_preset_repeat)
                if lret.value != 0:
                    caio.AioGetErrorString(lret, error_buf)
                    #----------------------------------------
                    # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("")
                        g_info_flag.value = 0
                    print("\n比較一致プリセット設定エラー")
                    print(f"AioSetCntPresetReg Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
            print("\n比較一致プリセット設定 正常終了\n")
        #--------------------
        # 戻る
        #--------------------
        elif buf == "b":
            print("")
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\n範囲外の番号になります。\nもう一度入力してください。\n")
            continue