#================================================================
#================================================================
# API-DIO(WDM)
# PWM pulse output sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import cdio
from common_function import *
#----------------------------------------
# Macro definition
#----------------------------------------
MAX_PWM_CH = 4    # Maximum number of PWM channels


#========================================
# Function name    main
# Parameter        None
# Details          Function that performs main processing
# Return value     None
#========================================
def main():
    error_buf = ctypes.create_string_buffer(256)                      # Error code string
    lret = ctypes.c_long()                                            # For return code
    id = ctypes.c_short()                                             # ID for device access
    pwm_ch_num = ctypes.c_short()                                     # Number of PWM channels
    pulse_period_value = (ctypes.c_ulonglong * MAX_PWM_CH)()          # Pulse period value array
    pulse_period_unit = (ctypes.c_ushort * MAX_PWM_CH)(2, 2, 2, 2)    # Pulse period unit array
    pulse_phase = (ctypes.c_short * MAX_PWM_CH)()                     # Phase shift array
    pulse_duty = (ctypes.c_ushort * MAX_PWM_CH)()                     # Duty ratio array
    pwm_status = (ctypes.c_ushort * MAX_PWM_CH)()                     # PWM status array
    pwm_error = (ctypes.c_ushort * MAX_PWM_CH)()                      # PWM error array
    ch_no_array = (ctypes.c_short * MAX_PWM_CH)(0, 1, 2, 3)           # Channel number array
    max_pwm_channels = ctypes.c_ushort()                              # Maximum number of PWM channels
    initialized = 0                                                   # Whether the board has been initialized

    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the PWM pulse period
        #--------------------
        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)
        #--------------------
        # Get the PWM pulse phase shift
        #--------------------
        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)
        #--------------------
        # Get the PWM pulse duty ratio
        #--------------------
        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)
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        ch_num_string = f"Number of Channels : {pwm_ch_num.value:d}"
        ch_no_string = "                     "
        pulse_period_string = "Pulse Period       : "
        pulse_phase_string = "Phase Shift        : "
        pulse_duty_string = "Duty Ratio         : "
        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("Number of Channels : -")
            print("Pulse Period       : -")
            print("Phase Shift        : -")
            print("Duty Ratio         : -")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print("1 : DioInit")
        print("2 : Number of Channels Set")
        print("3 : DioSetPwmPulsePeriod")
        print("4 : DioSetPwmPulsePhase")
        print("5 : DioSetPwmPulseDuty")
        print("6 : DioStartPwm")
        print("7 : DioGetPwmStatus")
        print("8 : DioStopPwm")
        print("9 : DioExit")
        print("q : Quit")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # DioInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Input the device name
            #----------------------------------------
            print("\nPlease input the device name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # Initialization
            #----------------------------------------
            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
                #----------------------------------------
                # Get the maximum number of PWM channels
                #----------------------------------------
                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
        #--------------------
        # Number of Channels Set
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # Input the number of channels
            #----------------------------------------
            print("")
            while True:
                print("Please input the number of channels : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                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"\nNumber of Channels Set : Successful completion")
            print(f"Number of Channels = {pwm_ch_num.value:d}\n")
        #--------------------
        # DioSetPwmPulsePeriod
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Input the pulse period
            #----------------------------------------
            print("\nPlease input the pulse period")
            for i in range(0, pwm_ch_num.value):
                while True:
                    print(f"Ch{i} : ", end='', flush=True)
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Check if the input value is a number
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    break
                pulse_period_value[i] = ctypes.c_ulonglong(int(buf))
            print("\n----------------------------------------")
            print("Parameter(Period unit)")
            print("----------------------------------------")
            print(" 1 :  [sec]")
            print(" 2 : [msec]")
            print(" 3 : [usec]")
            print(" 4 : [nsec]")
            print("Please input the pulse period unit")
            for i in range(0, pwm_ch_num.value):
                while True:
                    print(f"Ch{i} : ", end='', flush=True)
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Check if the input value is a number
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    break
                pulse_period_unit[i] = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Set the PWM pulse period
            #----------------------------------------
            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 = {pulse_period_string_array[i]}")
            print("")
        #--------------------
        # DioSetPwmPulsePhase
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # Input the phase shift
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Phase shift)")
            print("----------------------------------------")
            print(" 1 :   0[Deg]")
            print(" 2 :  90[Deg]")
            print(" 3 : 180[Deg]")
            print("Please input the phase shift")
            for i in range(0, pwm_ch_num.value):
                while True:
                    print(f"Ch{i} : ", end='', flush=True)
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Check if the input value is a number
                    #----------------------------------------
                    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)
            #----------------------------------------
            # Set the PWM pulse phase shift
            #----------------------------------------
            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}: Phase Shift = {pulse_phase_string_array[i]}")
            print("")
        #--------------------
        # DioSetPwmPulseDuty
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Input the duty ratio
            #----------------------------------------
            print("\nPlease input the duty ratio")
            for i in range(0, pwm_ch_num.value):
                while True:
                    print(f"Ch{i} : ", end='', flush=True)
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Check if the input value is a number
                    #----------------------------------------
                    if False == isnum(buf, 10):
                        continue
                    break
                pulse_duty[i] = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Set the PWM pulse duty ratio
            #----------------------------------------
            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}: Duty Ratio = {pulse_duty_string_array[i]}")
            print("")
        #--------------------
        # DioStartPwm
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # Start the PWM pulse output
            #----------------------------------------
            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":
            #----------------------------------------
            # Get the PWM status
            #----------------------------------------
            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}: Status = 0x{pwm_status[i]:08x}({status_string_array[i]}), Error = 0x{pwm_error[i]:08x}")
            print("")
        #--------------------
        # DioStopPwm
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Stop the PWM pulse output
            #----------------------------------------
            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":
            #----------------------------------------
            # Exit process
            #----------------------------------------
            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
        #--------------------
        # Quit
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    #----------------------------------------
    # Exit process
    #----------------------------------------
    cdio.DioExit(id)
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


#----------------------------------------
# Call main function
#----------------------------------------
if __name__ == "__main__":
    main()