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


#========================================
# AiSamplingOnceDev class
#========================================
class AiSamplingOnceDev:
    #========================================
    # 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_data = None                # Pointer to sampling data storage area
        self.sampling_count = ctypes.c_long()    # Total sampling count
        self.pai_callback = None                 # Pointer to callback function
        self.user_data = None                    # User data of callback function
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = AiSamplingOnceDevUI()
        #----------------------------------------
        # 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_basic_settings=self.OnClickedButtonBasicSettings,
            command_sampling_start=self.OnClickedButtonSamplingStart,
            command_aio_get_ai_sampling_count=self.OnClickedButtonAioGetAiSamplingCount,
            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_sampling_count = ctypes.c_long()                # Sampling count
        ai_status = ctypes.c_long()                        # Status
        ai_channels = ctypes.c_short()                     # Number of channels

        #----------------------------------------
        # 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 sampling count
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingCount(self.id, ctypes.byref(ai_sampling_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"Device Operation End Event Process : AioGetAiSamplingCount = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Display sampling count
            #----------------------------------------
            self.ui.textbox_sampling_count_var.set(f"{ai_sampling_count.value}")
            #----------------------------------------
            # Get the number of channels
            #----------------------------------------
            lret.value = caio.AioGetAiChannels(self.id, ctypes.byref(ai_channels))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"Device Operation End Event Process : AioGetAiChannels = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Get sampling data process
            #----------------------------------------
            #--------------------
            # Allocate an array for storing data
            #--------------------
            if self.sampling_data is not None:
                self.sampling_data = None
            try:
                self.sampling_data = (ctypes.c_float * (ai_sampling_count.value * ai_channels.value))()
            except:
                text_buf = "Device Operation End Event Process : Failed to allocate an array for storing data"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Get sampling data
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingDataEx(self.id, ctypes.byref(ai_sampling_count), self.sampling_data)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"Device Operation End Event Process : AioGetAiSamplingDataEx = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Update the total sampling count
            #----------------------------------------
            self.sampling_count.value = ai_sampling_count.value
            #----------------------------------------
            # Set the loop count for the sampling data display loop
            #----------------------------------------
            #--------------------
            # When the sampling count of the data acquired this time exceeds the maximum sampling number of data display
            #--------------------
            if (ai_sampling_count.value > 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_sampling_count.value - 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 number of total sampling data to the maximum loop number
                #--------------------
                loop_max_count = ai_sampling_count.value
                #--------------------
                # 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 sampling count of the data acquired this time is 1 or more
            #--------------------
            if (ai_sampling_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, loop_max_count + top_address):
                    #--------------------
                    # Generate display string
                    #--------------------
                    text_string =  f"{(i + 1):5d}:"
                    #--------------------
                    # Repeat the process for the specified number of channels
                    #--------------------
                    for j in range(0, ai_channels.value):
                        text_string += f"   {self.sampling_data[i * ai_channels.value + j]:10.5f}"
                    #----------------------------------------
                    # 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    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 analog input conversion data transfer mode to device buffer mode
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioSetAiTransferMode(self.id, 0)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Basic Settings : AioSetAiTransferMode = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the data storage memory type to FIFO
        # 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
        #----------------------------------------
        # In the Z series, the bus master buffer may be limited to a maximum of 1MByte or less.
        # In the real system, implement buffer size change processing as necessary.
        #----------------------------------------
        #lret.value = caio.AioSetAiMemorySize(self.id, 750 * 1024)
        #----------------------------------------
        # 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    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 memory
        #----------------------------------------
        lret.value = caio.AioResetAiMemory(self.id)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Sampling Start : AioResetAiMemory = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # 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 sampling count
        #----------------------------------------
        self.sampling_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 sampling count
        #----------------------------------------
        self.ui.textbox_sampling_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    OnClickedButtonAioGetAiSamplingCount
    # Parameter        None
    # Details          AioGetAiSamplingCount button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioGetAiSamplingCount(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        ai_sampling_count = ctypes.c_long()                # Sampling count

        #----------------------------------------
        # Get sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(self.id, ctypes.byref(ai_sampling_count))
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioGetAiSamplingCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # When the sampling count acquisition function is completed successfully
        #----------------------------------------
        if lret.value == 0:
            #--------------------
            # Update the sampling count
            #--------------------
            self.ui.textbox_sampling_count_var.set(f"{ai_sampling_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_sampling_count = ctypes.c_long()                # Sampling count
        ai_status = ctypes.c_long()                        # Status
        ai_channels = ctypes.c_short()                     # Number of channels

        #----------------------------------------
        # 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 sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(self.id, ctypes.byref(ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Sampling Stop : AioGetAiSamplingCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display sampling count
        #----------------------------------------
        self.ui.textbox_sampling_count_var.set(f"{ai_sampling_count.value}")
        #----------------------------------------
        # When the sampling count of the data acquired this time is 1 or more
        #----------------------------------------
        if ai_sampling_count.value > 0:
            #----------------------------------------
            # Get the number of channels
            #----------------------------------------
            lret.value = caio.AioGetAiChannels(self.id, ctypes.byref(ai_channels))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"Sampling Stop : AioGetAiChannels = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Get sampling data process
            #----------------------------------------
            #--------------------
            # Allocate an array for storing data
            #--------------------
            if self.sampling_data is not None:
                self.sampling_data = None
            try:
                self.sampling_data = (ctypes.c_float * (ai_sampling_count.value * ai_channels.value))()
            except:
                text_buf = "Sampling Stop : Failed to allocate an array for storing data"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Get sampling data
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingDataEx(self.id, ctypes.byref(ai_sampling_count), self.sampling_data)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_string)
                text_buf = f"Sampling Stop : AioGetAiSamplingDataEx = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # Update the total sampling count
            #----------------------------------------
            self.sampling_count.value = ai_sampling_count.value
            #----------------------------------------
            # Set the loop count for the sampling data display loop
            #----------------------------------------
            #--------------------
            # When the sampling count of the data acquired this time exceeds the maximum sampling number of data display
            #--------------------
            if (ai_sampling_count.value > 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_sampling_count.value - 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 number of total sampling data to the maximum loop number
                #--------------------
                loop_max_count = ai_sampling_count.value
                #--------------------
                # 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)
            #----------------------------------------
            #--------------------
            # 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, loop_max_count + top_address):
                #--------------------
                # Generate display string
                #--------------------
                text_string =  f"{(i + 1):5d}:"
                #--------------------
                # Repeat the process for the specified number of channels
                #--------------------
                for j in range(0, ai_channels.value):
                    text_string += f"   {self.sampling_data[i * ai_channels.value + j]:10.5f}"
                #----------------------------------------
                # 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)
        #----------------------------------------
        # When the sampling count of the data acquired this time is 0 or less
        #----------------------------------------
        else:
            #----------------------------------------
            # 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):
        ai_channels = ctypes.c_short()
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # 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
        #----------------------------------------
        # Get the number of channels
        #----------------------------------------
        lret.value = caio.AioGetAiChannels(self.id, ctypes.byref(ai_channels))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_string)
            text_buf = f"Output Acquired Data to File : AioGetAiSamplingCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            #----------------------------------------
            # Close file
            #----------------------------------------
            file.close()
            return
        #----------------------------------------
        # Create sampling data for file output
        #----------------------------------------
        #--------------------
        # If the total sampling count is 1 or more, output the file
        #--------------------
        if (self.sampling_count.value > 0):
            #--------------------
            # Repeat the process up to the total sampling count
            #--------------------
            for i in range(0, int(self.sampling_count.value)):
                #--------------------
                # Generate display string
                #--------------------
                text_string =  f"{(i + 1):d},"
                #--------------------
                # Repeat the process for the specified number of channels
                #--------------------
                for j in range(0, ai_channels.value):
                    text_string += f"{self.sampling_data[i * ai_channels.value + j]:0.5f}"
                    #--------------------
                    # Add newline character for the last channel
                    #--------------------
                    if j == ai_channels.value - 1:
                        text_string += "\n"
                    #--------------------
                    # Add comma for channels other than the last channel
                    #--------------------
                    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

        #----------------------------------------
        # Release the array for storing AD conversion data
        #----------------------------------------
        if self.sampling_data is not None:
            self.sampling_data = None
        #----------------------------------------
        # 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):
        #----------------------------------------
        # Release the array for storing AD conversion data
        #----------------------------------------
        if self.sampling_data is not None:
            self.sampling_data = None
        #----------------------------------------
        # 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 AiSamplingOnceDev
    #----------------------------------------
    instance = AiSamplingOnceDev()
    instance.run()

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