#================================================================
#================================================================
# C-WaveformGenerator
# 複数チャネル波形出力サンプル
# mainファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import cgen_api
from CommonFunction import *
from DeviceSetting import *
from ChannelSetting 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()                     # 画面サイズ
    aochannels = ctypes.c_ushort(1)                   # チャネル数
    frequency = ctypes.c_float(1.0)                   # 周波数
    unit_window = ctypes.c_ushort(0)                  # 周波数単位
    frequency_type = ctypes.c_ushort(0)               # 周波数or周期
    frequency_unit = ctypes.c_ushort(0)               # Hz(sec) Or kHz(msec)
    oscillation_type = ctypes.c_ushort(0)             # 発振タイプ
    oscillation_start = ctypes.c_ushort(1)            # 発振波数
    oscillation_stop = ctypes.c_float(1.0)            # 発振停止波数or発振停止時間
    aochannel = ctypes.c_ushort(0)                    # チャネル番号
    amplitude = ctypes.c_float(0.0)                   # 振幅
    offset = ctypes.c_float(0.0)                      # オフセット
    amplitude_type = ctypes.c_ushort(0)               # 振幅タイプ
    amplitude_unit = ctypes.c_ushort(0)               # 振幅単位
    duty = ctypes.c_float(0.0)                        # Duty
    phase = ctypes.c_float(0.0)                       # 位相
    sweep_type = ctypes.c_ushort(0)                   # 簡易スイープ
    sweep_time = ctypes.c_ushort(1)                   # スイープ時間
    sweep_start = ctypes.c_float(0.0)                 # スイープ変化前
    sweep_stop = ctypes.c_float(0.0)                  # スイープ変化後
    wave_type = ctypes.c_ushort()                     # 波形タイプ
    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 : デバイス設定")
        print("3 : チャネル設定")
        print("4 : GenSetWaveType")
        print("5 : GenStartOperation")
        print("6 : GenGetApplicationStatus")
        print("7 : GenStopOperation")
        print("8 : 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")
        #--------------------
        # デバイス設定
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # デバイス情報の取得を行う
            #----------------------------------------
            lret.value = cgen_api.GenGetDeviceSetting(appid, ctypes.byref(aochannels), ctypes.byref(frequency), ctypes.byref(frequency_type), ctypes.byref(frequency_unit))
            unit_window.value = ((frequency_type.value << 1) + frequency_unit.value)
            #----------------------------------------
            # 発振の取得を行う
            #----------------------------------------
            lret.value = cgen_api.GenGetOscillation(appid, ctypes.byref(oscillation_type), ctypes.byref(oscillation_start), ctypes.byref(oscillation_stop))
            #----------------------------------------
            # デバイス設定の画面へ
            #----------------------------------------
            devinfo_data_set(aochannels, frequency, unit_window, oscillation_type, oscillation_start, oscillation_stop)
            #----------------------------------------
            # デバイス設定メニュー表示
            #----------------------------------------
            #----------------------------------------
            # OKを選択した場合、処理を行う
            #----------------------------------------
            if DeviceSetting() == True:
                #----------------------------------------
                # デバイス設定の画面から
                #----------------------------------------
                devinfo_data_get(aochannels, frequency, unit_window, oscillation_type, oscillation_start, oscillation_stop)
                #----------------------------------------
                # 周波数単位から、タイプと単位に変更
                #----------------------------------------
                frequency_type.value = ((unit_window.value & 0x2) >> 1)
                frequency_unit.value = (unit_window.value & 0x1)
                #----------------------------------------
                # デバイス情報の設定を行う
                #----------------------------------------
                lret.value = cgen_api.GenSetDeviceSetting(appid, aochannels, frequency, frequency_type, frequency_unit)
                #----------------------------------------
                # 正常終了ではない場合、エラーコードを表示
                #----------------------------------------
                if lret.value != 0:
                    cgen_api.GenGetErrorString(lret, error_buf)
                    print("\nデバイス設定 エラー")
                    print(f"GenSetDeviceSetting Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # 発振の設定を行う
                #----------------------------------------
                lret.value = cgen_api.GenSetOscillation(appid, oscillation_type, oscillation_start, oscillation_stop)
                #----------------------------------------
                # 正常終了ではない場合、エラーコードを表示
                #----------------------------------------
                if lret.value != 0:
                    cgen_api.GenGetErrorString(lret, error_buf)
                    print("\nデバイス設定 エラー")
                    print(f"GenSetOscillation Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # デバイス設定完了のメッセージ表示
                #----------------------------------------
                print("\nデバイス設定：正常終了\n")
            #----------------------------------------
            # Cancelを選択した場合、処理を行う
            #----------------------------------------
            else:
                print("")
                continue
        #--------------------
        # チャネル設定
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # チャネル番号を入力
            #----------------------------------------
            print("")
            while True:
                print(f"チャネル番号を入力してください(0-15) : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            aochannel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # 波形タイプを取得を行う
            #----------------------------------------
            lret.value = cgen_api.GenGetWaveType(appid, aochannel, ctypes.byref(wave_type))
            #----------------------------------------
            # チャネル情報の取得を行う
            #----------------------------------------
            lret.value = cgen_api.GenGetChannelSetting(appid, aochannel, ctypes.byref(amplitude), ctypes.byref(offset), ctypes.byref(amplitude_type), ctypes.byref(amplitude_unit), ctypes.byref(duty), ctypes.byref(phase))
            #----------------------------------------
            # 簡易スイープの取得を行う
            #----------------------------------------
            lret.value = cgen_api.GenGetAoSweep(appid, aochannel, ctypes.byref(sweep_type), ctypes.byref(sweep_time), ctypes.byref(sweep_start), ctypes.byref(sweep_stop))
            #----------------------------------------
            # チャネル設定の画面へ
            #----------------------------------------
            chinfo_data_set(aochannel, amplitude, offset, amplitude_type, amplitude_unit, duty, phase, sweep_type, sweep_time, sweep_start, sweep_stop, wave_type)
            #----------------------------------------
            # チャネル設定メニュー表示
            #----------------------------------------
            #----------------------------------------
            # OKを選択した場合、処理を行う
            #----------------------------------------
            if ChannelSetting() == True:
                #----------------------------------------
                # デバイス設定の画面から
                #----------------------------------------
                chinfo_data_get(aochannels, amplitude, offset, amplitude_type, amplitude_unit, duty, phase, sweep_type, sweep_time, sweep_start, sweep_stop)
                #----------------------------------------
                # チャネル情報の設定を行う
                #----------------------------------------
                lret.value = cgen_api.GenSetChannelSetting(appid, aochannel, amplitude, offset, amplitude_type, amplitude_unit, duty, phase)
                #----------------------------------------
                # 正常終了ではない場合、エラーコードを表示
                #----------------------------------------
                if lret.value != 0:
                    cgen_api.GenGetErrorString(lret, error_buf)
                    print("\nチャネル設定 エラー")
                    print(f"GenSetChannelSetting Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # 簡易スイープの設定を行う
                #----------------------------------------
                lret.value = cgen_api.GenSetAoSweep(appid, aochannel, sweep_type, sweep_time, sweep_start, sweep_stop)
                #----------------------------------------
                # 正常終了ではない場合、エラーコードを表示
                #----------------------------------------
                if lret.value != 0:
                    cgen_api.GenGetErrorString(lret, error_buf)
                    print("\nチャネル設定 エラー")
                    print(f"GenSetAoSweep Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    continue
                #----------------------------------------
                # デバイス設定完了のメッセージ表示
                #----------------------------------------
                print("\nチャネル設定：正常終了\n")
            #----------------------------------------
            # Cancelを選択した場合、処理を行う
            #----------------------------------------
            else:
                print("")
                continue
        #--------------------
        # GenSetWaveType
        #--------------------
        elif buf == "4":
            print("\n----------------------------------------")
            print("GenSetWaveTypeを開始します")
            print("----------------------------------------")
            #----------------------------------------
            # チャネル番号を入力
            #----------------------------------------
            while True:
                print(f"チャネル番号を入力してください(0-15) : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            aochannel = 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, aochannel, wave_type)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSetWaveType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenStartOperation
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # アプリの出力開始を行う
            #----------------------------------------
            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 == "6":
            #----------------------------------------
            # 動作状況の取得を行う
            #----------------------------------------
            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 == "7":
            #----------------------------------------
            # アプリの出力停止を行う
            #----------------------------------------
            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 == "8":
            #----------------------------------------
            # デバイスの終了処理を行う
            #----------------------------------------
            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()
