#================================================================
#================================================================
# API-AIO(WDM)
# カウンタサンプル
# mainファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import caio
from CommonFunction import *
from CounterSetting import *
#----------------------------------------
# グローバル変数
#----------------------------------------
g_cnt_event_count = ctypes.c_long()    # 比較カウント一致イベント発生回数


#========================================
# 関数名    CallBackProc
# 引数      id           AioInitで取得したid
# 引数      cnt_event    発生したイベント
# 引数      wParam       ドライバから渡されるパラメータ
# 引数      lParam       イベントごとに固有のパラメータ
# 引数      Param        AioSetCntCallBackProc関数に指定されたパラメータ
# 詳細      AioSetCntCallBackProc関数で登録する関数になります
#          イベントが発生すると本関数が呼び出されます
# 戻り値    なし
#========================================
def CallBackProc(id, cnt_event, wParam, lParam, Param):
    error_buf = ctypes.create_string_buffer(256)    # エラーコード文字列
    lret = ctypes.c_long()                          # 戻り値取得用
    cnt_channel = ctypes.c_short()                  # カウンタのチャネル番号
    cnt_count = ctypes.c_long()                     # 現在のカウント値
    cnt_status = ctypes.c_long()                    # ステータス
    global g_cnt_channel                            # カウンタのチャネル番号
    global g_cnt_event_count                        # 比較カウント一致イベント発生回数

    #----------------------------------------
    # 比較カウント一致イベントの場合
    #----------------------------------------
    if cnt_event == caio.AIOM_CNTE_DATA_NUM:
        #----------------------------------------
        # カウンタチャネルの取得
        #----------------------------------------
        cnt_channel = ctypes.c_short(wParam)
        if cnt_channel.value == g_cnt_channel.value:
            #----------------------------------------
            # カウント値の取得
            #----------------------------------------
            lret.value = caio.AioGetCntCount(id, cnt_channel, ctypes.byref(cnt_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\n比較カウント一致イベント処理 : AioGetCntCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # ステータス取得
            #----------------------------------------
            lret.value = caio.AioGetCntStatus(id, cnt_channel, ctypes.byref(cnt_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\n比較カウント一致イベント処理 : AioGetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # ステータス文字例の作成
            #----------------------------------------
            cnt_status_string = GetStatusString(cnt_status)
            #----------------------------------------
            # 比較カウント一致イベント発生回数をインクリメント
            #----------------------------------------
            g_cnt_event_count.value += 1
            #----------------------------------------
            # ステータスリセット
            #----------------------------------------
            lret.value = caio.AioResetCntStatus(id, cnt_channel, caio.CNTS_DATA_NUM)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\n比較カウント一致イベント処理 : AioResetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # 比較一致回数、カウント値、ステータスを表示
            #----------------------------------------
            text_buf = f"\n比較一致回数 = {g_cnt_event_count.value:<8d} カウント値 = {cnt_count.value:<8d} ステータス = 0x{cnt_status.value:08x}({cnt_status_string:})"
            PrintOnOneLine(text_buf)
    #----------------------------------------
    # カウンタ動作エラーイベントの場合
    #----------------------------------------
    elif cnt_event == caio.AIOM_CNTE_ERR:
        #----------------------------------------
        # カウンタチャネルの取得
        #----------------------------------------
        cnt_channel = ctypes.c_short(wParam)
        if cnt_channel.value == g_cnt_channel.value:
            #----------------------------------------
            # カウント値の取得
            #----------------------------------------
            lret.value = caio.AioGetCntCount(id, cnt_channel, ctypes.byref(cnt_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\nカウンタ動作エラーイベント処理 : AioGetCntCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # ステータス取得
            #----------------------------------------
            lret.value = caio.AioGetCntStatus(id, cnt_channel, ctypes.byref(cnt_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                text_buf = f"\nカウンタ動作エラーイベント処理 : AioGetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
                PrintOnOneLine(text_buf)
                return
            #----------------------------------------
            # ステータス文字例の作成
            #----------------------------------------
            cnt_status_string = GetStatusString(cnt_status)
            #----------------------------------------
            # 比較一致回数、カウント値、ステータスを表示
            #----------------------------------------
            text_buf = f"\n比較一致回数 = {g_cnt_event_count.value:<8d} カウント値 = {cnt_count.value:<8d} ステータス = 0x{cnt_status.value:08x}({cnt_status_string:})"
            PrintOnOneLine(text_buf)
    return

pcnt_callback = caio.PAIO_CNT_CALLBACK(CallBackProc)


#========================================
# 関数名    main
# 引数      なし
# 詳細      main処理を行う関数になります
# 戻り値    なし
#========================================
def main():
    error_buf = ctypes.create_string_buffer(256)    # エラーコード文字列
    lret = ctypes.c_long()                          # 戻り値取得用
    id = ctypes.c_short()                           # デバイスアクセス用ID
    cnt_preset_data = ctypes.c_long()               # カウンタのプリセット値
    cnt_count = ctypes.c_long()                     # 現在のカウント値
    cnt_status = ctypes.c_long()                    # ステータス
    cnt_max_channels = ctypes.c_short()             # カウンタチャネル数の最大値
    initialized = 0                                 # ボードが初期化されているかどうか
    global g_cnt_channel                            # カウンタのチャネル番号
    global g_cnt_event_count                        # 比較カウント一致イベント発生回数
    global g_lock                                   # ミューテックス
    global g_info_flag                              # コールバックで比較一致回数、カウント値、ステータスが表示されているフラグ

    #----------------------------------------
    # 変数を初期化
    #----------------------------------------
    g_info_flag.value = 0
    #----------------------------------------
    # ロック
    #----------------------------------------
    g_lock.acquire()
    #----------------------------------------
    # 入力待ちループ
    #----------------------------------------
    while True:
        #----------------------------------------
        # 設定パラメータの取得
        #----------------------------------------
        #--------------------
        # カウンタチャネル番号を取得
        #--------------------
        if initialized == 0:
            cnt_channel_string = "-"
        else:
            cnt_channel_string = f"{g_cnt_channel.value:d}"
        #----------------------------------------
        # 設定パラメータの表示
        #----------------------------------------
        print("========================================")
        print("設定パラメータ")
        print("========================================")
        print(f"カウンタチャネル番号 : {cnt_channel_string}")
        #----------------------------------------
        # コマンドの表示
        #----------------------------------------
        print("========================================")
        print("メニュー(トップ)")
        print("========================================")
        print(" 1 : AioInit")
        print(" 2 : AioResetDevice")
        print(" 3 : カウンタチャンネル番号設定")
        print(" 4 : カウンタ設定")
        print(" 5 : AioPresetCnt")
        print(" 6 : カウント開始")
        print(" 7 : AioGetCntCount")
        print(" 8 : AioGetCntStatus")
        print(" 9 : カウント停止")
        print("10 : AioExit")
        print(" q : 終了")
        print("コマンドを入力してください : ", end='', flush=True)
        #----------------------------------------
        # ロック解除
        #----------------------------------------
        g_lock.release()
        #----------------------------------------
        # 入力待ち
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # ロック
        #----------------------------------------
        g_lock.acquire()
        #----------------------------------------
        # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
        #----------------------------------------
        if g_info_flag.value == 1:
            print("")
            g_info_flag.value = 0
        #----------------------------------------
        # コマンドの識別
        #----------------------------------------
        #--------------------
        # AioInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # デバイス名を入力
            #----------------------------------------
            print("\nデバイス名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # ロック解除
            #----------------------------------------
            g_lock.release()
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # ロック
            #----------------------------------------
            g_lock.acquire()
            #----------------------------------------
            # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
            #----------------------------------------
            if g_info_flag.value == 1:
                print("")
                g_info_flag.value = 0
            #----------------------------------------
            # 初期化
            #----------------------------------------
            lret.value = caio.AioInit(buf.encode(), ctypes.byref(id))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioInit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            #----------------------------------------
            # 初期化済み設定
            #----------------------------------------
            if lret.value == 0:
                initialized = 1
            else:
                initialized = 0
        #--------------------
        # AioResetDevice
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # リセットデバイス
            #----------------------------------------
            lret.value = caio.AioResetDevice(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioResetDevice Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # カウンタチャンネル番号設定
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # カウンタチャネル数の最大値の取得
            #----------------------------------------
            lret.value = caio.AioGetCntMaxChannels(id, ctypes.byref(cnt_max_channels))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nカウンタチャネル番号設定 エラー")
                print(f"AioGetCntMaxChannels Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # カウンタチャネル番号を入力
            #----------------------------------------
            print("")
            while True:
                print(f"カウンタチャネル番号を入力してください(0～{cnt_max_channels.value - 1}) : ", 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) < cnt_max_channels.value:
                    break
            g_cnt_channel.value = int(buf)
            #----------------------------------------
            # コールバックで比較一致回数、カウント値、ステータスが表示されている場合、改行を出力
            #----------------------------------------
            if g_info_flag.value == 1:
                print("")
                g_info_flag.value = 0
            #----------------------------------------
            # カウンタチャネル番号設定
            #----------------------------------------
            print("\nカウンタチャネル番号設定 正常終了")
            print(f"カウンタチャネル番号 = {g_cnt_channel.value}\n")
        #--------------------
        # カウンタ設定
        #--------------------
        elif buf == "4":
            print("")
            #----------------------------------------
            # カウンタ設定メニュー表示
            #----------------------------------------
            CounterSetting(id)
        #--------------------
        # AioPresetCnt
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # プリセット値を入力
            #----------------------------------------
            print("")
            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
                break
            cnt_preset_data = ctypes.c_long(int(buf))
            #----------------------------------------
            # プリセット値設定
            #----------------------------------------
            lret.value = caio.AioPresetCnt(id, g_cnt_channel, cnt_preset_data)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioPresetCnt Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"プリセット値 = {cnt_preset_data.value}")
            print("")
        #--------------------
        # カウント開始
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # イベント要因の設定：比較カウント一致イベント、カウンタ動作エラーイベント
            #----------------------------------------
            lret.value = caio.AioSetCntCallBackProc(id, g_cnt_channel, pcnt_callback, caio.CNTE_DATA_NUM | caio.CNTE_ERR, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nカウント開始 エラー")
                print(f"AioSetCntCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # カウンタステータスクリア
            #----------------------------------------
            lret.value = caio.AioResetCntStatus(id, g_cnt_channel, caio.CNTE_DATA_NUM | caio.CNTS_ORERR)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nカウント開始 エラー")
                print(f"AioResetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # 比較一致回数を初期化
            #----------------------------------------
            g_cnt_event_count.value = 0
            #----------------------------------------
            # カウント開始
            #----------------------------------------
            lret.value = caio.AioStartCnt(id, g_cnt_channel)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nカウント開始 エラー")
                print(f"AioStartCnt Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # カウント開始完了
            #----------------------------------------
            print("\nカウント開始 正常終了\n")
        #--------------------
        # AioGetCntCount
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # 現在のカウント値取得
            #----------------------------------------
            lret.value = caio.AioGetCntCount(id, g_cnt_channel, ctypes.byref(cnt_count))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetCntCount Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"カウント値 = {cnt_count.value}")
            print("")
        #--------------------
        # AioGetCntStatus
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # カウンタのステータス取得
            #----------------------------------------
            lret.value = caio.AioGetCntStatus(id, g_cnt_channel, ctypes.byref(cnt_status))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetCntStatus Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                #----------------------------------------
                # ステータス文字例の作成
                #----------------------------------------
                cnt_status_string = GetStatusString(cnt_status)
                print(f"ステータス = 0x{cnt_status.value:08x}({cnt_status_string})")
            print("")
        #--------------------
        # カウント停止
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # カウント停止
            #----------------------------------------
            lret.value = caio.AioStopCnt(id, g_cnt_channel)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nカウント停止 エラー")
                print(f"AioStopCnt Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # カウント停止完了
            #----------------------------------------
            print("\nカウント停止 正常終了\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # 終了処理
            #----------------------------------------
            lret.value = caio.AioExit(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            #----------------------------------------
            # 初期化済み設定
            #----------------------------------------
            if lret.value == 0:
                initialized = 0
        #--------------------
        # 終了
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\n範囲外の番号になります。\nもう一度入力してください。\n")
            continue
    #----------------------------------------
    # 終了処理
    #----------------------------------------
    caio.AioExit(id)
    #----------------------------------------
    # ロック解除
    #----------------------------------------
    g_lock.release()
    #----------------------------------------
    # アプリケーション終了
    #----------------------------------------
    sys.exit()


#----------------------------------------
# main関数呼び出し
#----------------------------------------
if __name__ == "__main__":
    main()