#================================================================
#================================================================
# API-DIO(WDM)
# PWM パルス出力サンプル
# mainファイル
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# インポートモジュール
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import cdio
from common_function import *
#----------------------------------------
# マクロ定義
#----------------------------------------
MAX_PWM_CH = 4    # 最大PWMチャネル数


#========================================
# 関数名    main
# 引数      なし
# 詳細      main処理を行う関数になります
# 戻り値    なし
#========================================
def main():
    error_buf = ctypes.create_string_buffer(256)                      # エラーコード文字列
    lret = ctypes.c_long()                                            # 戻り値取得用
    id = ctypes.c_short()                                             # デバイスアクセス用ID
    pwm_ch_num = ctypes.c_short()                                     # PWMチャネル数
    pulse_period_value = (ctypes.c_ulonglong * MAX_PWM_CH)()          # パルス周期値配列
    pulse_period_unit = (ctypes.c_ushort * MAX_PWM_CH)(2, 2, 2, 2)    # パルス周期単位配列
    pulse_phase = (ctypes.c_short * MAX_PWM_CH)()                     # 位相シフト配列
    pulse_duty = (ctypes.c_ushort * MAX_PWM_CH)()                     # デューティ比配列
    pwm_status = (ctypes.c_ushort * MAX_PWM_CH)()                     # PWMステータ配列
    pwm_error = (ctypes.c_ushort * MAX_PWM_CH)()                      # PWMエラー配列
    ch_no_array = (ctypes.c_short * MAX_PWM_CH)(0, 1, 2, 3)           # チャネル番号配列
    max_pwm_channels = ctypes.c_ushort()                              # 最大PWMチャネル数
    initialized = 0                                                   # ボードが初期化されているかどうか

    #----------------------------------------
    # 入力待ちループ
    #----------------------------------------
    while True:
        #----------------------------------------
        # 設定パラメータの取得
        #----------------------------------------
        #--------------------
        # PWMパルス周期を取得
        #--------------------
        pulse_period_string_array = ["-"] * MAX_PWM_CH
        lret.value = cdio.DioGetPwmPulsePeriod(id, ch_no_array, pwm_ch_num, pulse_period_value, pulse_period_unit)
        if lret.value == 0:
            GetPulsePeriodString(pwm_ch_num, pulse_period_value, pulse_period_unit, pulse_period_string_array)
        #--------------------
        # PWMパルス位相シフトを取得
        #--------------------
        pulse_phase_string_array = ["-"] * MAX_PWM_CH
        lret.value = cdio.DioGetPwmPulsePhase(id, ch_no_array, pwm_ch_num, pulse_phase)
        if lret.value == 0:
            GetPulsePhaseString(pwm_ch_num, pulse_phase, pulse_phase_string_array)
        #--------------------
        # PWMパルスデューティ比を取得
        #--------------------
        pulse_duty_string_array = ["-"] * MAX_PWM_CH
        lret.value = cdio.DioGetPwmPulseDuty(id, ch_no_array, pwm_ch_num, pulse_duty)
        if lret.value == 0:
            GetPulseDutyString(pwm_ch_num, pulse_duty, pulse_duty_string_array)
        #----------------------------------------
        # 設定パラメータの表示
        #----------------------------------------
        print("========================================")
        print("設定パラメータ")
        print("========================================")
        ch_num_string = f"チャネル数  : {pwm_ch_num.value:d}"
        ch_no_string = "              "
        pulse_period_string = "パルス周期  : "
        pulse_phase_string = "位相シフト  : "
        pulse_duty_string = "デューティ比: "
        for i in range(0, pwm_ch_num.value):
            ch_no_string += f"{f"Ch{i}":<16}"
            pulse_period_string += f"{pulse_period_string_array[i]:<16}"
            pulse_phase_string += f"{pulse_phase_string_array[i]:<16}"
            pulse_duty_string += f"{pulse_duty_string_array[i]:<16}"
        if initialized == 1 and pwm_ch_num.value > 0:
            print(ch_num_string)
            print(ch_no_string)
            print(pulse_period_string)
            print(pulse_phase_string)
            print(pulse_duty_string)
        else:
            if initialized == 1:
                print(ch_num_string)
            else:
                print("チャネル数  : -")
            print("パルス周期  : -")
            print("位相シフト  : -")
            print("デューティ比: -")
        #----------------------------------------
        # コマンドの表示
        #----------------------------------------
        print("========================================")
        print("メニュー")
        print("========================================")
        print("1 : DioInit")
        print("2 : チャンネル数設定")
        print("3 : DioSetPwmPulsePeriod")
        print("4 : DioSetPwmPulsePhase")
        print("5 : DioSetPwmPulseDuty")
        print("6 : DioStartPwm")
        print("7 : DioGetPwmStatus")
        print("8 : DioStopPwm")
        print("9 : DioExit")
        print("q : 終了")
        print("コマンドを入力してください : ", end='', flush=True)
        #----------------------------------------
        # 入力待ち
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # コマンドの識別
        #----------------------------------------
        #--------------------
        # DioInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # デバイス名を入力
            #----------------------------------------
            print("\nデバイス名を入力してください : ", end='', flush=True)
            #----------------------------------------
            # 入力待ち
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # 初期化
            #----------------------------------------
            lret.value = cdio.DioInit(buf.encode(), ctypes.byref(id))
            cdio.DioGetErrorString(lret, error_buf)
            print(f"\nDioInit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            if lret.value == 0:
                initialized = 1
                #----------------------------------------
                # 最大PWMチャネル数を取得
                #----------------------------------------
                lret.value = cdio.DioGetMaxPwmChannels(id, ctypes.byref(max_pwm_channels))
                if lret.value == 0:
                    if max_pwm_channels.value > MAX_PWM_CH:
                        pwm_ch_num.value = MAX_PWM_CH
                    else:
                        pwm_ch_num.value = max_pwm_channels.value
                else:
                    pwm_ch_num.value = 0
            else:
                initialized = 0
        #--------------------
        # チャンネル数設定
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # チャネル数を入力
            #----------------------------------------
            print("")
            while True:
                print("チャネル数を入力してください : ", end='', flush=True)
                #----------------------------------------
                # 入力待ち
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 入力値が数値かとうかをチェック
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            pwm_ch_num = ctypes.c_short(int(buf))
            if pwm_ch_num.value > MAX_PWM_CH:
                pwm_ch_num.value = MAX_PWM_CH
            print(f"\nチャネル数設定 正常終了")
            print(f"チャネル数 = {pwm_ch_num.value:d}\n")
        #--------------------
        # DioSetPwmPulsePeriod
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # パルス周期を入力
            #----------------------------------------
            print("\nパルス周期を入力してください")
            for i in range(0, pwm_ch_num.value):
                while True:
                    print(f"Ch{i} : ", end='', flush=True)
                    #----------------------------------------
                    # 入力待ち
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # 入力値が数値かとうかをチェック
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    break
                pulse_period_value[i] = ctypes.c_ulonglong(int(buf))
            print("\n----------------------------------------")
            print("パラメータ(周期の単位)")
            print("----------------------------------------")
            print(" 1 :  [sec]")
            print(" 2 : [msec]")
            print(" 3 : [usec]")
            print(" 4 : [nsec]")
            print("パルス周期の単位を入力してください")
            for i in range(0, pwm_ch_num.value):
                while True:
                    print(f"Ch{i} : ", end='', flush=True)
                    #----------------------------------------
                    # 入力待ち
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # 入力値が数値かとうかをチェック
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    break
                pulse_period_unit[i] = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # PWMパルス周期設定
            #----------------------------------------
            lret.value = cdio.DioSetPwmPulsePeriod(id, ch_no_array, pwm_ch_num, pulse_period_value, pulse_period_unit)
            cdio.DioGetErrorString(lret, error_buf)
            print(f"\nDioSetPwmPulsePeriod Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                GetPulsePeriodString(pwm_ch_num, pulse_period_value, pulse_period_unit, pulse_period_string_array)
                for i in range(0, pwm_ch_num.value):
                    print(f"Ch{i}: パルス周期 = {pulse_period_string_array[i]}")
            print("")
        #--------------------
        # DioSetPwmPulsePhase
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # 位相シフトを入力
            #----------------------------------------
            print("\n----------------------------------------")
            print("パラメータ(位相シフト)")
            print("----------------------------------------")
            print(" 1 :   0[Deg]")
            print(" 2 :  90[Deg]")
            print(" 3 : 180[Deg]")
            print("位相シフトを入力してください")
            for i in range(0, pwm_ch_num.value):
                while True:
                    print(f"Ch{i} : ", end='', flush=True)
                    #----------------------------------------
                    # 入力待ち
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # 入力値が数値かとうかをチェック
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    break
                if buf == "1":
                    pulse_phase[i] = ctypes.c_short(cdio.DIO_PWM_PULSE_PHASE_0_DEGREES)
                elif buf == "2":
                    pulse_phase[i] = ctypes.c_short(cdio.DIO_PWM_PULSE_PHASE_90_DEGREES)
                elif buf == "3":
                    pulse_phase[i] = ctypes.c_short(cdio.DIO_PWM_PULSE_PHASE_180_DEGREES)
                else:
                    pulse_phase[i] = ctypes.c_short(cdio.DIO_PWM_PULSE_PHASE_0_DEGREES)
            #----------------------------------------
            # PWMパルス位相シフト設定
            #----------------------------------------
            lret.value = cdio.DioSetPwmPulsePhase(id, ch_no_array, pwm_ch_num, pulse_phase)
            cdio.DioGetErrorString(lret, error_buf)
            print(f"\nDioSetPwmPulsePhase Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                GetPulsePhaseString(pwm_ch_num, pulse_phase, pulse_phase_string_array)
                for i in range(0, pwm_ch_num.value):
                    print(f"Ch{i}: 位相シフト = {pulse_phase_string_array[i]}")
            print("")
        #--------------------
        # DioSetPwmPulseDuty
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # デューティ比を入力
            #----------------------------------------
            print("\nデューティ比を入力してください")
            for i in range(0, pwm_ch_num.value):
                while True:
                    print(f"Ch{i} : ", end='', flush=True)
                    #----------------------------------------
                    # 入力待ち
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # 入力値が数値かとうかをチェック
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    break
                pulse_duty[i] = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # PWMパルスデューティ比設定
            #----------------------------------------
            lret.value = cdio.DioSetPwmPulseDuty(id, ch_no_array, pwm_ch_num, pulse_duty)
            cdio.DioGetErrorString(lret, error_buf)
            print(f"\nDioSetPwmPulseDuty Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                GetPulseDutyString(pwm_ch_num, pulse_duty, pulse_duty_string_array)
                for i in range(0, pwm_ch_num.value):
                    print(f"Ch{i}: デューティ比 = {pulse_duty_string_array[i]}")
            print("")
        #--------------------
        # DioStartPwm
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # PWMパルス出力開始
            #----------------------------------------
            lret.value = cdio.DioStartPwm(id, ch_no_array, pwm_ch_num)
            cdio.DioGetErrorString(lret, error_buf)
            print(f"\nDioStartPwm Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # DioGetPwmStatus
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # PWMステータス取得
            #----------------------------------------
            lret.value = cdio.DioGetPwmStatus(id, ch_no_array, pwm_ch_num, pwm_status, pwm_error)
            cdio.DioGetErrorString(lret, error_buf)
            print(f"\nDioGetPwmStatus Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                status_string_array = [""] * MAX_PWM_CH
                GetStatusString(pwm_ch_num, pwm_status, status_string_array)
                for i in range(0, pwm_ch_num.value):
                    print(f"Ch{i}: ステータス = 0x{pwm_status[i]:08x}({status_string_array[i]})、エラー = 0x{pwm_error[i]:08x}")
            print("")
        #--------------------
        # DioStopPwm
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # PWMパルス出力停止
            #----------------------------------------
            lret.value = cdio.DioStopPwm(id, ch_no_array, pwm_ch_num)
            cdio.DioGetErrorString(lret, error_buf)
            print(f"\nDioStopPwm Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # DioExit
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # 終了処理
            #----------------------------------------
            lret.value = cdio.DioExit(id)
            cdio.DioGetErrorString(lret, error_buf)
            print(f"\nDioExit 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
    #----------------------------------------
    # 終了処理
    #----------------------------------------
    cdio.DioExit(id)
    #----------------------------------------
    # アプリケーション終了
    #----------------------------------------
    sys.exit()


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