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


#========================================
# AiSimple class
#========================================
class AiSimple:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()                # ID for device access
        self.ai_range_index = ctypes.c_short()    # Index of range
        self.ai_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.PM20MA,           # +/-20mA
                           caio.P1TO5)            # 1-5V
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = AiSimpleUI()
        #----------------------------------------
        # Set the callback function for the UI controls
        #----------------------------------------
        self.ui.setup_commands(
            command_aio_init=self.OnClickedButtonAioInit,
            command_aio_set_ai_range_all=self.OnClickedButtonAioSetAiRangeAll,
            command_aio_set_ai_input_method=self.OnClickedButtonAioSetAiInputMethod,
            command_aio_single_ai_ex=self.OnClickedButtonAioSingleAiEx,
            command_aio_multi_ai_ex=self.OnClickedButtonAioMultiAiEx,
            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    OnClickedButtonAioSetAiRangeAll
    # Parameter        None
    # Details          AioSetAiRangeAll button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioSetAiRangeAll(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

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

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

        #----------------------------------------
        # Get the input method setting value from combobox
        #----------------------------------------
        input_method = ctypes.c_short(self.ui.combobox_input_method.current())
        #----------------------------------------
        # Set the analog input method
        #----------------------------------------
        lret.value = caio.AioSetAiInputMethod(self.id, input_method)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioSetAiInputMethod = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioSingleAiEx
    # Parameter        None
    # Details          AioSingleAiEx button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioSingleAiEx(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        ai_data = ctypes.c_float()                         # Input data

        #----------------------------------------
        # 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:
            ai_channel = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get the AD conversion data of specified channel
        #----------------------------------------
        lret.value = caio.AioSingleAiEx(self.id, ai_channel, ai_data)
        #----------------------------------------
        # Error process
        #----------------------------------------
        #--------------------
        # Get error string
        #--------------------
        caio.AioGetErrorString(lret, error_string)
        #--------------------
        # Display message
        #--------------------
        text_buf = f"AioSingleAiEx = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #--------------------
        # Exit the process if not completed successfully
        #--------------------
        if lret.value != 0:
            return
        #----------------------------------------
        # Display the AD conversion data of specified channel
        #----------------------------------------
        if (self.ai_range[self.ai_range_index.value] == caio.P20MA) or (self.ai_range[self.ai_range_index.value] == caio.P4TO20MA) or (self.ai_range[self.ai_range_index.value] == caio.PM20MA):
            text_string = f"{ai_data.value:2.5f}mA"
        else:
            text_string = f"{ai_data.value:2.5f}V"
        #--------------------
        # Update conversion data display
        #--------------------
        self.ui.textbox_single_ai_data_var.set(text_string)

    #========================================
    # Function name    OnClickedButtonAioMultiAiEx
    # Parameter        None
    # Details          AioMultiAiEx button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioMultiAiEx(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        ai_data = (ctypes.c_float * 256)()                 # Multi input 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:
            ai_channels = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get the AD conversion data of multi-channels
        #----------------------------------------
        lret.value = caio.AioMultiAiEx(self.id, ai_channels, ai_data)
        #----------------------------------------
        # Error process
        #----------------------------------------
        #--------------------
        # Get error string
        #--------------------
        caio.AioGetErrorString(lret, error_string)
        #--------------------
        # Display message
        #--------------------
        text_buf = f"AioMultiAiEx = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #--------------------
        # Exit the process if not completed successfully
        #--------------------
        if lret.value != 0:
            return
        #----------------------------------------
        # Display AD conversion data
        #----------------------------------------
        #--------------------
        # Clear the listbox for AD conversion data display
        #--------------------
        self.ui.listbox_multi_ai_data_var.set([""])
        data = []
        #--------------------
        # Repeat the process up to the set number of channels
        #--------------------
        for i in range(0, ai_channels.value):
            #--------------------
            # Generate display data
            #--------------------
            if (self.ai_range[self.ai_range_index.value] == caio.P20MA) or (self.ai_range[self.ai_range_index.value] == caio.P4TO20MA) or (self.ai_range[self.ai_range_index.value] == caio.PM20MA):
                text_string = f"{i:3d}            {ai_data[i]:2.5f}mA"
            else:
                text_string = f"{i:3d}            {ai_data[i]:2.5f}V"
            #----------------------------------------
            # Collect conversion data
            #----------------------------------------
            data.append(text_string)
        #----------------------------------------
        # Update conversion data display
        #----------------------------------------
        self.ui.listbox_multi_ai_data_var.set(data)

    #========================================
    # 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 AiSimple
    #----------------------------------------
    instance = AiSimple()
    instance.run()

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