#================================================================
#================================================================
# API-AIO(WDM)
# Finite sampling using attached data sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import caio
from AiSamplingAttachedDataUI import AiSamplingAttachedDataUI


#========================================
# AiSamplingAttachedData class
#========================================
class AiSamplingAttachedData:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.DISPLAY_SAMPLING_COUNT = 1000       # Maximum sampling count of sampling data displayed in listbox
        self.id = ctypes.c_short()               # ID for device access
        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
        self.sampling_buffer = None              # User buffer
        self.sampling_buffer_size = 0            # User buffer size
        self.data_size = 1                       # Data Size (Number of packets)
        self.transfer_count = ctypes.c_long()    # Total transfer count
        self.pai_callback = None                 # Pointer to callback function
        self.user_data = None                    # User data of callback function
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = AiSamplingAttachedDataUI()
        #----------------------------------------
        # Set the callback function for the UI controls
        #----------------------------------------
        self.ui.setup_commands(
            command_aio_init=self.OnClickedButtonAioInit,
            command_aio_reset_device=self.OnClickedButtonAioResetDevice,
            command_aio_set_ai_range_all=self.OnClickedButtonAioSetAiRangeAll,
            command_aio_set_ai_input_method=self.OnClickedButtonAioSetAiInputMethod,
            command_aio_set_ai_channels=self.OnClickedButtonAioSetAiChannels,
            command_aio_set_ai_sampling_clock=self.OnClickedButtonAioSetAiSamplingClock,
            command_aio_set_ai_scan_clock=self.OnClickedButtonAioSetAiScanClock,
            command_aio_set_ai_stop_times=self.OnClickedButtonAioSetAiStopTimes,
            command_aio_set_ai_attached_data=self.OnClickedButtonAioSetAiAttachedData,
            command_basic_settings=self.OnClickedButtonBasicSettings,
            command_user_buffer_size_settings=self.OnClickedButtonUserBufferSizeSettings,
            command_sampling_start=self.OnClickedButtonSamplingStart,
            command_aio_get_ai_transfer_count=self.OnClickedButtonAioGetAiTransferCount,
            command_aio_get_ai_status=self.OnClickedButtonAioGetAiStatus,
            command_sampling_stop=self.OnClickedButtonSamplingStop,
            command_output_sampling_data=self.OnClickedButtonOutputSamplingData,
            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     GetStatusString
    # Parameter         ai_status           Status
    # Details           Function to get status string
    # Return value      ai_status_string    Status string
    #========================================
    @staticmethod
    def GetStatusString(ai_status):
        #----------------------------------------
        # Create the analog input status string
        #----------------------------------------
        #--------------------
        # When status 'Device is running' is ON
        #--------------------
        if (ai_status.value & caio.AIS_BUSY) == caio.AIS_BUSY:
            ai_status_string = "Operating"
        #--------------------
        # When status 'Device is running' is OFF
        #--------------------
        else:
            ai_status_string = "Stop"
        #--------------------
        # When status 'Wait the start trigger' is ON
        #--------------------
        if (ai_status.value & caio.AIS_START_TRG) == caio.AIS_START_TRG:
            ai_status_string += ", Wait the start trigger"
        #--------------------
        # When status 'The specified number of data are stored' is ON
        #--------------------
        if (ai_status.value & caio.AIS_DATA_NUM) == caio.AIS_DATA_NUM:
            ai_status_string += ", The specified number of data are stored"
        #--------------------
        # When status 'Overflow' is ON
        #--------------------
        if (ai_status.value & caio.AIS_OFERR) == caio.AIS_OFERR:
            ai_status_string += ", Overflow"
        #--------------------
        # When status 'Sampling clock error' is ON
        #--------------------
        if (ai_status.value & caio.AIS_SCERR) == caio.AIS_SCERR:
            ai_status_string += ", Sampling clock error"
        #--------------------
        # When status 'AD conversion error' is ON
        #--------------------
        if (ai_status.value & caio.AIS_AIERR) == caio.AIS_AIERR:
            ai_status_string += ", AD conversion error"
        #--------------------
        # When status 'Driver spec error' is ON
        #--------------------
        if (ai_status.value & caio.AIS_DRVERR) == caio.AIS_DRVERR:
            ai_status_string += ", Driver spec error"
        return ai_status_string

    #========================================
    # Function name    CallBackProc
    # Parameter        id          Id get by AioInit
    # Parameter        ai_event    The event that occurred
    # Parameter        wParam      Parameter passed from driver
    # Parameter        lParam      Parameter unique to each event
    # Parameter        Param       Parameter specified in the AioSetAiCallBackProc function
    # Details          Function registered with the AioSetAiCallBackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def CallBackProc(id, ai_event, wParam, lParam, Param):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        ai_transfer_count = ctypes.c_long()                # Transfer count
        ai_status = ctypes.c_long()                        # Status

        #----------------------------------------
        # Create class object
        #----------------------------------------
        obj_ptr = ctypes.cast(Param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Event that device operation end
        # Acquire and display data
        #----------------------------------------
        if ai_event == caio.AIOM_AIE_END:
            #----------------------------------------
            # Get status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"Device Operation End Event Process : AioGetAiStatus = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ai_status_string = self.GetStatusString(ai_status)
            #----------------------------------------
            # Display status
            #----------------------------------------
            self.ui.textbox_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
            #----------------------------------------
            # Get the current transfer count
            #----------------------------------------
            lret.value = caio.AioGetAiTransferCount(self.id, ctypes.byref(ai_transfer_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"Device Operation End Event Process : AioGetAiTransferCount = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Display transfer count
            #----------------------------------------
            self.ui.textbox_transfer_count_var.set(f"{ai_transfer_count.value}")
            #----------------------------------------
            # Update the total transfer count
            #----------------------------------------
            self.transfer_count = ai_transfer_count
            #----------------------------------------
            # Set the loop count for the sampling data display loop
            #----------------------------------------
            #--------------------
            # When the user buffer size is less than the data display maximum sampling count
            #--------------------
            if ((self.sampling_buffer_size / self.data_size) < self.DISPLAY_SAMPLING_COUNT):
                #--------------------
                # When the transfer count of the data acquired this time exceeds the user buffer size
                #--------------------
                if (ai_transfer_count.value > self.sampling_buffer_size):
                    #--------------------
                    # Limit the maximum number of loops to the user buffer size
                    #--------------------
                    loop_max_count = self.sampling_buffer_size / self.data_size
                #--------------------
                # When the transfer count of the data acquired this time less than or equal to the user buffer size
                #--------------------
                else:
                    #--------------------
                    # Limit the maximum number of loops to the transfer count
                    #--------------------
                    loop_max_count = ai_transfer_count.value / self.data_size
                #--------------------
                # Set the top address of the referenced buffer to 0
                #--------------------
                top_address = 0
            #--------------------
            # When the transfer count of the data acquired this time exceeds the user buffer size
            #--------------------
            elif (ai_transfer_count.value > self.sampling_buffer_size):
                #--------------------
                # Limit the maximum number of loops to the data display maximum sampling count
                #--------------------
                loop_max_count = self.DISPLAY_SAMPLING_COUNT
                #--------------------
                # Set the top address of the buffer to be referenced to the address 
                # before the maximum sampling count for data display from the end of the user buffer
                #--------------------
                top_address = (self.sampling_buffer_size.value / self.data_size) - self.DISPLAY_SAMPLING_COUNT
            #--------------------
            # When the transfer count of the data acquired this time exceeds the maximum sampling number of data display
            #--------------------
            elif ((ai_transfer_count.value / self.data_size) > self.DISPLAY_SAMPLING_COUNT):
                #--------------------
                # Limit the maximum number of loops to the data display maximum sampling count
                #--------------------
                loop_max_count = self.DISPLAY_SAMPLING_COUNT
                #--------------------
                # Set the top address of the buffer to be referenced to the address 
                # before the maximum sampling count for data display from the end of the acquired data
                #--------------------
                top_address = (ai_transfer_count.value / self.data_size) - self.DISPLAY_SAMPLING_COUNT
            #--------------------
            # When the sampling count of the data acquired this time is less than or equal to the maximum sampling number of data display
            #--------------------
            else:
                #--------------------
                # Set the transfer count to the maximum loop number
                #--------------------
                loop_max_count = ai_transfer_count.value / self.data_size
                #--------------------
                # Set the top address of the referenced buffer to 0
                #--------------------
                top_address = 0
            #----------------------------------------
            # Display sampling data
            # (Display from the end of acquired data to the maximum number of data display sampling count)
            #----------------------------------------
            #--------------------
            # When the transfer count of the data acquired this time is 1 or more
            #--------------------
            if (ai_transfer_count.value > 0):
                #--------------------
                # Clear the listbox for sampling data display
                #--------------------
                self.ui.listbox_sampling_data_var.set([""])
                data = []
                #--------------------
                # Repeat the process up to the maximum sampling count of the display data
                #--------------------
                for i in range(top_address, int(loop_max_count + top_address)):
                    #--------------------
                    # Generate display string
                    #--------------------
                    text_string =  f"{(i + 1):5d}:  "
                    #--------------------
                    # Repeat the process for the data size (the number of packets)
                    #--------------------
                    for j in range(0, self.data_size):
                        text_string += f" {(self.sampling_buffer[i * self.data_size + j]):08X}"
                    #----------------------------------------
                    # Collect sampling data
                    #----------------------------------------
                    data.append(text_string)
                #----------------------------------------
                # Display sampling start data
                #----------------------------------------
                self.ui.listbox_sampling_data_var.set(data)
            #----------------------------------------
            # Display the message that event processing is completed
            #----------------------------------------
            text_buf = f"Device Operation End Event Process : Successful completion"
            self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # Event that overflow
        # Display the status
        #----------------------------------------
        elif ai_event == caio.AIOM_AIE_OFERR:
            #----------------------------------------
            # Get status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"Overflow Occurrence Process : AioGetAiStatus = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ai_status_string = self.GetStatusString(ai_status)
            #----------------------------------------
            # Display status
            #----------------------------------------
            self.ui.textbox_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
            #----------------------------------------
            # Display the message that event processing is completed
            #----------------------------------------
            text_buf = f"Overflow Occurrence Process : Successful completion"
            self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # Event that sampling clock error
        # Display the status
        #----------------------------------------
        elif ai_event == caio.AIOM_AIE_SCERR:
            #----------------------------------------
            # Get status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"Sampling Clock Error Occurrence Process : AioGetAiStatus = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ai_status_string = self.GetStatusString(ai_status)
            #----------------------------------------
            # Display status
            #----------------------------------------
            self.ui.textbox_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
            #----------------------------------------
            # Display the message that event processing is completed
            #----------------------------------------
            text_buf = f"Sampling Clock Error Occurrence Process : Successful completion"
            self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # Event that AD conversion error
        # Display the status
        #----------------------------------------
        elif ai_event == caio.AIOM_AIE_ADERR:
            #----------------------------------------
            # Get status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"AD Conversion Error Occurrence Process : AioGetAiStatus = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ai_status_string = self.GetStatusString(ai_status)
            #----------------------------------------
            # Display status
            #----------------------------------------
            self.ui.textbox_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
            #----------------------------------------
            # Display the message that event processing is completed
            #----------------------------------------
            text_buf = f"AD Conversion Error Occurrence Process : Successful completion"
            self.ui.textbox_return_string_var.set(text_buf)
        return

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

        #----------------------------------------
        # Reset device
        #----------------------------------------
        lret.value = caio.AioResetDevice(self.id)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioResetDevice = {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 range setting value from combobox
        #----------------------------------------
        ai_range = ctypes.c_short(self.ai_range[self.ui.combobox_range.current()])
        #----------------------------------------
        # Set the analog input range (all channels)
        #----------------------------------------
        lret.value = caio.AioSetAiRangeAll(self.id, ai_range)
        #----------------------------------------
        # 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    OnClickedButtonAioSetAiChannels
    # Parameter        None
    # Details          AioSetAiChannels button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioSetAiChannels(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get the number of channels from textbox
        #----------------------------------------
        buf = self.ui.textbox_channels_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))
        #----------------------------------------
        # Set the number of channels for the analog input conversion
        #----------------------------------------
        lret.value = caio.AioSetAiChannels(self.id, ai_channels)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioSetAiChannels = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Get the internal clock conversion speed from textbox
        #----------------------------------------
        buf = self.ui.textbox_sampling_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:
            ai_sampling_clock = ctypes.c_float(float(buf))
        #----------------------------------------
        # Set the internal clock conversion speed
        #----------------------------------------
        lret.value = caio.AioSetAiSamplingClock(self.id, ai_sampling_clock)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioSetAiSamplingClock = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Get the conversion speed from textbox
        #----------------------------------------
        buf = self.ui.textbox_scan_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:
            ai_scan_clock = ctypes.c_float(float(buf))
        #----------------------------------------
        # Set the conversion speed
        #----------------------------------------
        lret.value = caio.AioSetAiScanClock(self.id, ai_scan_clock)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioSetAiScanClock = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Get the sampling stop times from textbox
        #----------------------------------------
        buf = self.ui.textbox_stop_times_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_stop_times = ctypes.c_long(int(buf))
        #----------------------------------------
        # Set the sampling stop times
        #----------------------------------------
        lret.value = caio.AioSetAiStopTimes(self.id, ai_stop_times)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioSetAiStopTimes = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Get the type of the attached data from textbox
        #----------------------------------------
        attach_data = ((caio.AIAT_AI if self.ui.checkbox_ai_attached_ai_var.get() != 0 else 0) |
                       (caio.AIAT_AO0 if self.ui.checkbox_ai_attached_ao0_var.get() != 0 else 0) |
                       (caio.AIAT_DIO0 if self.ui.checkbox_ai_attached_dio0_var.get() != 0 else 0) |
                       (caio.AIAT_CNT0 if self.ui.checkbox_ai_attached_cnt0_var.get() != 0 else 0) |
                       (caio.AIAT_CNT1 if self.ui.checkbox_ai_attached_cnt1_var.get() != 0 else 0))
        #----------------------------------------
        # Set the attached data that are attached to the AD conversion data
        #----------------------------------------
        lret.value = caio.AioSetAiAttachedData(self.id, attach_data)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioSetAiAttachedData = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Set the data storage memory type to Not overwrite the memory
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioSetAiMemoryType(self.id, 0)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Basic Settings : AioSetAiMemoryType = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the sampling start condition to Software
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioSetAiStartTrigger(self.id, 0)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Basic Settings : AioSetAiStartTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the clock type to Internal Clock
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioSetAiClockType(self.id, 0)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Basic Settings : AioSetAiClockType = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the sampling stop condition to Stop conversion by the specified times
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioSetAiStopTrigger(self.id, 0)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Basic Settings : AioSetAiStopTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the callback routine: 'Event that device operation end', 'Event that overflow', 
        # 'Event that sampling clock error', and 'Event that AD conversion error'.
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        self.pai_callback = caio.PAIO_AI_CALLBACK(self.CallBackProc)
        self.user_data = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p)
        lret.value = caio.AioSetAiCallBackProc(self.id, self.pai_callback, (caio.AIE_END | caio.AIE_OFERR | caio.AIE_SCERR | caio.AIE_ADERR), self.user_data)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Basic Settings : AioSetAiCallBackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display the message that basic setting is completed
        #----------------------------------------
        text_buf = "Basic Settings : Successful completion"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonUserBufferSizeSettings
    # Parameter        None
    # Details          User Buffer Size Set button click event function
    # Return value     None
    #========================================
    def OnClickedButtonUserBufferSizeSettings(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        data_size = ctypes.c_short()                       # Data size (Number of packets)
        sampling_times = ctypes.c_long()                   # Sampling times

        #----------------------------------------
        # Set the analog input conversion data transfer mode to user buffer mode
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioSetAiTransferMode(self.id, 1)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"User Buffer Size Set : AioSetAiTransferMode = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # When the user buffer mode is used to transfer data, retrieves data size that is necessary for one sampling
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingDataSize(self.id, ctypes.byref(data_size))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"User Buffer Size Set : AioGetAiSamplingDataSize = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Get the sampling times from textbox
        #----------------------------------------
        buf = self.ui.textbox_sampling_times_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:
            sampling_times = ctypes.c_long(int(buf))
        #----------------------------------------
        # Allocate the user buffer for storing conversion data
        #----------------------------------------
        #--------------------
        # Release the user buffer for storing conversion data if it has been allocated
        #--------------------
        if self.sampling_buffer is not None:
            self.sampling_buffer = None
        #--------------------
        # User buffer size: number of packets that is necessary for one sampling x sampling times
        #--------------------
        self.data_size = data_size.value
        self.sampling_buffer_size = data_size.value * sampling_times.value
        #--------------------
        # Allocate the user buffer for storing conversion data
        #--------------------
        try:
            self.sampling_buffer = (ctypes.c_int * self.sampling_buffer_size)()
        except:
            text_buf = "User Buffer Size Set : Failed to allocate the user buffer"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set user buffer
        #----------------------------------------
        lret.value = caio.AioSetAiTransferData(self.id, self.sampling_buffer_size, self.sampling_buffer)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"User Buffer Size Set : AioSetAiTransferData = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display the message that user buffer setting is completed
        #----------------------------------------
        text_buf = "User Buffer Size Set : Successful completion"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Clear status
        #----------------------------------------
        lret.value = caio.AioResetAiStatus(self.id)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Sampling Start : AioResetAiStatus = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Initialize the total transfer count
        #----------------------------------------
        self.transfer_count.value = 0
        #----------------------------------------
        # Start sampling
        #----------------------------------------
        lret.value = caio.AioStartAi(self.id)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Sampling Start : AioStartAi = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Get status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Sampling Start : AioGetAiStatus = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = self.GetStatusString(ai_status)
        #----------------------------------------
        # Display status
        #----------------------------------------
        self.ui.textbox_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
        #----------------------------------------
        # Update the transfer count
        #----------------------------------------
        self.ui.textbox_transfer_count_var.set("0")
        #----------------------------------------
        # Clear the listbox for sampling data display
        #----------------------------------------
        self.ui.listbox_sampling_data_var.set([""])
        #----------------------------------------
        # Display the message that sampling start is completed
        #----------------------------------------
        text_buf = "Sampling Start : Successful completion"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Get transfer count
        #----------------------------------------
        lret.value = caio.AioGetAiTransferCount(self.id, ctypes.byref(ai_transfer_count))
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioGetAiTransferCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # When the transfer count acquisition function is completed successfully
        #----------------------------------------
        if lret.value == 0:
            #--------------------
            # Update the transfer count
            #--------------------
            self.ui.textbox_transfer_count_var.set(f"{ai_transfer_count.value}")

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

        #----------------------------------------
        # Get status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioGetAiStatus = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # When the status acquisition function is completed successfully
        #----------------------------------------
        if lret.value == 0:
            #--------------------
            # Display status
            #--------------------
            ai_status_string = self.GetStatusString(ai_status)
            self.ui.textbox_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")

    #========================================
    # Function name    OnClickedButtonSamplingStop
    # Parameter        None
    # Details          Sampling Stop button click event function
    # Return value     None
    #========================================
    def OnClickedButtonSamplingStop(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        ai_transfer_count = ctypes.c_long()                # Transfer count
        ai_status = ctypes.c_long()                        # Status

        #----------------------------------------
        # Stop sampling
        #----------------------------------------
        lret.value = caio.AioStopAi(self.id)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Sampling Stop : AioStopAi = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Get status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Sampling Stop : AioGetAiStatus = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = self.GetStatusString(ai_status)
        #----------------------------------------
        # Display status
        #----------------------------------------
        self.ui.textbox_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
        #----------------------------------------
        # Get the current transfer count
        #----------------------------------------
        lret.value = caio.AioGetAiTransferCount(self.id, ctypes.byref(ai_transfer_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Sampling Stop : AioGetAiTransferCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display transfer count
        #----------------------------------------
        self.ui.textbox_transfer_count_var.set(f"{ai_transfer_count.value}")
        #----------------------------------------
        # Update the total transfer count
        #----------------------------------------
        self.transfer_count = ai_transfer_count
        #----------------------------------------
        # Set the loop count for the sampling data display loop
        #----------------------------------------
        #--------------------
        # When the user buffer size is less than the data display maximum sampling count
        #--------------------
        if ((self.sampling_buffer_size / self.data_size) < self.DISPLAY_SAMPLING_COUNT):
            #--------------------
            # When the transfer count of the data acquired this time exceeds the user buffer size
            #--------------------
            if (ai_transfer_count.value > self.sampling_buffer_size):
                #--------------------
                # Limit the maximum number of loops to the user buffer size
                #--------------------
                loop_max_count = self.sampling_buffer_size / self.data_size
            #--------------------
            # When the transfer count of the data acquired this time less than or equal to the user buffer size
            #--------------------
            else:
                #--------------------
                # Limit the maximum number of loops to the transfer count
                #--------------------
                loop_max_count = ai_transfer_count.value / self.data_size
            #--------------------
            # Set the top address of the referenced buffer to 0
            #--------------------
            top_address = 0
        #--------------------
        # When the transfer count of the data acquired this time exceeds the user buffer size
        #--------------------
        elif (ai_transfer_count.value > self.sampling_buffer_size):
            #--------------------
            # Limit the maximum number of loops to the data display maximum sampling count
            #--------------------
            loop_max_count = self.DISPLAY_SAMPLING_COUNT
            #--------------------
            # Set the top address of the buffer to be referenced to the address 
            # before the maximum sampling count for data display from the end of the user buffer
            #--------------------
            top_address = (self.sampling_buffer_size.value / self.data_size) - self.DISPLAY_SAMPLING_COUNT
        #--------------------
        # When the transfer count of the data acquired this time exceeds the maximum sampling number of data display
        #--------------------
        elif ((ai_transfer_count.value / self.data_size) > self.DISPLAY_SAMPLING_COUNT):
            #--------------------
            # Limit the maximum number of loops to the data display maximum sampling count
            #--------------------
            loop_max_count = self.DISPLAY_SAMPLING_COUNT
            #--------------------
            # Set the top address of the buffer to be referenced to the address 
            # before the maximum sampling count for data display from the end of the acquired data
            #--------------------
            top_address = (ai_transfer_count.value / self.data_size) - self.DISPLAY_SAMPLING_COUNT
        #--------------------
        # When the sampling count of the data acquired this time is less than or equal to the maximum sampling number of data display
        #--------------------
        else:
            #--------------------
            # Set the transfer count to the maximum loop number
            #--------------------
            loop_max_count = ai_transfer_count.value / self.data_size
            #--------------------
            # Set the top address of the referenced buffer to 0
            #--------------------
            top_address = 0
        #----------------------------------------
        # Display sampling data
        # (Display from the end of acquired data to the maximum number of data display sampling count)
        #----------------------------------------
        #--------------------
        # When the transfer count of the data acquired this time is 1 or more
        #--------------------
        if (ai_transfer_count.value > 0):
            #--------------------
            # Clear the listbox for sampling data display
            #--------------------
            self.ui.listbox_sampling_data_var.set([""])
            data = []
            #--------------------
            # Repeat the process up to the maximum sampling count of the display data
            #--------------------
            for i in range(top_address, int(loop_max_count + top_address)):
                #--------------------
                # Generate display string
                #--------------------
                text_string =  f"{(i + 1):5d}:  "
                #--------------------
                # Repeat the process for the data size (the number of packets)
                #--------------------
                for j in range(0, self.data_size):
                    text_string += f" {(self.sampling_buffer[i * self.data_size + j]):08X}"
                #----------------------------------------
                # Collect sampling data
                #----------------------------------------
                data.append(text_string)
            #----------------------------------------
            # Display sampling start data
            #----------------------------------------
            self.ui.listbox_sampling_data_var.set(data)
        #----------------------------------------
        # Display the message that sampling stop is completed
        #----------------------------------------
        text_buf = "Sampling Stop : Successful completion"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonOutputSamplingData
    # Parameter        None
    # Details          Output Acquired Data to File... button click event function
    # Return value     None
    #========================================
    def OnClickedButtonOutputSamplingData(self):
        #----------------------------------------
        # Open file
        #----------------------------------------
        try:
            file = open("SamplingData.csv", 'w')
        except:
            text_buf = "Output Acquired Data to File : open = file open error."
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the maximum loop count for file output loop
        #----------------------------------------
        #--------------------
        # When the total transfer count exceeds the user buffer size
        #--------------------
        if self.transfer_count.value > self.sampling_buffer_size:
            #--------------------
            # Limit the maximum number of loops to the user buffer size
            #--------------------
            loop_max_count = self.sampling_buffer_size
        #--------------------
        # When the total transfer count is less than the user buffer size
        #--------------------
        else:
            #--------------------
            # Set the total transfer count to the maximum number of loops
            #--------------------
            loop_max_count = self.transfer_count.value
        #----------------------------------------
        # Create sampling data for file output
        #----------------------------------------
        #--------------------
        # If the total transfer count is 1 or more
        #--------------------
        if self.transfer_count.value > 0:
            #--------------------
            # Repeat the process up to the maximum number of loops
            #--------------------
            for i in range(0, int(loop_max_count / self.data_size)):
                #--------------------
                # Generate display string
                #--------------------
                text_string = f"{i + 1:d},"
                #--------------------
                # Repeat the process for the data size (the number of packets)
                #--------------------
                for j in range(0, self.data_size):
                    text_string += f"{ctypes.c_uint(self.sampling_buffer[i * self.data_size + j]).value:08X}"
                    #--------------------
                    # Add newline character for the last packet
                    #--------------------
                    if j == (self.data_size - 1):
                        text_string += "\n"
                    #--------------------
                    # Add comma for channels other than the last packet
                    #--------------------
                    else:
                        text_string += ","
                #----------------------------------------
                # Write data
                #----------------------------------------
                file.write(text_string)
        #----------------------------------------
        # Close file
        #----------------------------------------
        file.close()
        #----------------------------------------
        # Display the message that file output is completed
        #----------------------------------------
        text_buf = "Output Acquired Data to File : Save data to \"SamplingData.csv\"."
        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)
        #----------------------------------------
        # Release the user buffer for storing conversion data if it has been allocated
        #----------------------------------------
        if self.sampling_buffer is not None:
            self.sampling_buffer = None
        #----------------------------------------
        # 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 AiSamplingAttachedData
    #----------------------------------------
    instance = AiSamplingAttachedData()
    instance.run()

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