#================================================================
#================================================================
# C-WaveformGenerator
# Fileサンプル
# mainファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import cgen_api
from CommonFunction import *


#========================================
# 関数名    main
# 引数      なし
# 詳細      main処理を行う関数になります
# 戻り値    なし
#========================================
def main():
    device_name = ctypes.create_string_buffer(256)    # デバイス名
    error_buf = ctypes.create_string_buffer(256)      # エラーコード文字列
    lret = ctypes.c_long()                            # 戻り値取得用
    appid = ctypes.c_short()                          # デバイスアクセス用ID
    open_mode = ctypes.c_ushort()                     # 画面サイズ
    file_path = ctypes.create_string_buffer(256)      # ファイルパス
    ao_channel = ctypes.c_ushort()                    # チャンネル番号
    wave_type = ctypes.c_ushort()                     # 波形タイプ
    param = ctypes.c_short()                          # パラメータ（単数or複数）
    status = ctypes.c_ulong()                         # ステータス


    #----------------------------------------
    # 入力待ちループ
    #----------------------------------------
    while True:
        #----------------------------------------
        # 設定パラメータの取得
        #----------------------------------------
        #--------------------
        # デバイス名を取得
        #--------------------
        lret.value = cgen_api.GenGetDeviceName(appid, device_name)
        if lret.value != 0:
            device_name_string = "-"
        else:
            device_name_string = device_name.value.decode('sjis')
        #----------------------------------------
        # 設定パラメータの表示
        #----------------------------------------
        print("========================================")
        print("設定パラメータ")
        print("========================================")
        print(f"デバイス名 : {device_name_string}")
        #----------------------------------------
        # コマンドの表示
        #----------------------------------------
        print("========================================")
        print("メニュー")
        print("========================================")
        print(" 1 : GenOpenApplication")
        print(" 2 : GenSetDeviceName")
        print(" 3 : GenExportSettingFile")
        print(" 4 : GenImportSettingFile")
        print(" 5 : GenSetWaveType")
        print(" 6 : GenSetArbitraryDataFile")
        print(" 7 : GenGetArbitraryDataFile")
        print(" 8 : GenSaveDataFile")
        print(" 9 : GenStartOperation")
        print("10 : GenGetApplicationStatus")
        print("11 : GenStopOperation")
        print("12 : GenCloseApplication")
        print(" q : 終了")
        print("コマンドを入力してください : ", end='', flush=True)
        #----------------------------------------
        # 入力待ち
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # コマンドの識別
        #----------------------------------------
        #--------------------
        # GenOpenApplication
        #--------------------
        if buf == "1":
            #----------------------------------------
            # デバイス名を入力
            #----------------------------------------
            print("\nデバイス名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            device_name.value = buf.encode()
            #----------------------------------------
            # 画面サイズを入力
            #----------------------------------------
            print("\n----------------------------------------")
            print("パラメータ(画面サイズ)")
            print("----------------------------------------")
            print("0 : 最小化")
            print("1 : 通常")
            print("2 : 最大化")
            while True:
                print("画面サイズを選択してください : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            open_mode = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # アプリの初期化処理を行う
            #----------------------------------------
            lret.value = cgen_api.GenOpenApplication(device_name, ctypes.byref(appid), open_mode)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenOpenApplication Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenSetDeviceName
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # デバイス名を入力
            #----------------------------------------
            print("\nデバイス名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            device_name.value = buf.encode()
            #----------------------------------------
            # デバイス名の設定
            #----------------------------------------
            lret.value = cgen_api.GenSetDeviceName(appid, device_name.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSetDeviceName Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenExportSettingFile
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # 設定ファイル名を入力
            #----------------------------------------
            print("\n設定ファイル名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            file_path.value = buf.encode()
            #----------------------------------------
            # 設定をiniファイルに保存
            #----------------------------------------
            lret.value = cgen_api.GenExportSettingFile(appid, file_path.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenExportSettingFile Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenImportSettingFile
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # 設定ファイル名を入力
            #----------------------------------------
            print("\n設定ファイル名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            file_path.value = buf.encode()
            #----------------------------------------
            # iniファイルの設定読み出しを行う
            #----------------------------------------
            lret.value = cgen_api.GenImportSettingFile(appid, file_path.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenImportSettingFile Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenSetWaveType
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # チャネル番号を入力
            #----------------------------------------
            print("")
            while True:
                print("チャネル番号を入力してください(0-15) : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # 波形タイプを入力
            #----------------------------------------
            print("\n----------------------------------------")
            print("パラメータ(波形タイプ)")
            print("----------------------------------------")
            print("0 : 正弦")
            print("1 : 固定")
            print("2 : 三角")
            print("3 : のこぎり")
            print("4 : 矩形")
            print("5 : ノイズ")
            print("6 : 任意")
            while True:
                print("波形タイプを選択してください : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            wave_type = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # 波形タイプの設定を行う
            #----------------------------------------
            lret.value = cgen_api.GenSetWaveType(appid, ao_channel, wave_type)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSetWaveType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenSetArbitraryDataFile
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # チャネル番号を入力
            #----------------------------------------
            print("")
            while True:
                print("チャネル番号を入力してください(0-15) : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # データファイル名を入力
            #----------------------------------------
            print("\nデータファイル名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            file_path.value = buf.encode()
            #----------------------------------------
            # データファイルパスの設定
            #----------------------------------------
            lret.value = cgen_api.GenSetArbitraryDataFile(appid, ao_channel, file_path.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSetArbitraryDataFile Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenGetArbitraryDataFile
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # チャネル番号を入力
            #----------------------------------------
            print("")
            while True:
                print("チャネル番号を入力してください(0-15) : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # データファイルパスの取得
            #----------------------------------------
            lret.value = cgen_api.GenGetArbitraryDataFile(appid, ao_channel, file_path.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenGetArbitraryDataFile Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"データファイル名 = {file_path.value.decode('sjis')}")
            print("")
        #--------------------
        # GenSaveDataFile
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # チャネル番号を入力
            #----------------------------------------
            print("")
            while True:
                print("チャネル番号を入力してください(0-15) : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # データファイル名を入力
            #----------------------------------------
            print("\nデータファイル名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            file_path.value = buf.encode()
            #----------------------------------------
            # 保存データ数を入力
            #----------------------------------------
            print("\n----------------------------------------")
            print("パラメータ(保存データ数)")
            print("----------------------------------------")
            print("0 : 単数")
            print("1 : 複数")
            while True:
                print("保存データ数を選択してください : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            param = ctypes.c_short(int(buf))
            #----------------------------------------
            # データファイルの設定
            #----------------------------------------
            #-------------------
            # 単数チャネルの場合、第4引数をチャネル番号にする
            #-------------------
            if param.value == 0:
                lret.value = cgen_api.GenSaveDataFile(appid, file_path.value, param, ctypes.c_short(ao_channel.value))
            #-------------------
            # 複数チャネルの場合、第4引数を0にする
            #-------------------
            else:
                lret.value = cgen_api.GenSaveDataFile(appid, file_path.value, param, 0)
            #----------------------------------------
            # エラー文字列取得
            #----------------------------------------
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSaveDataFile Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenStartOperation
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # アプリの出力開始を行う
            #----------------------------------------
            lret.value = cgen_api.GenStartOperation(appid)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenStartOperation Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenGetApplicationStatus
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # 動作状況の取得を行う
            #----------------------------------------
            lret.value = cgen_api.GenGetApplicationStatus(appid, ctypes.byref(status))
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenGetApplicationStatus Ret = {lret.value} {error_buf.value.decode('sjis')}")
            #----------------------------------------
            # ステータスを表示
            #----------------------------------------
            if status.value == 0:
                status_string = "00H(停止中)"
            elif status.value == 1:
                status_string = "01H(動作中)"
            elif status.value == 2:
                status_string = "02H(開始トリガ待ち)"
            elif status.value == 3:
                status_string = "03H(動作中、開始トリガ待ち)"
            else:
                status_string = f"{status.value}"
            print(f"ステータス = {status_string}\n")
        #--------------------
        # GenStopOperation
        #--------------------
        elif buf == "11":
            #----------------------------------------
            # アプリの出力停止を行う
            #----------------------------------------
            lret.value = cgen_api.GenStopOperation(appid)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenStopOperation Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenCloseApplication
        #--------------------
        elif buf == "12":
            #----------------------------------------
            # デバイスの終了処理を行う
            #----------------------------------------
            lret.value = cgen_api.GenCloseApplication(appid, ctypes.byref(status))
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenCloseApplication Ret = {lret.value} {error_buf.value.decode('sjis')}")
            #----------------------------------------
            # ステータスを表示
            #----------------------------------------
            if status.value == 0:
                status_string = "0(正常終了)"
            elif status.value == 1:
                status_string = "1(C-WaveformGenerator終了エラー)"
            else:
                status_string = f"{status.value}"
            print(f"ステータス = {status_string}\n")
        #--------------------
        # 終了
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # コマンド範囲外
        #--------------------
        else:
            print("\n範囲外の番号になります。\nもう一度入力してください。\n")
            continue
    #----------------------------------------
    # アプリケーション終了
    #----------------------------------------
    sys.exit()


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