﻿#================================================================
#================================================================
# API-AIO(WDM)
# Infinite generating using user buffer sample
# Condition setting file
#                                                 CONTEC Co.,Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import caio
from ConditionUI import ConditionWindowUI


#========================================
# ConditionWindow class
#========================================
class ConditionWindow:
    #========================================
    # Initialization function
    #========================================
    def __init__(self, parent):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.start_trigger = (0,    # Software
                              1,    # External trigger rising edge
                              2)    # External trigger falling edge
        self.clock_type    = (0,    # Internal clock
                              1)    # External clock
        self.clock_edge    = (0,    # External input falling edge
                              1)    # External input rising edge
        self.stop_trigger  = (1,    # External trigger rising edge
                              2)    # External trigger falling edge
        #----------------------------------------
        # Set the parent window
        #----------------------------------------
        self.parent = parent
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = ConditionWindowUI(parent)
        #----------------------------------------
        # Set the callback function for the UI controls
        #----------------------------------------
        self.ui.setup_commands(
            command_clock_type=self.OnSelendokComboClockType,
            command_ok=self.OnClickedButtonOk,
            command_cancel=self.OnClickedButtonCancel
        )
        #----------------------------------------
        # Initialize the display
        #----------------------------------------
        self._update_ui()
        #----------------------------------------
        # Wait until the modal dialog closes
        #----------------------------------------
        self.parent.ui.root.wait_window(self.ui.condition_window)

    #========================================
    # Initialize the display
    #========================================
    def _update_ui(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        ao_start_trigger = ctypes.c_short()                # Conversion start condition
        ao_stop_trigger = ctypes.c_short()                 # Conversion stop condition
        ao_clock_type = ctypes.c_short()                   # Clock type
        ao_generating_clock = ctypes.c_float()             # Generating clock
        ao_clock_edge = ctypes.c_short()                   # Timing of the external clock input
        ao_auto_mode = ctypes.c_short()                    # Set mode of transfer size
        ao_transfer_size = ctypes.c_long()                 # Transfer size

        #----------------------------------------
        # Initialize parameters
        #----------------------------------------
        err_flag = 0
        self.parent.condition_ok = False
        #----------------------------------------
        # Get the analog output conversion start condition
        #----------------------------------------
        lret.value = caio.AioGetAoStartTrigger(self.parent.id, ctypes.byref(ao_start_trigger))
        #----------------------------------------
        # Abnormal termination process
        #----------------------------------------
        if lret.value != 0:
            if lret.value != 20001:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Generate error message
                #--------------------
                message_string = f"AioGetAoStartTrigger = {lret.value} : {error_string.value.decode('sjis')}\n\n*The display could not be updated since an error occurred."
                err_flag = 1
            else:
                #--------------------
                # Disable control
                #--------------------
                self.ui.combobox_start_condition.config(state="disabled")
            #--------------------
            # Change the selection of analog output conversion start condition combobox to 0
            #--------------------
            self.ui.combobox_start_condition.current(0)
        #----------------------------------------
        # Normal termination process
        #----------------------------------------
        else:
            #--------------------
            # Change the selection of the analog output conversion start condition combobox
            #--------------------
            if ao_start_trigger.value == 0:
                self.ui.combobox_start_condition.current(0)
            elif ao_start_trigger.value == 1:
                self.ui.combobox_start_condition.current(1)
            elif ao_start_trigger.value == 2:
                self.ui.combobox_start_condition.current(2)
            else:
                self.ui.combobox_start_condition.current(0)
        #----------------------------------------
        # Get clock type
        #----------------------------------------
        lret.value = caio.AioGetAoClockType(self.parent.id, ctypes.byref(ao_clock_type))
        #----------------------------------------
        # Abnormal termination process
        #----------------------------------------
        if lret.value != 0:
            if lret.value != 20001:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Generate error message
                #--------------------
                message_string = f"AioGetAoClockType = {lret.value} : {error_string.value.decode('sjis')}\n\n*The display could not be updated since an error occurred."
                err_flag = 1
            else:
                #--------------------
                # Disable control
                #--------------------
                self.ui.combobox_clock_type.config(state="disabled")
            #--------------------
            # Change the selection of the analog output clock type combobox to 0
            #--------------------
            self.ui.combobox_clock_type.current(0)
            self.OnSelendokComboClockType()
        #----------------------------------------
        # Normal termination process
        #----------------------------------------
        else:
            #--------------------
            # Change the selection of the analog output clock type combobox
            #--------------------
            if ao_clock_type.value == 0:
                self.ui.combobox_clock_type.current(0)
            elif ao_clock_type.value == 1:
                self.ui.combobox_clock_type.current(1)
            else:
                self.ui.combobox_clock_type.current(0)
            self.OnSelendokComboClockType()
        #----------------------------------------
        # Get generating clock
        #----------------------------------------
        lret.value = caio.AioGetAoSamplingClock(self.parent.id, ctypes.byref(ao_generating_clock))
        #----------------------------------------
        # Abnormal termination process
        #----------------------------------------
        if lret.value != 0:
            if lret.value != 20001:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Generate error message
                #--------------------
                message_string = f"AioGetAoSamplingClock = {lret.value} : {error_string.value.decode('sjis')}\n\n*The display could not be updated since an error occurred."
                err_flag = 1
            else:
                #--------------------
                # Disable control
                #--------------------
                self.ui.textbox_generating_clock.config(state="disabled")
            #--------------------
            # Update the initial display of generating clock
            #--------------------
            self.ui.textbox_generating_clock_var.set("1000")
        #----------------------------------------
        # Normal termination process
        #----------------------------------------
        else:
            #--------------------
            # Update generating clock
            #--------------------
            self.ui.textbox_generating_clock_var.set(f"{ao_generating_clock.value:.6f}")
        #----------------------------------------
        # For External clock
        #----------------------------------------
        if ao_clock_type.value == 1:
            #----------------------------------------
            # Get the timing of external clock input
            #----------------------------------------
            lret.value = caio.AioGetAoClockEdge(self.parent.id, ctypes.byref(ao_clock_edge))
            #----------------------------------------
            # Abnormal termination process
            #----------------------------------------
            if lret.value != 0:
                if lret.value != 20001:
                    #--------------------
                    # Get error string
                    #--------------------
                    caio.AioGetErrorString(lret, error_string)
                    #--------------------
                    # Generate error message
                    #--------------------
                    message_string = f"AioGetAoClockEdge = {lret.value} : {error_string.value.decode('sjis')}\n\n*The display could not be updated since an error occurred."
                    err_flag = 1
                else:
                    #--------------------
                    # Disable control
                    #--------------------
                    self.ui.combobox_clock_edge['state'] = 'disabled'
                #--------------------
                # Change the selection of the external clock input timing combobox to 0
                #--------------------
                self.ui.combobox_clock_edge.current(0)
            #----------------------------------------
            # Normal termination process
            #----------------------------------------
            else:
                #--------------------
                # Change the selection of the external clock input timing combobox
                #--------------------
                if ao_clock_edge.value == 0:
                    self.ui.combobox_clock_edge.current(0)
                elif ao_clock_edge.value == 1:
                    self.ui.combobox_clock_edge.current(1)
                else:
                    self.ui.combobox_clock_edge.current(0)
        #----------------------------------------
        # Other than External clock
        #----------------------------------------
        else:
            #----------------------------------------
            # Change the selection of the external clock input timing combobox to 0
            #----------------------------------------
            self.ui.combobox_clock_edge.current(0)
        #----------------------------------------
        # Get transfer size
        #----------------------------------------
        lret.value = caio.AioGetAoTransferSize(self.parent.id, ctypes.byref(ao_auto_mode), ctypes.byref(ao_transfer_size))
        #----------------------------------------
        # Abnormal termination process
        #----------------------------------------
        if lret.value != 0:
            if lret.value != 20001:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Generate error message
                #--------------------
                message_string = f"AioGetAoTransferSize = {lret.value} : {error_string.value.decode('sjis')}\n\n*The display could not be updated since an error occurred."
                err_flag = 1
            else:
                #--------------------
                # Disable control
                #--------------------
                self.ui.textbox_transfer_size.config(state="disabled")
            #--------------------
            # Update the initial display of transfer size
            #--------------------
            self.ui.textbox_transfer_size_var.set("0")
        #----------------------------------------
        # Normal termination process
        #----------------------------------------
        else:
            #--------------------
            # Update transfer size
            #--------------------
            self.ui.textbox_transfer_size_var.set(f"{ao_transfer_size.value}")
        #----------------------------------------
        # Get the analog output conversion stop condition
        #----------------------------------------
        lret.value = caio.AioGetAoStopTrigger(self.parent.id, ctypes.byref(ao_stop_trigger))
        #----------------------------------------
        # Abnormal termination process
        #----------------------------------------
        if lret.value != 0:
            if lret.value != 20001:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Generate error message
                #--------------------
                message_string = f"AioGetAoStopTrigger = {lret.value} : {error_string.value.decode('sjis')}\n\n*The display could not be updated since an error occurred."
                err_flag = 1
            else:
                #--------------------
                # Disable control
                #--------------------
                self.ui.combobox_stop_condition.config(state="disabled")
            #--------------------
            # Change the selection in the analog output conversion stop condition combobox to 0
            #--------------------
            self.ui.combobox_stop_condition.current(0)
        #----------------------------------------
        # Normal termination process
        #----------------------------------------
        else:
            #--------------------
            # Change the selection in the analog output conversion stop condition combobox
            #--------------------
            if ao_stop_trigger.value == 1:
                self.ui.combobox_stop_condition.current(0)
            elif ao_stop_trigger.value == 2:
                self.ui.combobox_stop_condition.current(1)
            else:
                self.ui.combobox_stop_condition.current(0)
        #----------------------------------------
        # Display message if an error occurs
        #----------------------------------------
        if err_flag != 0:
            self.ui.show_error("Error", message_string)

    #========================================
    # Function name    isnum
    # Parameter        str     String
    # Parameter        base    Base
    # Details          Function to checks 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    OnSelendokComboClockType
    # Parameter        event    Event(Fixed to None)
    # Details          Function of updating available controls
    # Return value     None
    #========================================
    def OnSelendokComboClockType(self, event=None):
        lret = ctypes.c_long()             # For return code
        auto_mode = ctypes.c_short()       # Set mode of transfer size
        transfer_size = ctypes.c_long()    # Transfer size

        #----------------------------------------
        # Get the index of clock type from combobox
        #----------------------------------------
        index = self.ui.combobox_clock_type.current()
        #----------------------------------------
        # Branch processing by clock type
        #----------------------------------------
        if self.clock_type[index] == 0:      # Internal clock
            self.ui.textbox_generating_clock.config(state="normal")
            self.ui.combobox_clock_edge.config(state="disabled")
            self.ui.textbox_transfer_size.config(state="disabled")
        elif self.clock_type[index] == 1:    # External clock
            self.ui.textbox_generating_clock.config(state="disabled")
            self.ui.combobox_clock_edge.config(state="readonly")
            #----------------------------------------
            # Get transfer size
            #----------------------------------------
            lret.value = caio.AioGetAoTransferSize(self.parent.id, ctypes.byref(auto_mode), ctypes.byref(transfer_size))
            #----------------------------------------
            # Abnormal termination process
            #----------------------------------------
            if lret.value != 0:
                self.ui.textbox_transfer_size.config(state="disabled")
            else:
                self.ui.textbox_transfer_size.config(state="normal")
        else:
            self.ui.textbox_generating_clock.config(state="normal")
            self.ui.combobox_clock_edge.config(state="disabled")
            self.ui.textbox_transfer_size.config(state="disabled")

    #========================================
    # Function name    OnClickedButtonOk
    # Parameter        None
    # Details          OK button click event function
    # Return value     None
    #========================================
    def OnClickedButtonOk(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        ao_generating_clock = ctypes.c_float()             # Generating clock

        #----------------------------------------
        # Set the analog output conversion data transfer mode to user buffer mode
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioSetAoTransferMode(self.parent.id, 1)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_string = f"AioSetAoTransferMode = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_string)
            return
        #----------------------------------------
        # Set the data storage memory type to Repeat output
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioSetAoMemoryType(self.parent.id, 1)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_string = f"AioSetAoMemoryType = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_string)
            return
        #----------------------------------------
        # Set analog output conversion start condition
        #----------------------------------------
        lret.value = caio.AioSetAoStartTrigger(self.parent.id, self.start_trigger[self.ui.combobox_start_condition.current()])
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_string = f"AioSetAoStartTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_string)
            return
        #----------------------------------------
        # Set analog output clock type
        #----------------------------------------
        lret.value = caio.AioSetAoClockType(self.parent.id, self.clock_type[self.ui.combobox_clock_type.current()])
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_string = f"AioSetAoClockType = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_string)
            return
        #----------------------------------------
        # For Internal clock
        #----------------------------------------
        if self.clock_type[self.ui.combobox_clock_type.current()] == 0:
            #----------------------------------------
            # Get the generating clock from textbox
            #----------------------------------------
            buf = self.ui.textbox_generating_clock_var.get()
            #----------------------------------------
            # Check if the input value is a number
            #----------------------------------------
            if False == self.isnum(buf, 0):
                self.ui.show_error("Error", "The input value is invalid.")
                return
            else:
                ao_generating_clock = ctypes.c_float(float(buf))
            #----------------------------------------
            # Set analog output generating clock
            #----------------------------------------
            lret.value = caio.AioSetAoSamplingClock(self.parent.id, ao_generating_clock)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_string = f"AioSetAoSamplingClock = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_string)
                return
            #----------------------------------------
            # Set analog output transfer size
            #----------------------------------------
            lret.value = caio.AioSetAoTransferSize(self.parent.id, caio.AO_TRANSFERSIZE_AUTO, 0)
            if lret.value != 0 and lret.value != 20001:
                caio.AioGetErrorString(lret, error_string)
                text_string = f"AioSetAoTransferSize = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_string)
                return
        #----------------------------------------
        # For External clock
        #----------------------------------------
        elif self.clock_type[self.ui.combobox_clock_type.current()] == 1:
            #----------------------------------------
            # Set the timing of external clock input
            #----------------------------------------
            lret.value = caio.AioSetAoClockEdge(self.parent.id, self.clock_edge[self.ui.combobox_clock_edge.current()])
            #--------------------
            # Exit the process if not completed successfully
            #--------------------
            if lret.value != 0 and lret.value != 20001:
                caio.AioGetErrorString(lret, error_string)
                text_string = f"AioSetAoClockEdge = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_string)
                return
            #----------------------------------------
            # Get the transfer size from textbox
            #----------------------------------------
            buf = self.ui.textbox_transfer_size_var.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:
                ao_transfer_size = ctypes.c_long(int(buf))
            #----------------------------------------
            # Set analog output transfer size
            #----------------------------------------
            lret.value = caio.AioSetAoTransferSize(self.parent.id, caio.AO_TRANSFERSIZE_MANUAL, ao_transfer_size)
            if lret.value != 0 and lret.value != 20001:
                caio.AioGetErrorString(lret, error_string)
                text_string = f"AioSetAoTransferSize = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.show_error("Error", text_string)
                return
        #----------------------------------------
        # Set analog output conversion stop condition
        #----------------------------------------
        lret.value = caio.AioSetAoStopTrigger(self.parent.id, self.stop_trigger[self.ui.combobox_stop_condition.current()])
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_string = f"AioSetAoStopTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_string)
            return
        #----------------------------------------
        # Repeat times: Infinite
        #----------------------------------------
        lret.value = caio.AioSetAoRepeatTimes(self.parent.id, 0)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_string = f"AioSetAoRepeatTimes = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.show_error("Error", text_string)
            return
        #----------------------------------------
        # Close window
        #----------------------------------------
        self.parent.condition_ok = True
        self.ui.condition_window.destroy()

    #========================================
    # Function name    OnClickedButtonCancel
    # Parameter        None
    # Details          Cancel button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCancel(self):
        #----------------------------------------
        # Close window
        #----------------------------------------
        self.ui.condition_window.destroy()