#================================================================
#================================================================
# API-DIO(WDM)
# PWM Pulse Output Sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import cdio
from pwm_output_ui import PwmOutputUI


#========================================
# PwmOutput class
#========================================
class PwmOutput:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Macro definition
        #----------------------------------------
        self.MAX_PWM_CH = 4                                           # Maximum number of PWM channels
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()                                    # Device ID
        self.combobox_pulse_period_unit = [None] * self.MAX_PWM_CH    # Pulse period unit control
        self.combobox_phase_shift = [None] * self.MAX_PWM_CH          # Pulse phase shift control
        self.textbox_pulse_period_var = [None] * self.MAX_PWM_CH      # PWM pulse period value control
        self.textbox_duty_ratio_var = [None] * self.MAX_PWM_CH        # PWM pulse duty ratio control
        self.textbox_pwm_status_var = [None] * self.MAX_PWM_CH        # PWM status control
        self.textbox_pwm_error_var = [None] * self.MAX_PWM_CH         # PWM error control
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = PwmOutputUI()
        #----------------------------------------
        # Set control array
        #----------------------------------------
        #--------------------
        # Pulse period control
        #--------------------
        self.textbox_pulse_period_var[0] = self.ui.textbox_ch0_pulse_period_var
        self.textbox_pulse_period_var[1] = self.ui.textbox_ch1_pulse_period_var
        self.textbox_pulse_period_var[2] = self.ui.textbox_ch2_pulse_period_var
        self.textbox_pulse_period_var[3] = self.ui.textbox_ch3_pulse_period_var
        #--------------------
        # Pulse period unit control
        #--------------------
        self.combobox_pulse_period_unit[0] = self.ui.combobox_ch0_pulse_period_unit
        self.combobox_pulse_period_unit[1] = self.ui.combobox_ch1_pulse_period_unit
        self.combobox_pulse_period_unit[2] = self.ui.combobox_ch2_pulse_period_unit
        self.combobox_pulse_period_unit[3] = self.ui.combobox_ch3_pulse_period_unit
        #--------------------
        # Pulse duty ratio control
        #--------------------
        self.textbox_duty_ratio_var[0] = self.ui.textbox_ch0_duty_ratio_var
        self.textbox_duty_ratio_var[1] = self.ui.textbox_ch1_duty_ratio_var
        self.textbox_duty_ratio_var[2] = self.ui.textbox_ch2_duty_ratio_var
        self.textbox_duty_ratio_var[3] = self.ui.textbox_ch3_duty_ratio_var
        #--------------------
        # Pulse phase shift control
        #--------------------
        self.combobox_phase_shift[0] = self.ui.combobox_ch0_phase_shift
        self.combobox_phase_shift[1] = self.ui.combobox_ch1_phase_shift
        self.combobox_phase_shift[2] = self.ui.combobox_ch2_phase_shift
        self.combobox_phase_shift[3] = self.ui.combobox_ch3_phase_shift
        #--------------------
        # PWM status control
        #--------------------
        self.textbox_pwm_status_var[0] = self.ui.textbox_ch0_pwm_status_var
        self.textbox_pwm_status_var[1] = self.ui.textbox_ch1_pwm_status_var
        self.textbox_pwm_status_var[2] = self.ui.textbox_ch2_pwm_status_var
        self.textbox_pwm_status_var[3] = self.ui.textbox_ch3_pwm_status_var
        #--------------------
        # PWM error control
        #--------------------
        self.textbox_pwm_error_var[0] = self.ui.textbox_ch0_pwm_error_var
        self.textbox_pwm_error_var[1] = self.ui.textbox_ch1_pwm_error_var
        self.textbox_pwm_error_var[2] = self.ui.textbox_ch2_pwm_error_var
        self.textbox_pwm_error_var[3] = self.ui.textbox_ch3_pwm_error_var
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_dio_init=self.OnClickedButtonDioInit,
            command_dio_set_pwm_pulse_period=self.OnClickedButtonDioSetPwmPulsePeriod,
            command_dio_set_pwm_pulse_phase=self.OnClickedButtonDioSetPwmPulsePhase,
            command_dio_set_pwm_pulse_duty=self.OnClickedButtonDioSetPwmPulseDuty,
            command_dio_start_pwm=self.OnClickedButtonDioStartPwm,
            command_dio_get_pwm_status=self.OnClickedButtonDioGetPwmStatus,
            command_dio_stop_pwm=self.OnClickedButtonDioStopPwm,
            command_dio_exit=self.OnClickedButtonDioExit,
            command_close=self.OnClickedButtonClose
        )

    #========================================
    # Function name    isnum
    # Parameter        str     String
    # Parameter        base    Base
    # Details          Function to check if a string can be converted to a number
    # Return value     True: Can be converted
    #                  False: Can not be converted
    #========================================
    @staticmethod
    def isnum(str, base):
        try:
            if 10 == base:
                int(str, 10)
            elif 16 == base:
                int(str, 16)
            else:
                float(str)
        except:
            return False
        return True

    #========================================
    # Function name    OnClickedButtonDioInit
    # Parameter        None
    # Details          DioInit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioInit(self):
        error_string = ctypes.create_string_buffer(256)
        lret = ctypes.c_long()

        #----------------------------------------
        # Get device name
        #----------------------------------------
        device_name = self.ui.textbox_device_name_var.get()
        #----------------------------------------
        # Initialization and get device ID
        #----------------------------------------
        lret.value = cdio.DioInit(device_name.encode(), ctypes.byref(self.id))
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioInit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioSetPwmPulsePeriod
    # Parameter        None
    # Details          DioSetPwmPulsePeriod button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioSetPwmPulsePeriod(self):
        error_string = ctypes.create_string_buffer(256)
        lret = ctypes.c_long()
        pulse_period_value = (ctypes.c_ulonglong * self.MAX_PWM_CH)()
        pulse_period_unit = (ctypes.c_ushort * self.MAX_PWM_CH)()
        ch_no_array = (ctypes.c_short * self.MAX_PWM_CH)()
        pwm_ch_num = ctypes.c_short()

        #----------------------------------------
        # Get number of channels
        #----------------------------------------
        buf = self.ui.combobox_channel_num.get()
        pwm_ch_num = ctypes.c_short(int(buf))
        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(0, pwm_ch_num.value):
            #----------------------------------------
            # Store channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
            #----------------------------------------
            # Get specified value of PWM pulse period
            #----------------------------------------
            buf = self.textbox_pulse_period_var[ch_no].get()
            #--------------------
            # Check if the input value is a number
            #--------------------
            if False == self.isnum(buf, 10):
                self.ui.show_error("Error", "The input value is invalid.")
                return
            else:
                pulse_period_value[ch_no] = ctypes.c_ulonglong(int(buf))
            #----------------------------------------
            # Get specified value of pulse period unit
            #----------------------------------------
            buf = self.combobox_pulse_period_unit[ch_no].get()
            if buf == "sec":
                pulse_period_unit[ch_no] = cdio.DIO_PWM_PULSE_UNIT_S
            elif buf == "msec":
                pulse_period_unit[ch_no] = cdio.DIO_PWM_PULSE_UNIT_MS
            elif buf == "usec":
                pulse_period_unit[ch_no] = cdio.DIO_PWM_PULSE_UNIT_US
            else:
                pulse_period_unit[ch_no] = cdio.DIO_PWM_PULSE_UNIT_NS
        #----------------------------------------
        # PWM pulse period setting
        #----------------------------------------
        lret.value = cdio.DioSetPwmPulsePeriod(self.id, ch_no_array, pwm_ch_num, pulse_period_value, pulse_period_unit)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioSetPwmPulsePeriod = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioSetPwmPulsePhase
    # Parameter        None
    # Details          DioSetPwmPulsePhase button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioSetPwmPulsePhase(self):
        error_string = ctypes.create_string_buffer(256)
        lret = ctypes.c_long()
        pulse_phase = (ctypes.c_short * self.MAX_PWM_CH)()
        ch_no_array = (ctypes.c_short * self.MAX_PWM_CH)()
        pwm_ch_num = ctypes.c_short()

        #----------------------------------------
        # Get number of channels
        #----------------------------------------
        buf = self.ui.combobox_channel_num.get()
        pwm_ch_num = ctypes.c_short(int(buf))
        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(0, pwm_ch_num.value):
            #----------------------------------------
            # Store channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
            #----------------------------------------
            # Get specified value of PWM pulse phase shift
            #----------------------------------------
            buf = self.combobox_phase_shift[ch_no].get()
            if buf == "0":
                pulse_phase[ch_no] = cdio.DIO_PWM_PULSE_PHASE_0_DEGREES
            elif buf == "90":
                pulse_phase[ch_no] = cdio.DIO_PWM_PULSE_PHASE_90_DEGREES
            else:
                pulse_phase[ch_no] = cdio.DIO_PWM_PULSE_PHASE_180_DEGREES
        #----------------------------------------
        # PWM pulse phase shift setting
        #----------------------------------------
        lret.value = cdio.DioSetPwmPulsePhase(self.id, ch_no_array, pwm_ch_num, pulse_phase)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioSetPwmPulsePhase = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioSetPwmPulseDuty
    # Parameter        None
    # Details          DioSetPwmPulseDuty button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioSetPwmPulseDuty(self):
        error_string = ctypes.create_string_buffer(256)
        lret = ctypes.c_long()
        pulse_duty = (ctypes.c_ushort * self.MAX_PWM_CH)()
        ch_no_array = (ctypes.c_short * self.MAX_PWM_CH)()
        pwm_ch_num = ctypes.c_short()

        #----------------------------------------
        # Get number of channels
        #----------------------------------------
        buf = self.ui.combobox_channel_num.get()
        pwm_ch_num = ctypes.c_short(int(buf))
        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(0, pwm_ch_num.value):
            #----------------------------------------
            # Store channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
            #----------------------------------------
            # Get specified value of PWM pulse duty ratio
            #----------------------------------------
            buf = self.textbox_duty_ratio_var[ch_no].get()
            #--------------------
            # Check if the input value is a number
            #--------------------
            if False == self.isnum(buf, 10):
                self.ui.show_error("Error", "The input value is invalid.")
                return
            else:
                pulse_duty[ch_no] = ctypes.c_ushort(int(buf))
        #----------------------------------------
        # PWM pulse duty ratio setting
        #----------------------------------------
        lret.value = cdio.DioSetPwmPulseDuty(self.id, ch_no_array, pwm_ch_num, pulse_duty)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioSetPwmPulseDuty = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioStartPwm
    # Parameter        None
    # Details          DioStartPwm button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioStartPwm(self):
        error_string = ctypes.create_string_buffer(256)
        lret = ctypes.c_long()
        ch_no_array = (ctypes.c_short * self.MAX_PWM_CH)()
        pwm_ch_num = ctypes.c_short()

        #----------------------------------------
        # Get number of channels
        #----------------------------------------
        buf = self.ui.combobox_channel_num.get()
        pwm_ch_num = ctypes.c_short(int(buf))
        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(0, pwm_ch_num.value):
            #----------------------------------------
            # Store channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
        #----------------------------------------
        # Start PWM pulse output
        #----------------------------------------
        lret.value = cdio.DioStartPwm(self.id, ch_no_array, pwm_ch_num)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioStartPwm = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioGetPwmStatus
    # Parameter        None
    # Details          DioGetPwmStatus button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioGetPwmStatus(self):
        error_string = ctypes.create_string_buffer(256)
        lret = ctypes.c_long()
        pwm_status = (ctypes.c_ushort * self.MAX_PWM_CH)()
        pwm_error = (ctypes.c_ushort * self.MAX_PWM_CH)()
        ch_no_array = (ctypes.c_short * self.MAX_PWM_CH)()
        pwm_ch_num = ctypes.c_short()

        #----------------------------------------
        # Get number of channels
        #----------------------------------------
        buf = self.ui.combobox_channel_num.get()
        pwm_ch_num = ctypes.c_short(int(buf))
        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(0, pwm_ch_num.value):
            #----------------------------------------
            # Store channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
        #----------------------------------------
        # Get PWM status
        #----------------------------------------
        lret.value = cdio.DioGetPwmStatus(self.id, ch_no_array, pwm_ch_num, pwm_status, pwm_error)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioGetPwmStatus = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # Terminate process in case of error
        #----------------------------------------
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(0, pwm_ch_num.value):
            #----------------------------------------
            # Update the display of PWM status
            #----------------------------------------
            buf = f"{pwm_status[ch_no]:X}"
            self.textbox_pwm_status_var[ch_no].set(buf)
            #----------------------------------------
            # Update the display of PWM error
            #----------------------------------------
            buf = f"{pwm_error[ch_no]:X}"
            self.textbox_pwm_error_var[ch_no].set(buf)

    #========================================
    # Function name    OnClickedButtonDioStopPwm
    # Parameter        None
    # Details          DioStopPwm button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioStopPwm(self):
        error_string = ctypes.create_string_buffer(256)
        lret = ctypes.c_long()
        ch_no_array = (ctypes.c_short * self.MAX_PWM_CH)()
        pwm_ch_num = ctypes.c_short()

        #----------------------------------------
        # Get number of channels
        #----------------------------------------
        buf = self.ui.combobox_channel_num.get()
        pwm_ch_num = ctypes.c_short(int(buf))
        #----------------------------------------
        # For each channel
        #----------------------------------------
        for ch_no in range(0, pwm_ch_num.value):
            #----------------------------------------
            # Store channel number
            #----------------------------------------
            ch_no_array[ch_no] = ch_no
        #----------------------------------------
        # Stop PWM pulse output
        #----------------------------------------
        lret.value = cdio.DioStopPwm(self.id, ch_no_array, pwm_ch_num)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioStopPwm = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioExit
    # Parameter        None
    # Details          DioExit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioExit(self):
        error_string = ctypes.create_string_buffer(256)
        lret = ctypes.c_long()

        #----------------------------------------
        # Exit process
        #----------------------------------------
        lret.value = cdio.DioExit(self.id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioExit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonClose
    # Parameter        None
    # Details          Close button click event function
    # Return value     None
    #========================================
    def OnClickedButtonClose(self):
        #----------------------------------------
        # Exit process
        #----------------------------------------
        cdio.DioExit(self.id)
        #----------------------------------------
        # Exit the window
        #----------------------------------------
        self.ui.root.destroy()

    #========================================
    # Function name    run
    # Parameter        None
    # Details          A function that runs the application
    # Return value     None
    #========================================
    def run(self):
        self.ui.run()


#========================================
# main function
#========================================
def main():
    #----------------------------------------
    # Create and Run PwmOutput
    #----------------------------------------
    instance = PwmOutput()
    instance.run()

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