#================================================================
#================================================================
# API-AIO(WDM)
# Simple analog output sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import caio
from AoSimpleUI import AoSimpleUI


#========================================
# AoSimple class
#========================================
class AoSimple:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()                # ID for device access
        self.ao_range = (  caio.PM10,             # +/-10V
                           caio.PM5,              # +/-5V
                           caio.PM25,             # +/-2.5V
                           caio.PM125,            # +/-1.25V
                           caio.P10,              # 0 ~ 10V
                           caio.P5,               # 0 ~ 5V
                           caio.P25,              # 0 ~ 2.5V
                           caio.P125,             # 0 ~ 1.25V
                           caio.P20MA,            # 0 ~ 20mA
                           caio.P4TO20MA,         # 4 ~ 20mA
                           caio.P1TO5)            # 1 ~ 5V
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = AoSimpleUI()
        #----------------------------------------
        # Set the callback function for the UI controls
        #----------------------------------------
        self.ui.setup_commands(
            command_aio_init=self.OnClickedButtonAioInit,
            command_aio_set_ao_range_all=self.OnClickedButtonAioSetAoRangeAll,
            command_aio_single_ao_ex=self.OnClickedButtonAioSingleAoEx,
            command_aio_multi_ao_ex=self.OnClickedButtonAioMultiAoEx,
            command_aio_exit=self.OnClickedButtonAioExit,
            command_close=self.OnClickedButtonClose
        )

    #========================================
    # 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    OnClickedButtonAioInit
    # Parameter        None
    # Details          AioInit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioInit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get device name from textbox
        #----------------------------------------
        device_name = self.ui.textbox_device_name_var.get()
        #----------------------------------------
        # Device initialization
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioInit(device_name.encode(), ctypes.byref(self.id))
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioInit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioSetAoRangeAll
    # Parameter        None
    # Details          AioSetAoRangeAll button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioSetAoRangeAll(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get the range setting value from combobox
        #----------------------------------------
        ao_range = ctypes.c_short(self.ao_range[self.ui.combobox_range.current()])
        #----------------------------------------
        # Set the analog output range (all channels)
        #----------------------------------------
        lret.value = caio.AioSetAoRangeAll(self.id, ao_range)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioSetAoRangeAll = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioSingleAoEx
    # Parameter        None
    # Details          AioSingleAoEx button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioSingleAoEx(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get the channel No. from textbox
        #----------------------------------------
        buf = self.ui.textbox_channel_no_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_channel = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get the output data from textbox
        #----------------------------------------
        buf = self.ui.textbox_single_ao_data_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_data = ctypes.c_float(float(buf))
        #----------------------------------------
        # Output the output data from the specified channel
        #----------------------------------------
        lret.value = caio.AioSingleAoEx(self.id, ao_channel, ao_data)
        #----------------------------------------
        # Error process
        #----------------------------------------
        #--------------------
        # Get error string
        #--------------------
        caio.AioGetErrorString(lret, error_string)
        #--------------------
        # Display message
        #--------------------
        text_buf = f"AioSingleAoEx = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioMultiAoEx
    # Parameter        None
    # Details          AioMultiAoEx button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioMultiAoEx(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        ao_data = (ctypes.c_float * 256)()                 # Multi output data

        #----------------------------------------
        # Get the number of channels from textbox
        #----------------------------------------
        buf = self.ui.textbox_channel_num_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_channels = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get DA conversion data from textbox
        #----------------------------------------
        if 0 < ao_channels.value:
            buf = self.ui.textbox_multi_ao_ex_data1_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_data[0] = float(buf)
        if 1 < ao_channels.value:
            buf = self.ui.textbox_multi_ao_ex_data2_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_data[1] = float(buf)
        if 2 < ao_channels.value:
            buf = self.ui.textbox_multi_ao_ex_data3_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_data[2] = float(buf)
        if 3 < ao_channels.value:
            buf = self.ui.textbox_multi_ao_ex_data4_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_data[3] = float(buf)
        #----------------------------------------
        # Output the output data from the multi-channels
        #----------------------------------------
        lret.value = caio.AioMultiAoEx(self.id, ao_channels, ao_data)
        #----------------------------------------
        # Error process
        #----------------------------------------
        #--------------------
        # Get error string
        #--------------------
        caio.AioGetErrorString(lret, error_string)
        #--------------------
        # Display message
        #--------------------
        text_buf = f"AioMultiAoEx = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioExit
    # Parameter        None
    # Details          AioExit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioExit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Exit process
        #----------------------------------------
        lret.value = caio.AioExit(self.id)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioExit = {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
        #----------------------------------------
        caio.AioExit(self.id)
        #----------------------------------------
        # Close window
        #----------------------------------------
        self.ui.root.destroy()

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


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

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