﻿#================================================================
#================================================================
# API-AIO(WDM)
# Device internal synchronization (Count Comparison Match/Sampling) sample
# main file
#                                                 CONTEC Co.,Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import caio
from InternalSyncCounterSamplingUI import InternalSyncCounterSamplingUI


#========================================
# InternalSyncCounterSampling class
#========================================
class InternalSyncCounterSampling:
    #========================================
    # 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.cnt_channel = ctypes.c_short()    # Counter channel
        self.sampling_count = 0                # Total sampling count
        self.sampling_data = None              # Pointer to sampling data storage area
        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.pcnt_callback = None              # Pointer to counter callback function
        self.pcnt_user_data = None             # User data of counter callback function
        self.pai_callback = None               # Pointer to sampling callback function
        self.pai_user_data = None              # User data of sampling callback function
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = InternalSyncCounterSamplingUI()
        #----------------------------------------
        # Set the callback function for the UI controls
        #----------------------------------------
        self.ui.setup_commands(
            command_aio_init=self.OnClickedButtonAioInit,
            command_aio_reset_device=self.OnClickedButtonAioResetDevice,
            command_cnt_channel_no=self.OnChangedEditCntChannelNo,
            command_cnt_ai_setting=self.OnClickedButtonCntAiSetting,
            command_sampling_setting=self.OnClickedButtonSamplingSetting,
            command_sync_setting=self.OnClickedButtonSyncSetting,
            command_sampling_start=self.OnClickedButtonSamplingStart,
            command_counter_start=self.OnClickedButtonCounterStart,
            command_aio_preset_cnt=self.OnClickedButtonAioPresetCnt,
            command_get_status=self.OnClickedButtonGetStatus,
            command_sampling_stop=self.OnClickedButtonSamplingStop,
            command_counter_stop=self.OnClickedButtonCounterStop,
            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     GetCntStatusString
    # Parameter         cnt_status           Status
    # Details           Function to get status string
    # Return value      cnt_status_string    Status string
    #========================================
    @staticmethod
    def GetCntStatusString(cnt_status):
        #----------------------------------------
        # Create counter input status string
        #----------------------------------------
        #--------------------
        # When status 'Counter in operation' is ON
        #--------------------
        if (cnt_status.value & caio.CNTS_BUSY) == caio.CNTS_BUSY:
            cnt_status_string = "Operating"
        #--------------------
        # When status 'Counter in operation' is OFF
        #--------------------
        else:
            cnt_status_string = "Stop"
        #--------------------
        # When status 'Comparison count match' is ON
        #--------------------
        if (cnt_status.value & caio.CNTS_DATA_NUM) == caio.CNTS_DATA_NUM:
            cnt_status_string += ", Comparison count match"
        #--------------------
        # When status 'Overrun' is ON
        #--------------------
        if (cnt_status.value & caio.CNTS_ORERR) == caio.CNTS_ORERR:
            cnt_status_string += ", Overrun"
        #--------------------
        # When status 'Counter operation error' is ON
        #--------------------
        if (cnt_status.value & caio.CNTS_ERR) == caio.CNTS_ERR:
            text_buf += ", Counter operation error"
        return cnt_status_string

    #========================================
    # Function name     GetAiStatusString
    # Parameter         ai_status           Status
    # Details           Function to get status string
    # Return value      ai_status_string    Status string
    #========================================
    @staticmethod
    def GetAiStatusString(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    CounterMasterCallBackProc
    # Parameter        id           Id get by AioInit
    # Parameter        cnt_event    The event that occurred
    # Parameter        wParam       Parameter passed from driver
    # Parameter        lParam       Parameter unique to each event
    # Parameter        Param        Parameter specified in the AioSetCntCallBackProc function
    # Details          Function registered with the AioSetCntCallBackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def CounterMasterCallBackProc(id, cnt_event, wParam, lParam, Param):
        cnt_status = ctypes.c_long()                       # Counter status
        cnt_count = ctypes.c_long()                        # Count value
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Create class object
        #----------------------------------------
        obj_ptr = ctypes.cast(Param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # [Counter]
        # Comparison count match event
        # Acquire and display data
        #----------------------------------------
        if cnt_event == caio.AIOM_CNTE_DATA_NUM:
            #----------------------------------------
            # Get counter channel
            #----------------------------------------
            cnt_channel = wParam >> 16
            if cnt_channel == self.cnt_channel.value:
                #----------------------------------------
                # Get count value
                #----------------------------------------
                lret.value = caio.AioGetCntCount(self.id, self.cnt_channel, ctypes.byref(cnt_count))
                #----------------------------------------
                # Error process
                #----------------------------------------
                if lret.value != 0:
                    #--------------------
                    # Get error string
                    #--------------------
                    caio.AioGetErrorString(lret, error_string)
                    #--------------------
                    # Display message
                    #--------------------
                    text_buf = f"Comparison Count Match Event Process : AioGetCntCount = {lret.value} : {error_string.value.decode('sjis')}"
                    self.ui.textbox_return_string_var.set(text_buf)
                    return
                #----------------------------------------
                # Display count value
                #----------------------------------------
                text_buf = f"{cnt_count.value}"
                self.ui.textbox_cnt_count_var.set(text_buf)
                #----------------------------------------
                # Get status
                #----------------------------------------
                lret.value = caio.AioGetCntStatus(self.id, self.cnt_channel, ctypes.byref(cnt_status))
                #----------------------------------------
                # Error process
                #----------------------------------------
                if lret.value != 0:
                    #--------------------
                    # Get error string
                    #--------------------
                    caio.AioGetErrorString(lret, error_string)
                    #--------------------
                    # Display message
                    #--------------------
                    text_buf = f"Comparison Count Match Event Process : AioGetCntStatus = {lret.value} : {error_string.value.decode('sjis')}"
                    self.ui.textbox_return_string_var.set(text_buf)
                    return
                #----------------------------------------
                # Create the status string
                #----------------------------------------
                cnt_status_string = self.GetCntStatusString(cnt_status)
                #----------------------------------------
                # Display the status
                #----------------------------------------
                self.ui.textbox_cnt_status_var.set(f"{cnt_status.value:08x}H ({cnt_status_string})")
                #----------------------------------------
                # Display the message that event processing is completed
                #----------------------------------------
                self.ui.textbox_return_string_var.set("Comparison Count Match Event Process : Successful completion")
        #----------------------------------------
        # [Counter]
        # Counter operation error
        # Display the status
        #----------------------------------------
        if cnt_event == caio.AIOM_CNTE_ERR:
            #----------------------------------------
            # Get counter channel
            #----------------------------------------
            cnt_channel = wParam >> 16
            if cnt_channel == self.cnt_channel.value:
                #----------------------------------------
                # Get status
                #----------------------------------------
                lret.value = caio.AioGetCntStatus(self.id, self.cnt_channel, ctypes.byref(cnt_status))
                #----------------------------------------
                # Error process
                #----------------------------------------
                if lret.value != 0:
                    #--------------------
                    # Get error string
                    #--------------------
                    caio.AioGetErrorString(lret, error_string)
                    #--------------------
                    # Display message
                    #--------------------
                    text_buf = f"Counter Operation Error Occurrence Process : AioGetCntStatus = {lret.value} : {error_string.value.decode('sjis')}"
                    self.ui.textbox_return_string_var.set(text_buf)
                    return
                #----------------------------------------
                # Create the status string
                #----------------------------------------
                cnt_status_string = self.GetCntStatusString(cnt_status)
                #----------------------------------------
                # Display the status
                #----------------------------------------
                self.ui.textbox_cnt_status_var.set(f"{cnt_status.value:08x}H ({cnt_status_string})")
                #----------------------------------------
                # Display the message that event processing is completed
                #----------------------------------------
                self.ui.textbox_return_string_var.set("Counter Operation Error Occurrence Process : Successful completion")

    #========================================
    # Function name    SamplingSlaveCallBackProc
    # 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 SamplingSlaveCallBackProc(id, ai_event, wParam, lParam, Param):
        ai_status = ctypes.c_long()                        # Sampling Status
        ai_sampling_count = ctypes.c_long()                # Sampling count
        ai_channels = ctypes.c_short()                     # Number of channels
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Create class object
        #----------------------------------------
        obj_ptr = ctypes.cast(Param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # [Sampling]
        # Event that AD conversion start
        # Display the status
        #----------------------------------------
        if ai_event == caio.AIOM_AIE_START:
            #----------------------------------------
            # Get status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                text_buf = f"Event that AD conversion start 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.GetAiStatusString(ai_status)
            #----------------------------------------
            # Display the status
            #----------------------------------------
            self.ui.textbox_ai_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
            #----------------------------------------
            # Display the message that event processing is completed
            #----------------------------------------
            self.ui.textbox_return_string_var.set("Event that AD conversion start Process : Successful completion")
        #----------------------------------------
        # [Sampling]
        # 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))
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                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.GetAiStatusString(ai_status)
            #----------------------------------------
            # Display the status
            #----------------------------------------
            self.ui.textbox_ai_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))
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                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
            #----------------------------------------
            text_buf = f"{ai_sampling_count.value}"
            self.ui.textbox_ai_sampling_count_var.set(text_buf)
            #----------------------------------------
            # Get the number of channels
             #----------------------------------------
            lret.value = caio.AioGetAiChannels(self.id, ctypes.byref(ai_channels))
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                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
            #----------------------------------------
            # 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:
                self.ui.textbox_return_string_var.set("Device Operation End Event Process : Failed to allocate an array for storing data")
                return
            #----------------------------------------
            # Get sampling data
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingDataEx(self.id, ctypes.byref(ai_sampling_count), self.sampling_data)
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                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 = 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_ai_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(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_ai_sampling_data_var.set(data)
            #----------------------------------------
            # Display the message that event processing is completed
            #----------------------------------------
            self.ui.textbox_return_string_var.set("Device Operation End Event Process : Successful completion")
        #----------------------------------------
        # [Sampling]
        # Event that overflow
        # Display the status
        #----------------------------------------
        if ai_event == caio.AIOM_AIE_OFERR:
            #----------------------------------------
            # Get status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                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.GetAiStatusString(ai_status)
            #----------------------------------------
            # Display the status
            #----------------------------------------
            self.ui.textbox_ai_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
            #----------------------------------------
            # Display the message that event processing is completed
            #----------------------------------------
            self.ui.textbox_return_string_var.set("Overflow Occurrence Process : Successful completion")
        #----------------------------------------
        # [Sampling]
        # Event that sampling clock error
        # Display the status
        #----------------------------------------
        if ai_event == caio.AIOM_AIE_SCERR:
            #----------------------------------------
            # Get status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                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.GetAiStatusString(ai_status)
            #----------------------------------------
            # Display the status
            #----------------------------------------
            self.ui.textbox_ai_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
            #----------------------------------------
            # Display the message that event processing is completed
            #----------------------------------------
            self.ui.textbox_return_string_var.set("Sampling Clock Error Occurrence Process : Successful completion")
        #----------------------------------------
        # [Sampling]
        # Event that AD conversion error
        # Display the status
        #----------------------------------------
        if ai_event == caio.AIOM_AIE_ADERR:
            #----------------------------------------
            # Get status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                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.GetAiStatusString(ai_status)
            #----------------------------------------
            # Display the status
            #----------------------------------------
            self.ui.textbox_ai_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
            #----------------------------------------
            # Display the message that event processing is completed
            #----------------------------------------
            self.ui.textbox_return_string_var.set("AD Conversion Error Occurrence Process : Successful completion")

    #========================================
    # 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    OnChangedEditCntChannelNo
    # Parameter        event    Event(None Fixed)
    # Details          ChannelNo textbox changed event function
    # Return value     None
    #========================================
    def OnChangedEditCntChannelNo(self, event=None):
        #----------------------------------------
        # Get counter channel from textbox
        #----------------------------------------
        buf = self.ui.textbox_cnt_channel_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:
            self.cnt_channel = ctypes.c_short(int(buf))

    #========================================
    # Function name    OnClickedButtonCntAiSetting
    # Parameter        None
    # Details          Counter/Analog Input Set button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCntAiSetting(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get the analog input range setting value from combobox
        #----------------------------------------
        ai_range = ctypes.c_short(self.ai_range[self.ui.combobox_ai_range.current()])
        #----------------------------------------
        # Set the analog input range (all channels)
        #----------------------------------------
        lret.value = caio.AioSetAiRangeAll(self.id, ai_range)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Counter/Analog Input Set : AioSetAiRangeAll = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Get the input method setting value from combobox
        #----------------------------------------
        input_method = ctypes.c_short(self.ui.combobox_ai_input_method.current())
        #----------------------------------------
        # Set the analog input method
        #----------------------------------------
        lret.value = caio.AioSetAiInputMethod(self.id, input_method)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Counter/Analog Input Set : AioSetAiInputMethod = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the counter operation mode
        #----------------------------------------
        lret.value = caio.AioSetCntComparisonMode(self.id, self.cnt_channel, caio.CNT_LOADCOMP)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Counter/Analog Input Set : AioSetCntComparisonMode = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Get counter comparison count data from textbox
        #----------------------------------------
        buf = self.ui.textbox_cnt_comparison_value_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:
            comparison_data = ctypes.c_long(int(buf))
        #----------------------------------------
        # Set the next comparison count value loaded after comparison count match
        #----------------------------------------
        lret.value = caio.AioSetCntComparisonReg(self.id, self.cnt_channel, 1, ctypes.byref(comparison_data), 0)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Counter/Analog Input Set : AioSetCntComparisonReg = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the callback routine: 'Comparison count match event', 'Counter operation error'.
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        self.pcnt_callback = caio.PAIO_CNT_CALLBACK(self.CounterMasterCallBackProc)
        self.pcnt_user_data = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p)
        lret.value = caio.AioSetCntCallBackProc(self.id, self.cnt_channel, self.pcnt_callback, (caio.CNTE_DATA_NUM | caio.CNTE_ERR), self.pcnt_user_data)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Counter/Analog Input Set : AioSetCntCallBackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display the message that counter/analog input settings is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Counter/Analog Input Set : Successful completion")

    #========================================
    # Function name    OnClickedButtonSamplingSetting
    # Parameter        None
    # Details          Sampling Set button click event function
    # Return value     None
    #========================================
    def OnClickedButtonSamplingSetting(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_ai_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 analog input channels used for conversion
        #----------------------------------------
        lret.value = caio.AioSetAiChannels(self.id, ai_channels)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sampling Set : AioSetAiChannels = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # 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)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sampling Set : 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)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sampling Set : AioSetAiMemoryType = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the sampling start condition to Event controller output
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioSetAiStartTrigger(self.id, 10)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sampling Set : 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)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sampling Set : AioSetAiClockType = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Get the internal clock conversion speed from textbox
        #----------------------------------------
        buf = self.ui.textbox_ai_internal_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)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sampling Set : AioSetAiSamplingClock = {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)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sampling Set : AioSetAiStopTrigger = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Get the sampling stop times from textbox
        #----------------------------------------
        buf = self.ui.textbox_ai_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:
            stop_times = ctypes.c_long(int(buf))
        #----------------------------------------
        # Set the sampling stop times
        #----------------------------------------
        lret.value = caio.AioSetAiStopTimes(self.id, stop_times)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sampling Set : AioSetAiStopTimes = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set the callback routine: 'Event that AD conversion start', '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.SamplingSlaveCallBackProc)
        self.pai_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_START | caio.AIE_END | caio.AIE_OFERR | caio.AIE_SCERR | caio.AIE_ADERR), self.pai_user_data)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sampling Set : AioSetAiCallBackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display the message that sampling settings is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Sampling Set : Successful completion")

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

        #----------------------------------------
        # Event Controller Setting : Connect Count comparison match of counter 0/1 to Analog input converting start signal
        #----------------------------------------
        lret.value = caio.AioSetEcuSignal(self.id, caio.AIOECU_DEST_AI_START, caio.AIOECU_SRC_CNT0_CMP + self.cnt_channel.value)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Sync Process Set : AioSetEcuSignal = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display the message that synchronous process settings is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Sync Process Set : Successful completion")

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

        #----------------------------------------
        # Clear memory
        #----------------------------------------
        lret.value = caio.AioResetAiMemory(self.id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            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)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            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 = 0
        #----------------------------------------
        # Start sampling
        #----------------------------------------
        lret.value = caio.AioStartAi(self.id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            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))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            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.GetAiStatusString(ai_status)
        #----------------------------------------
        # Display the status
        #----------------------------------------
        self.ui.textbox_ai_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
        #----------------------------------------
        # Update the sampling count
        #----------------------------------------
        self.ui.textbox_ai_sampling_count_var.set("0")
        #----------------------------------------
        # Clear the listbox for sampling data display
        #----------------------------------------
        self.ui.listbox_ai_sampling_data_var.set([""])
        #----------------------------------------
        # Display the message that sampling start is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set('Sampling Start : Successful completion')

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

        #----------------------------------------
        # Reset status
        #----------------------------------------
        lret.value = caio.AioResetCntStatus(self.id, self.cnt_channel, caio.CNTS_DATA_NUM | caio.CNTS_ORERR)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Counter Start : AioResetCntStatus = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Start the counter action
        #----------------------------------------
        lret.value = caio.AioStartCnt(self.id, self.cnt_channel)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Counter Start : AioStartCnt = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Get status
        #----------------------------------------
        lret.value = caio.AioGetCntStatus(self.id, self.cnt_channel, ctypes.byref(cnt_status))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Counter Start : AioGetCntStatus = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        cnt_status_string = self.GetCntStatusString(cnt_status)
        #----------------------------------------
        # Display the status
        #----------------------------------------
        self.ui.textbox_cnt_status_var.set(f"{cnt_status.value:08x}H ({cnt_status_string})")
        #----------------------------------------
        # Update count value
        #----------------------------------------
        self.ui.textbox_cnt_count_var.set("0")
        #----------------------------------------
        # Display the message that counter start is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Counter Start : Successful completion")

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

        #----------------------------------------
        # Get counter preset value from textbox
        #----------------------------------------
        buf = self.ui.textbox_cnt_preset_value_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:
            preset_data = ctypes.c_long(int(buf))
        #----------------------------------------
        # Preset the counter
        #----------------------------------------
        lret.value = caio.AioPresetCnt(self.id, self.cnt_channel, preset_data)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioPresetCnt = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # When the count value preset function is completed successfully
        #----------------------------------------
        if lret.value == 0:
            #--------------------
            # Get the count value
            #--------------------
            lret.value = caio.AioGetCntCount(self.id, self.cnt_channel, ctypes.byref(cnt_count))
            #--------------------
            # Error process
            #--------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                text_buf = f"AioGetCntCount = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #--------------------
            # Update count value
            #--------------------
            text_buf = f"{cnt_count.value}"
            self.ui.textbox_cnt_count_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonGetStatus
    # Parameter        None
    # Details          Get Status button click event function
    # Return value     None
    #========================================
    def OnClickedButtonGetStatus(self):
        ai_sampling_count = ctypes.c_long()                # Sampling count
        ai_status = ctypes.c_long()                        # Sampling status
        cnt_count = ctypes.c_long()                        # Count value
        cnt_status = ctypes.c_long()                       # Counter Status
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get the sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(self.id, ctypes.byref(ai_sampling_count))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Get Status : AioGetAiSamplingCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Update sampling count
        #----------------------------------------
        text_buf = f"{ai_sampling_count.value}"
        self.ui.textbox_ai_sampling_count_var.set(text_buf)
        #----------------------------------------
        # Get status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(self.id, ctypes.byref(ai_status))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Get Status : 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.GetAiStatusString(ai_status)
        #----------------------------------------
        # Display the status
        #----------------------------------------
        self.ui.textbox_ai_status_var.set(f"{ai_status.value:08x}H ({ai_status_string})")
        #----------------------------------------
        # Get count value
        #----------------------------------------
        lret.value = caio.AioGetCntCount(self.id, self.cnt_channel, ctypes.byref(cnt_count))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Get Status : AioGetCntCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Update count value
        #----------------------------------------
        text_buf = f"{cnt_count.value}"
        self.ui.textbox_cnt_count_var.set(text_buf)
        #----------------------------------------
        # Get status
        #----------------------------------------
        lret.value = caio.AioGetCntStatus(self.id, self.cnt_channel, ctypes.byref(cnt_status))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Get Status : AioGetCntStatus = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        cnt_status_string = self.GetCntStatusString(cnt_status)
        #----------------------------------------
        # Display the status
        #----------------------------------------
        self.ui.textbox_cnt_status_var.set(f"{cnt_status.value:08x}H ({cnt_status_string})")
        #----------------------------------------
        # Display the message that get status is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Get Status : Successful completion")

    #========================================
    # 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_status = ctypes.c_long()                        # Sampling Status
        ai_sampling_count = ctypes.c_long()                # Sampling count
        ai_channels = ctypes.c_short()                     # Number of channels

        #----------------------------------------
        # Stop sampling
        #----------------------------------------
        lret.value = caio.AioStopAi(self.id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            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))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            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.GetAiStatusString(ai_status)
        #----------------------------------------
        # Display the status
        #----------------------------------------
        self.ui.textbox_ai_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))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            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
        #----------------------------------------
        text_buf = f"{ai_sampling_count.value}"
        self.ui.textbox_ai_sampling_count_var.set(text_buf)
        #----------------------------------------
        # 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))
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                text_buf = f"Sampling Stop : AioGetAiChannels = {lret.value} : {error_string.value.decode('sjis')}"
                self.ui.textbox_return_string_var.set(text_buf)
                return
            #----------------------------------------
            # 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:
                self.ui.textbox_return_string_var.set("Sampling Stop : Failed to allocate an array for storing data")
                return
            #----------------------------------------
            # Get sampling data
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingDataEx(self.id, ctypes.byref(ai_sampling_count), self.sampling_data)
            #----------------------------------------
            # Error process
            #----------------------------------------
            if lret.value != 0:
                #--------------------
                # Get error string
                #--------------------
                caio.AioGetErrorString(lret, error_string)
                #--------------------
                # Display message
                #--------------------
                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 = 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_ai_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(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_ai_sampling_data_var.set(data)
            #----------------------------------------
            # Display the message that sampling stop is completed
            #----------------------------------------
            self.ui.textbox_return_string_var.set("Sampling Stop : Successful completion")
        #----------------------------------------
        # When the sampling count of the data acquired this time is 0 or less
        #----------------------------------------
        else:
            #----------------------------------------
            # Display the message that sampling stop is completed
            #----------------------------------------
            self.ui.textbox_return_string_var.set("Sampling Stop : Successful completion")

    #========================================
    # Function name    OnClickedButtonCounterStop
    # Parameter        None
    # Details          Counter Stop button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCounterStop(self):
        cnt_count = ctypes.c_long()                        # Count value
        cnt_status = ctypes.c_long()                       # Count status
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Stop the counter action
        #----------------------------------------
        lret.value = caio.AioStopCnt(self.id, self.cnt_channel)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Count Stop : AioStopCnt = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Get count value
        #----------------------------------------
        lret.value = caio.AioGetCntCount(self.id, self.cnt_channel, ctypes.byref(cnt_count))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Count Stop : AioGetCntCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Update count value
        #----------------------------------------
        text_buf = f"{cnt_count.value}"
        self.ui.textbox_cnt_count_var.set(text_buf)
        #----------------------------------------
        # Get status
        #----------------------------------------
        lret.value = caio.AioGetCntStatus(self.id, self.cnt_channel, ctypes.byref(cnt_status))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Count Stop : AioGetCntStatus = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        cnt_status_string = self.GetCntStatusString(cnt_status)
        #----------------------------------------
        # Display the status
        #----------------------------------------
        self.ui.textbox_cnt_status_var.set(f"{cnt_status.value:08x}H ({cnt_status_string})")
        #----------------------------------------
        # Display the message that count stop is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Count Stop : Successful completion")

    #========================================
    # 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()                     # Number of channels
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        file_name = "SamplingData.csv"                     # Sampling data output file name

        #----------------------------------------
        # Open file
        #----------------------------------------
        try:
            file = open(file_name, 'w')
        except:
            self.ui.textbox_return_string_var.set("Output Acquired Data to File : open = file open error.")
            return
        #----------------------------------------
        # Get the number of channels
        #----------------------------------------
        lret.value = caio.AioGetAiChannels(self.id, ctypes.byref(ai_channels))
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Output Acquired Data to File : AioGetAiChannels = {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 > 0:
            #--------------------
            # Repeat the process up to the total sampling count
            #--------------------
            for i in range(self.sampling_count):
                #--------------------
                # Generate display string
                #--------------------
                text_string = f"{(i + 1):d},"
                #--------------------
                # Repeat the process for the specified number of channels
                #--------------------
                for j in range(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 = f"Output Acquired Data to File : Save data to \"{file_name}\"."
        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 InternalSyncCounterSampling
    #----------------------------------------
    instance = InternalSyncCounterSampling()
    instance.run()

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