#================================================================
#================================================================
# API-AIO(WDM)
# アナログ簡易入力サンプル
# mainファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import caio
from CommonFunction import *


#========================================
# 関数名    main
# 引数      なし
# 詳細      main処理を行う関数になります
# 戻り値    なし
#========================================
def main():
    error_buf = ctypes.create_string_buffer(256)    # エラーコード文字列
    lret = ctypes.c_long()                          # 戻り値取得用
    id = ctypes.c_short()                           # デバイスアクセス用ID
    ai_range = ctypes.c_short()                     # レンジ
    ai_input_method = ctypes.c_short()              # 入力方式
    ai_channel = ctypes.c_short()                   # チャネル番号
    ai_data_single = ctypes.c_float()               # 指定チャネル入力データ
    ai_channels = ctypes.c_short()                  # チャネル数
    ai_data_multi_type = ctypes.c_float * 256       # 配列タイプを作成(複数チャネル入力データ)
    ai_data_multi = ai_data_multi_type()            # 複数チャネル入力データ

    #----------------------------------------
    # 入力待ちループ
    #----------------------------------------
    while True:
        #----------------------------------------
        # 設定パラメータの取得
        #----------------------------------------
        #--------------------
        # レンジ値を取得
        #--------------------
        lret.value = caio.AioGetAiRange(id, 0, ctypes.byref(ai_range))
        if lret.value != 0:
            ai_range_string = "-"
        else:
            ai_range_string = GetRangeString(ai_range)
        #--------------------
        # 入力方式を取得
        #--------------------
        lret.value = caio.AioGetAiInputMethod(id, ctypes.byref(ai_input_method))
        if lret.value != 0:
            ai_input_method_string = "-"
        else:
            ai_input_method_string = GetInputMethodString(ai_input_method)
        #----------------------------------------
        # 設定パラメータの表示
        #----------------------------------------
        print("========================================")
        print("設定パラメータ")
        print("========================================")
        print(f"レンジ   : {ai_range_string}")
        print(f"入力方式 : {ai_input_method_string}")
        #----------------------------------------
        # コマンドの表示
        #----------------------------------------
        print("========================================")
        print("メニュー")
        print("========================================")
        print("1 : AioInit")
        print("2 : AioSetAiRangeAll")
        print("3 : AioSetAiInputMethod")
        print("4 : AioSingleAiEx")
        print("5 : AioMultiAiEx")
        print("6 : AioExit")
        print("q : 終了")
        print("コマンドを入力してください : ", end='', flush=True)
        #----------------------------------------
        # 入力待ち
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # コマンドの識別
        #----------------------------------------
        #--------------------
        # AioInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # デバイス名を入力
            #----------------------------------------
            print("\nデバイス名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # 初期化
            #----------------------------------------
            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")
        #--------------------
        # AioSetAiRangeAll
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # レンジを入力
            #----------------------------------------
            print("\n----------------------------------------")
            print("パラメータ(レンジ)")
            print("----------------------------------------")
            print(" 0 : ±10[V]\t\t 50 : 0-10[V]")
            print(" 1 : ±5[V]\t\t 51 : 0-5[V]")
            print(" 2 : ±2.5[V]\t\t 53 : 0-2.5[V]")
            print(" 3 : ±1.25[V]\t\t 54 : 0-1.25[V]")
            print("             \t\t100 : 0-20[mA]")
            print("             \t\t101 : 4-20[mA]")
            print("             \t\t102 : ±20[mA]")
            print("             \t\t150 : 1-5[V]")
            while True:
                print("レンジを入力してください : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ai_range = ctypes.c_short(int(buf))
            #----------------------------------------
            # レンジ設定
            #----------------------------------------
            lret.value = caio.AioSetAiRangeAll(id, ai_range)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiRangeAll Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                ai_range_string = GetRangeString(ai_range)
                print(f"レンジ = {ai_range.value}({ai_range_string})")
            print("")
        #--------------------
        # AioSetAiInputMethod
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # 入力方式を入力
            #----------------------------------------
            print("\n----------------------------------------")
            print("パラメータ(入力方式)")
            print("----------------------------------------")
            print("0 : シングルエンド入力")
            print("1 : 差動入力")
            while True:
                print("入力方式を入力してください : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ai_input_method = ctypes.c_short(int(buf))
            #----------------------------------------
            # 入力方式設定
            #----------------------------------------
            lret.value = caio.AioSetAiInputMethod(id, ai_input_method)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiInputMethod Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                ai_input_method_string = GetInputMethodString(ai_input_method)
                print(f"入力方式 = {ai_input_method.value}({ai_input_method_string})")
            print("")
        #--------------------
        # AioSingleAiEx
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # チャネル番号を入力
            #----------------------------------------
            print("")
            while True:
                print("チャネル番号を入力してください : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ai_channel = ctypes.c_short(int(buf))
            #----------------------------------------
            # 指定チャネルを1回アナログ入力
            #----------------------------------------
            lret.value = caio.AioSingleAiEx(id, ai_channel, ctypes.byref(ai_data_single))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSingleAiEx Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                if (ai_range.value == caio.P20MA) or (ai_range.value == caio.P4TO20MA) or (ai_range.value == caio.PM20MA):
                    print(f"チャネル{ai_channel.value:<3d} 入力データ = {ai_data_single.value:2.5f}[mA]")
                else:
                    print(f"チャネル{ai_channel.value:<3d} 入力データ = {ai_data_single.value:2.5f}[V]")
            print("")
        #--------------------
        # AioMultiAiEx
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # チャネル数を入力
            #----------------------------------------
            print("")
            while True:
                print("チャネル数を入力してください : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ai_channels = ctypes.c_short(int(buf))
            #----------------------------------------
            # 複数チャネルを1回アナログ入力
            #----------------------------------------
            lret.value = caio.AioMultiAiEx(id, ai_channels, ai_data_multi)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioMultiAiEx Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                if (ai_range.value == caio.P20MA) or (ai_range.value == caio.P4TO20MA) or (ai_range.value == caio.PM20MA):
                    for i in range(0, ai_channels.value):
                        print(f"チャネル{i:<3d} 入力データ = {ai_data_multi[i]:2.5f}[mA]")
                else:
                    for i in range(0, ai_channels.value):
                        print(f"チャネル{i:<3d} 入力データ = {ai_data_multi[i]:2.5f}[V]")
            print("")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # 終了処理
            #----------------------------------------
            lret.value = caio.AioExit(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # 終了
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\n範囲外の番号になります。\nもう一度入力してください。\n")
            continue
    #----------------------------------------
    # 終了処理
    #----------------------------------------
    caio.AioExit(id)
    #----------------------------------------
    # アプリケーション終了
    #----------------------------------------
    sys.exit()


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