#================================================================
#================================================================
# API-AIO(WDM)
# Sampling synchronization between 2 devices using synchronization bus sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import caio
from CommonFunction import *
#----------------------------------------
# Declaration of global variables
#----------------------------------------
g_master_sampling_data = None    # [Master] Pointer to sampling data storage area
g_slave_sampling_data = None     # [Slave]  Pointer to sampling data storage area


#========================================
# Function name    SamplingMasterCallBackProc
# 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
#========================================
def SamplingMasterCallBackProc(id, ai_event, wParam, lParam, Param):
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_long()                          # For return code
    master_ai_sampling_count = ctypes.c_long()      # [Master] Sampling Count
    master_ai_status = ctypes.c_long()              # [Master] Status
    master_ai_channels = ctypes.c_short()           # [Master] Number of channels
    global g_master_sampling_data             		# [Master] Pointer to sampling data storage area

    #----------------------------------------
    # Event that device operation end
    #----------------------------------------
    if ai_event == caio.AIOM_AIE_END:
        #----------------------------------------
        # [Master] Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(master_ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Create the status string
        #----------------------------------------
        master_ai_status_string = GetStatusString(master_ai_status)
        #----------------------------------------
        # [Master] Get the current sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(master_ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Get the number of channels
        #----------------------------------------
        lret.value = caio.AioGetAiChannels(id, ctypes.byref(master_ai_channels))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAiChannels Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Allocate the array for storing conversion data
        #----------------------------------------
        try:
            master_ai_data_type = ctypes.c_float * (master_ai_sampling_count.value * master_ai_channels.value)
            g_master_sampling_data = master_ai_data_type()
        except:
            text_buf  = "Sampling(Master)"
            text_buf += f"\nDevice Operation End Event Process : Failed to allocate the array for storing data"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Get the sampling data
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingDataEx(id, ctypes.byref(master_ai_sampling_count), g_master_sampling_data)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAiSamplingDataEx Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            #----------------------------------------
            # [Master] Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if g_master_sampling_data is not None:
                g_master_sampling_data = None
            return
        #----------------------------------------
        # [Master] Open file
        #----------------------------------------
        try:
            master_file = open("./SamplingDataMaster.csv", 'w')
        except:
            text_buf  = "Sampling(Master)"
            text_buf += f"\nDevice Operation End Event Process : Failed to create the file"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            #----------------------------------------
            # [Master] Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if g_master_sampling_data is not None:
                g_master_sampling_data = None
            return
        #----------------------------------------
        # [Master] Create sampling data for file output
        #----------------------------------------
        #--------------------
        # Repeat the process up to the number of sampling data
        #--------------------
        for i in range(0, int(master_ai_sampling_count.value)):
            #--------------------
            # Generate the string for sampling data
            #--------------------
            text_string = f"{(i + 1):5d},"
            #--------------------
            # Repeat the process for the specified number of channels
            #--------------------
            for j in range(0, master_ai_channels.value):
                text_string += f" {g_master_sampling_data[i * master_ai_channels.value + j]:10.5f}"
                #--------------------
                # Add newline character for the last channel
                #--------------------
                if j == master_ai_channels.value - 1:
                    text_string += "\n"
                #--------------------
                # Add comma for channels other than the last channel
                #--------------------
                else:
                    text_string += ","
            #----------------------------------------
            # [Master] Write data
            #----------------------------------------
            master_file.write(text_string)
        #----------------------------------------
        # [Master] Close file
        #----------------------------------------
        master_file.close()
        #----------------------------------------
        # [Master] Release the array for storing conversion data if it has been allocated
        #----------------------------------------
        if g_master_sampling_data is not None:
            g_master_sampling_data = None
        #----------------------------------------
        # [Master] Display the sampling count, status
        #----------------------------------------
        text_buf  = "Sampling(Master)"
        text_buf += "\nDevice Operation End Event Process : Successful completion"
        text_buf += f"\nSampling Count = {master_ai_sampling_count.value:<8d} Status = 0x{master_ai_status.value:08x}({master_ai_status_string:})"
        text_buf += "\nSave data to \"SamplingDataMaster.csv\"."
        SamplingMasterPrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that overflow
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_OFERR:
        #----------------------------------------
        # [Master] Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(master_ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nOverflow Occurrence Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Create the status string
        #----------------------------------------
        master_ai_status_string = GetStatusString(master_ai_status)
        #----------------------------------------
        # [Master] Get the current sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(master_ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nOverflow Occurrence Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Display the sampling count, status
        #----------------------------------------
        text_buf  = "Sampling(Master)"
        text_buf += "\nOverflow Occurrence Process : Successful completion"
        text_buf += f"\nSampling Count = {master_ai_sampling_count.value:<8d} Status = 0x{master_ai_status.value:08x}({master_ai_status_string:})"
        text_buf += "\n"
        SamplingMasterPrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that sampling clock error
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_SCERR:
        #----------------------------------------
        # [Master] Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(master_ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nSampling Clock Error Occurrence Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Create the status string
        #----------------------------------------
        master_ai_status_string = GetStatusString(master_ai_status)
        #----------------------------------------
        # [Master] Get the current sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(master_ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nSampling Clock Error Occurrence Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Display the sampling count, status
        #----------------------------------------
        text_buf  = "Sampling(Master)"
        text_buf += "\nSampling Clock Error Occurrence Process : Successful completion"
        text_buf += f"\nSampling Count = {master_ai_sampling_count.value:<8d} Status = 0x{master_ai_status.value:08x}({master_ai_status_string:})"
        text_buf += "\n"
        SamplingMasterPrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that AD conversion error
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_ADERR:
        #----------------------------------------
        # [Master] Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(master_ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nAD Conversion Error Occurrence Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Create the status string
        #----------------------------------------
        master_ai_status_string = GetStatusString(master_ai_status)
        #----------------------------------------
        # [Master] Get the current sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(master_ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Master)"
            text_buf += f"\nAD Conversion Error Occurrence Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingMasterPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Master] Display the sampling count, status
        #----------------------------------------
        text_buf  = "Sampling(Master)"
        text_buf += "\nAD Conversion Error Occurrence Process : Successful completion"
        text_buf += f"\nSampling Count = {master_ai_sampling_count.value:<8d} Status = 0x{master_ai_status.value:08x}({master_ai_status_string:})"
        text_buf += "\n"
        SamplingMasterPrintOnMultiLines(text_buf, 4)
    return


#========================================
# 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
#========================================
def SamplingSlaveCallBackProc(id, ai_event, wParam, lParam, Param):
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_long()                          # For return code
    slave_ai_sampling_count = ctypes.c_long()       # [Slave] Sampling count
    slave_ai_status = ctypes.c_long()               # [Slave] Status
    slave_ai_channels = ctypes.c_short()            # [Slave] Number of channels
    global g_slave_sampling_data              		# [Slave] Pointer to sampling data storage area

    #----------------------------------------
    # Event that AD conversion start
    #----------------------------------------
    if ai_event == caio.AIOM_AIE_START:
        #----------------------------------------
        # [Slave] Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(slave_ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nEvent that AD conversion start Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Create the status string
        #----------------------------------------
        slave_ai_status_string = GetStatusString(slave_ai_status)
        #----------------------------------------
        # [Slave] Get the current sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(slave_ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nEvent that AD conversion start Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Display the sampling count, status
        #----------------------------------------
        text_buf  = "Sampling(Slave)"
        text_buf += "\nEvent that AD conversion start Process : Successful completion"
        text_buf += f"\nSampling Count = {slave_ai_sampling_count.value:<8d} Status = 0x{slave_ai_status.value:08x}({slave_ai_status_string:})"
        text_buf += "\n"
        SamplingSlavePrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that device operation end
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_END:
        #----------------------------------------
        # [Slave] Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(slave_ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Create the status string
        #----------------------------------------
        slave_ai_status_string = GetStatusString(slave_ai_status)
        #----------------------------------------
        # [Slave] Get the current sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(slave_ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Get the number of channels
        #----------------------------------------
        lret.value = caio.AioGetAiChannels(id, ctypes.byref(slave_ai_channels))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAiChannels Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Allocate the array for storing conversion data
        #----------------------------------------
        try:
            slave_ai_data_type = ctypes.c_float * (slave_ai_sampling_count.value * slave_ai_channels.value)
            g_slave_sampling_data = slave_ai_data_type()
        except:
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nDevice Operation End Event Process : Failed to allocate the array for storing data"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Get the sampling data
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingDataEx(id, ctypes.byref(slave_ai_sampling_count), g_slave_sampling_data)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAiSamplingDataEx Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            #----------------------------------------
            # [Slave] Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if g_slave_sampling_data is not None:
                g_slave_sampling_data = None
            return
        #----------------------------------------
        # [Slave] Open file
        #----------------------------------------
        try:
            slave_file = open("./SamplingDataSlave.csv", 'w')
        except:
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nDevice Operation End Event Process : Failed to create the file"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            #----------------------------------------
            # [Slave] Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if g_slave_sampling_data is not None:
                g_slave_sampling_data = None
            return
        #----------------------------------------
        # [Slave] Create sampling data for file output
        #----------------------------------------
        #--------------------
        # Repeat the process up to the number of sampling data
        #--------------------
        for i in range(0, int(slave_ai_sampling_count.value)):
            #--------------------
            # Generate the string for sampling data
            #--------------------
            text_string = f"{(i + 1):5d},"
            #--------------------
            # Repeat the process for the specified number of channels
            #--------------------
            for j in range(0, slave_ai_channels.value):
                text_string += f" {g_slave_sampling_data[i * slave_ai_channels.value + j]:10.5f}"
                #--------------------
                # Add newline character for the last channel
                #--------------------
                if j == slave_ai_channels.value - 1:
                    text_string += "\n"
                #--------------------
                # Add comma for channels other than the last channel
                #--------------------
                else:
                    text_string += ","
            #----------------------------------------
            # [Slave] Write data
            #----------------------------------------
            slave_file.write(text_string)
        #----------------------------------------
        # [Slave] Close file
        #----------------------------------------
        slave_file.close()
        #----------------------------------------
        # [Slave] Release the array for storing conversion data if it has been allocated
        #----------------------------------------
        if g_slave_sampling_data is not None:
            g_slave_sampling_data = None
        #----------------------------------------
        # [Slave] Display the sampling count, status
        #----------------------------------------
        text_buf  = "Sampling(Slave)"
        text_buf += "\nDevice Operation End Event Process : Successful completion"
        text_buf += f"\nSampling Count = {slave_ai_sampling_count.value:<8d} Status = 0x{slave_ai_status.value:08x}({slave_ai_status_string:})"
        text_buf += "\nSave data to \"SamplingDataSlave.csv\"."
        SamplingSlavePrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that overflow
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_OFERR:
        #----------------------------------------
        # [Slave] Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(slave_ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nOverflow Occurrence Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Create the status string
        #----------------------------------------
        slave_ai_status_string = GetStatusString(slave_ai_status)
        #----------------------------------------
        # [Slave] Get the current sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(slave_ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nOverflow Occurrence Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Display the sampling count, status
        #----------------------------------------
        text_buf  = "Sampling(Slave)"
        text_buf += "\nOverflow Occurrence Process : Successful completion"
        text_buf += f"\nSampling Count = {slave_ai_sampling_count.value:<8d} Status = 0x{slave_ai_status.value:08x}({slave_ai_status_string:})"
        text_buf += "\n"
        SamplingSlavePrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that sampling clock error
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_SCERR:
        #----------------------------------------
        # [Slave] Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(slave_ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nSampling Clock Error Occurrence Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Create the status string
        #----------------------------------------
        slave_ai_status_string = GetStatusString(slave_ai_status)
        #----------------------------------------
        # [Slave] Get the current sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(slave_ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nSampling Clock Error Occurrence Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Display the sampling count, status
        #----------------------------------------
        text_buf  = "Sampling(Slave)"
        text_buf += "\nSampling Clock Error Occurrence Process : Successful completion"
        text_buf += f"\nSampling Count = {slave_ai_sampling_count.value:<8d} Status = 0x{slave_ai_status.value:08x}({slave_ai_status_string:})"
        text_buf += "\n"
        SamplingSlavePrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that AD conversion error
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_ADERR:
        #----------------------------------------
        # [Slave] Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(slave_ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nAD Conversion Error Occurrence Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Create the status string
        #----------------------------------------
        slave_ai_status_string = GetStatusString(slave_ai_status)
        #----------------------------------------
        # [Slave] Get the current sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(slave_ai_sampling_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf  = "Sampling(Slave)"
            text_buf += f"\nAD Conversion Error Occurrence Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            SamplingSlavePrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # [Slave] Display the sampling count, status
        #----------------------------------------
        text_buf  = "Sampling(Slave)"
        text_buf += "\nAD Conversion Error Occurrence Process : Successful completion"
        text_buf += f"\nSampling Count = {slave_ai_sampling_count.value:<8d} Status = 0x{slave_ai_status.value:08x}({slave_ai_status_string:})"
        text_buf += "\n"
        SamplingSlavePrintOnMultiLines(text_buf, 4)
    return


psampling_master_ai_callback = caio.PAIO_AI_CALLBACK(SamplingMasterCallBackProc)
psampling_slave_ai_callback = caio.PAIO_AI_CALLBACK(SamplingSlaveCallBackProc)


#========================================
# Function name    main
# Parameter        None
# Details          Function that performs main processing
# Return value     None
#========================================
def main():
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_long()                          # For return code
    master_id = ctypes.c_short()                    # [Master] ID for device access
    slave_id = ctypes.c_short()                     # [Slave]  ID for device access
    master_ai_range = ctypes.c_short()              # [Master] Range
    slave_ai_range = ctypes.c_short()               # [Slave]  Range
    master_ai_input_method = ctypes.c_short()       # [Master] Input method
    slave_ai_input_method = ctypes.c_short()        # [Slave]  Input method
    master_ai_channels = ctypes.c_short()           # [Master] Number of channels
    slave_ai_channels = ctypes.c_short()            # [Slave]  Number of channels
    master_ai_sampling_clock = ctypes.c_float()     # [Master] Sampling clock period
    master_ai_stop_times = ctypes.c_long()          # [Master] Stop times
    master_ai_status = ctypes.c_long()              # [Master] Status
    slave_ai_status = ctypes.c_long()               # [Slave]  Status
    master_ai_sampling_count = ctypes.c_long()      # [Master] Sampling count
    slave_ai_sampling_count = ctypes.c_long()       # [Slave]  Sampling count
    global g_master_sampling_data                   # [Master] Pointer to sampling data storage area
    global g_slave_sampling_data                    # [Slave]  Pointer to sampling data storage area
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the sampling count, status in the callback
    
    #----------------------------------------
    # Initialize the variable
    #----------------------------------------
    g_info_flag.value = 0
    #----------------------------------------
    # Lock
    #----------------------------------------
    g_lock.acquire()
    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # [Master] Get setting parameters
        #----------------------------------------
        #--------------------
        # [Master] Get the range value
        #--------------------
        lret.value = caio.AioGetAiRange(master_id, 0, ctypes.byref(master_ai_range))
        if lret.value != 0:
            master_ai_range_string = "-"
        else:
            master_ai_range_string = GetRangeString(master_ai_range)
        #--------------------
        # [Master] Get the input method
        #--------------------
        lret.value = caio.AioGetAiInputMethod(master_id, ctypes.byref(master_ai_input_method))
        if lret.value != 0:
            master_ai_input_method_string = "-"
        else:
            master_ai_input_method_string = GetInputMethodString(master_ai_input_method)
        #--------------------
        # [Master] Get the number of channels
        #--------------------
        lret.value = caio.AioGetAiChannels(master_id, ctypes.byref(master_ai_channels))
        if lret.value != 0:
            master_ai_channels_string = "-"
        else:
            master_ai_channels_string = f"{master_ai_channels.value}"
        #--------------------
        # [Master] Get the sampling clock period
        #--------------------
        lret.value = caio.AioGetAiSamplingClock(master_id, ctypes.byref(master_ai_sampling_clock))
        if lret.value != 0:
            master_ai_sampling_clock_string = "-"
        else:
            master_ai_sampling_clock_string = f"{master_ai_sampling_clock.value}[usec]"
        #--------------------
        # [Master] Get the stop times
        #--------------------
        lret.value = caio.AioGetAiStopTimes(master_id, ctypes.byref(master_ai_stop_times))
        if lret.value != 0:
            master_ai_stop_times_string = "-"
        else:
            master_ai_stop_times_string = f"{master_ai_stop_times.value}"
        #----------------------------------------
        # [Slave] Get setting parameters
        #----------------------------------------
        #--------------------
        # [Slave] Get the range value
        #--------------------
        lret.value = caio.AioGetAiRange(slave_id, 0, ctypes.byref(slave_ai_range))
        if lret.value != 0:
            slave_ai_range_string = "-"
        else:
            slave_ai_range_string = GetRangeString(slave_ai_range)
        #--------------------
        # [Slave] Get the input method
        #--------------------
        lret.value = caio.AioGetAiInputMethod(slave_id, ctypes.byref(slave_ai_input_method))
        if lret.value != 0:
            slave_ai_input_method_string = "-"
        else:
            slave_ai_input_method_string = GetInputMethodString(slave_ai_input_method)
        #--------------------
        # [Slave] Get the number of channels
        #--------------------
        lret.value = caio.AioGetAiChannels(slave_id, ctypes.byref(slave_ai_channels))
        if lret.value != 0:
            slave_ai_channels_string = "-"
        else:
            slave_ai_channels_string = f"{slave_ai_channels.value}"
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print("====================")
        print("Sampling(Master)")
        print("====================")
        print(f"Range                 : {master_ai_range_string}")
        print(f"Input Method          : {master_ai_input_method_string}")
        print(f"Number of Channels    : {master_ai_channels_string}")
        print(f"Sampling Clock Period : {master_ai_sampling_clock_string}")
        print(f"Stop Times            : {master_ai_stop_times_string}")
        print("====================")
        print("Sampling(Slave)")
        print("====================")
        print(f"Range                 : {slave_ai_range_string}")
        print(f"Input Method          : {slave_ai_input_method_string}")
        print(f"Number of Channels    : {slave_ai_channels_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print("1 : Initialize")
        print("2 : AioResetDevice")
        print("3 : Analog Input Set")
        print("4 : Sampling Set")
        print("5 : Sync Operation Set")
        print("6 : Sampling Start")
        print("7 : Get Status")
        print("8 : Sampling Stop")
        print("9 : AioExit")
        print("q : Quit")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Unlock
        #----------------------------------------
        g_lock.release()
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Lock
        #----------------------------------------
        g_lock.acquire()
        #----------------------------------------
        # If the sampling count, status are displayed in the callback, output eight new line
        #----------------------------------------
        if g_info_flag.value == 1:
            print("\n\n\n\n\n\n\n")
            g_info_flag.value = 0
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # Initialize
        #--------------------
        if buf == "1":
            print("\n----------------------------------------")
            print("Start the initialize")
            print("----------------------------------------")
            #----------------------------------------
            # [Master] Input the device name
            #----------------------------------------
            print("Please input the device name of Sampling(Master) : ", end='', flush=True)
            #----------------------------------------
            # Unlock
            #----------------------------------------
            g_lock.release()
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # Lock
            #----------------------------------------
            g_lock.acquire()
            #----------------------------------------
            # If the sampling count, status are displayed in the callback, output eight new line
            #----------------------------------------
            if g_info_flag.value == 1:
                print("\n\n\n\n\n\n\n")
                g_info_flag.value = 0
            #----------------------------------------
            # [Master] Initialization
            #----------------------------------------
            lret.value = caio.AioInit(buf.encode(), ctypes.byref(master_id))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioInit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            #----------------------------------------
            # [Slave] Input the device name
            #----------------------------------------
            print("Please input the device name of Sampling(Slave) : ", end='', flush=True)
            #----------------------------------------
            # Unlock
            #----------------------------------------
            g_lock.release()
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # Lock
            #----------------------------------------
            g_lock.acquire()
            #----------------------------------------
            # If the sampling count, status are displayed in the callback, output eight new line
            #----------------------------------------
            if g_info_flag.value == 1:
                print("\n\n\n\n\n\n\n")
                g_info_flag.value = 0
            #----------------------------------------
            # [Slave] Initialization
            #----------------------------------------
            lret.value = caio.AioInit(buf.encode(), ctypes.byref(slave_id))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioInit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # AioResetDevice
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # [Master] Reset the device
            #----------------------------------------
            lret.value = caio.AioResetDevice(master_id)
            caio.AioGetErrorString(lret, error_buf)
            print("\nSampling(Master)")
            print(f"AioResetDevice Ret = {lret.value} {error_buf.value.decode('sjis')}")
            #----------------------------------------
            # [Slave] Reset the device
            #----------------------------------------
            lret.value = caio.AioResetDevice(slave_id)
            caio.AioGetErrorString(lret, error_buf)
            print("\nSampling(Slave)")
            print(f"AioResetDevice Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Analog Input Set
        #--------------------
        elif buf == "3":
            print("\n----------------------------------------")
            print("Start the analog input set")
            print("----------------------------------------")
            #----------------------------------------
            # [Master] Input the range
            #----------------------------------------
            print("----------------------------------------")
            print("Parameter(Range)")
            print("----------------------------------------")
            print(" 0 : +/-10[V]\t\t 50 : 0-10[V]")
            print(" 1 : +/-5[V]\t\t 51 : 0-5[V]")
            print(" 2 : +/-2.5[V]\t\t 53 : 0-2.5[V]")
            print(" 3 : +/-1.25[V]\t\t 54 : 0-1.25[V]")
            print("               \t\t100 : 0-20[mA]")
            print("               \t\t101 : 4-20[mA]")
            print("               \t\t102 : +/-20[mA]")
            print("               \t\t150 : 1-5[V]")
            while True:
                print("Please input the range of Sampling(Master) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the sampling count, status are displayed in the callback, output eight new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            master_ai_range = ctypes.c_short(int(buf))
            #----------------------------------------
            # [Master] Set the range
            #----------------------------------------
            lret.value = caio.AioSetAiRangeAll(master_id, master_ai_range)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiRangeAll Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                master_ai_range_string = GetRangeString(master_ai_range)
                print(f"Range = {master_ai_range.value}({master_ai_range_string})")
            else:
                print("")
                continue
            #----------------------------------------
            # [Master] Input the input method
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Input method)")
            print("----------------------------------------")
            print("0 : Single-end input")
            print("1 : Differential input")
            while True:
                print("Please input the input method of Sampling(Master) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the sampling count, status are displayed in the callback, output eight new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            master_ai_input_method = ctypes.c_short(int(buf))
            #----------------------------------------
            # [Master] Set the input method
            #----------------------------------------
            lret.value = caio.AioSetAiInputMethod(master_id, master_ai_input_method)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiInputMethod Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                master_ai_input_method_string = GetInputMethodString(master_ai_input_method)
                print(f"Input Method = {master_ai_input_method.value}({master_ai_input_method_string})")
            else:
                print("")
                continue
            #----------------------------------------
            # [Master] Display the message that analog input set is completed
            #----------------------------------------
            print("\nSampling(Master)")
            print("Analog Input Set : Successful completion\n")
            #----------------------------------------
            # [Slave] Input the range
            #----------------------------------------
            print("----------------------------------------")
            print("Parameter(Range)")
            print("----------------------------------------")
            print(" 0 : +/-10[V]\t\t 50 : 0-10[V]")
            print(" 1 : +/-5[V]\t\t 51 : 0-5[V]")
            print(" 2 : +/-2.5[V]\t\t 53 : 0-2.5[V]")
            print(" 3 : +/-1.25[V]\t\t 54 : 0-1.25[V]")
            print("               \t\t100 : 0-20[mA]")
            print("               \t\t101 : 4-20[mA]")
            print("               \t\t102 : +/-20[mA]")
            print("               \t\t150 : 1-5[V]")
            while True:
                print("Please input the range of Sampling(Slave) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the sampling count, status are displayed in the callback, output eight new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            slave_ai_range = ctypes.c_short(int(buf))
            #----------------------------------------
            # [Slave] Set the range
            #----------------------------------------
            lret.value = caio.AioSetAiRangeAll(slave_id, slave_ai_range)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiRangeAll Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                slave_ai_range_string = GetRangeString(slave_ai_range)
                print(f"Range = {slave_ai_range.value}({slave_ai_range_string})")
            else:
                print("")
                continue
            #----------------------------------------
            # [Slave] Input the input method
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Input method)")
            print("----------------------------------------")
            print("0 : Single-end input")
            print("1 : Differential input")
            while True:
                print("Please input the input method of Sampling(Slave) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the sampling count, status are displayed in the callback, output eight new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            slave_ai_input_method = ctypes.c_short(int(buf))
            #----------------------------------------
            # [Slave] Set the input method
            #----------------------------------------
            lret.value = caio.AioSetAiInputMethod(slave_id, slave_ai_input_method)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiInputMethod Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                slave_ai_input_method_string = GetInputMethodString(slave_ai_input_method)
                print(f"Input Method = {slave_ai_input_method.value}({slave_ai_input_method_string})")
            else:
                print("")
                continue
            #----------------------------------------
            # [Slave] Display the message that analog input set is completed
            #----------------------------------------
            print("\nSampling(Slave)")
            print("Analog Input Set : Successful completion\n")
        #--------------------
        # Sampling Set
        #--------------------
        elif buf == "4":
            print("\n----------------------------------------")
            print("Start the sampling set")
            print("----------------------------------------")
            #----------------------------------------
            # [Master]  Input the number of channels
            #----------------------------------------
            while True:
                print("Please input the number of channels of Sampling(Master) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the sampling count, status are displayed in the callback, output eight new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            master_ai_channels = ctypes.c_short(int(buf))
            #----------------------------------------
            # [Master] Set the number of channels
            #----------------------------------------
            lret.value = caio.AioSetAiChannels(master_id, master_ai_channels)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiChannels Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Number of Channels = {master_ai_channels.value}")
            else:
                print("")
                continue
            #----------------------------------------
            # [Master] Set the data storage memory type to FIFO
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiMemoryType(master_id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Set Error")
                print(f"AioSetAiMemoryType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Set the sampling start condition to Software
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiStartTrigger(master_id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Set Error")
                print(f"AioSetAiStartTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Set the clock type to Internal Clock
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiClockType(master_id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Set Error")
                print(f"AioSetAiClockType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Input the sampling clock period
            #----------------------------------------
            print("")
            while True:
                print("Please input the sampling clock period of Sampling(Master)[usec] : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the sampling count, status are displayed in the callback, output eight new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 0):
                    continue
                break
            master_ai_sampling_clock = ctypes.c_float(float(buf))
            #----------------------------------------
            # [Master] Set the sampling clock period
            #----------------------------------------
            lret.value = caio.AioSetAiSamplingClock(master_id, master_ai_sampling_clock)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiSamplingClock Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Sampling Clock Period = {master_ai_sampling_clock.value}[usec]")
            else:
                print("")
                continue
            #----------------------------------------
            # [Master] 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(master_id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Set Error")
                print(f"AioSetAiStopTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Input the stop times
            #----------------------------------------
            print("")
            while True:
                print("Please input the stop times of Sampling(Master) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the sampling count, status are displayed in the callback, output eight new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            masterai_stop_times = ctypes.c_long(int(buf))
            #----------------------------------------
            # [Master] Set the stop times
            #----------------------------------------
            lret.value = caio.AioSetAiStopTimes(master_id, masterai_stop_times)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiStopTimes Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Stop Times = {masterai_stop_times.value}")
            else:
                print("")
                continue
            #----------------------------------------
            # [Master] Set the event factor to '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)
            #----------------------------------------
            lret.value = caio.AioSetAiCallBackProc(master_id, psampling_master_ai_callback, caio.AIE_END | caio.AIE_OFERR | caio.AIE_SCERR | caio.AIE_ADERR, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Set Error")
                print(f"AioSetAiCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Display the message that sampling set is completed
            #----------------------------------------
            print("\nSampling(Master)")
            print("Sampling Set : Successful completion\n")
            #----------------------------------------
            # [Slave] Input the number of channels
            #----------------------------------------
            while True:
                print("Please input the number of channels of Sampling(Slave) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the sampling count, status are displayed in the callback, output eight new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            slave_ai_channels = ctypes.c_short(int(buf))
            #----------------------------------------
            # [Slave] Set the number of channels
            #----------------------------------------
            lret.value = caio.AioSetAiChannels(slave_id, slave_ai_channels)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiChannels Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Number of Channels = {slave_ai_channels.value}")
            else:
                print("")
                continue
            #----------------------------------------
            # [Slave] Set the data storage memory type to FIFO
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiMemoryType(slave_id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Set Error")
                print(f"AioSetAiMemoryType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] 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(slave_id, 10)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Set Error")
                print(f"AioSetAiStartTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Set the clock type to Event controller output
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiClockType(slave_id, 10)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Set Error")
                print(f"AioSetAiClockType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Set the sampling stop condition to Event controller output
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiStopTrigger(slave_id, 10)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Set Error")
                print(f"AioSetAiStopTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Set the event factor to '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)
            #----------------------------------------
            lret.value = caio.AioSetAiCallBackProc(slave_id, psampling_slave_ai_callback, (caio.AIE_START | caio.AIE_END | caio.AIE_OFERR | caio.AIE_SCERR | caio.AIE_ADERR), 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Set Error")
                print(f"AioSetAiCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Display the message that sampling set is completed
            #----------------------------------------
            print("\nSampling(Slave)")
            print("Sampling Set : Successful completion\n")
        #--------------------
        # Sync Operation Set
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # [Master] Event Controller Setting: Connect Analog input internal clock signal to Synchronization bus master signal 1
            #----------------------------------------
            lret.value = caio.AioSetEcuSignal(master_id, caio.AIOECU_DEST_MASTER1, caio.AIOECU_SRC_AI_CLK)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sync Operation Set Error")
                print(f"AioSetEcuSignal Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Event Controller Setting: Connect Ai software start signal to Synchronization bus master signal 2
            #----------------------------------------
            lret.value = caio.AioSetEcuSignal(master_id, caio.AIOECU_DEST_MASTER2, caio.AIOECU_SRC_START)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sync Operation Set Error")
                print(f"AioSetEcuSignal Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Event Controller Setting: Connect Analog input signal that data of the specified sampling times have been converted (No delay) to Synchronization bus master signal 3
            #----------------------------------------
            lret.value = caio.AioSetEcuSignal(master_id, caio.AIOECU_DEST_MASTER3, caio.AIOECU_SRC_AI_STOP)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sync Operation Set Error")
                print(f"AioSetEcuSignal Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Display the message that sync operation set is completed
            #----------------------------------------
            print("\nSampling(Master)")
            print("Sync Operation Set : Successful completion")
            #----------------------------------------
            # [Slave] Event Controller Setting: Connect Synchronization bus slave signal 1 to Analog input sampling clock
            #----------------------------------------
            lret.value = caio.AioSetEcuSignal(slave_id, caio.AIOECU_DEST_AI_CLK, caio.AIOECU_SRC_SLAVE1)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sync Operation Set Error")
                print(f"AioSetEcuSignal Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Event Controller Setting: Connect Synchronization bus slave signal 2 to Analog input converting start signal
            #----------------------------------------
            lret.value = caio.AioSetEcuSignal(slave_id, caio.AIOECU_DEST_AI_START, caio.AIOECU_SRC_SLAVE2)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sync Operation Set Error")
                print(f"AioSetEcuSignal Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Event Controller Setting: Connect Synchronization bus slave signal 3 to Analog input converting stop signal
            #----------------------------------------
            lret.value = caio.AioSetEcuSignal(slave_id, caio.AIOECU_DEST_AI_STOP, caio.AIOECU_SRC_SLAVE3)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sync Operation Set Error")
                print(f"AioSetEcuSignal Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Display the message that sync operation set is completed
            #----------------------------------------
            print("\nSampling(Slave)")
            print("Sync Operation Set : Successful completion\n")
        #--------------------
        # Sampling Start
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # [Slave] Clear the memory
            #----------------------------------------
            lret.value = caio.AioResetAiMemory(slave_id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Start Error")
                print(f"AioResetAiMemory Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Clear the status
            #----------------------------------------
            lret.value = caio.AioResetAiStatus(slave_id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Start Error")
                print(f"AioResetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Start sampling
            #----------------------------------------
            lret.value = caio.AioStartAi(slave_id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Start Error")
                print(f"AioStartAi Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Display the message that sampling start is completed
            #----------------------------------------
            print("\nSampling(Slave)")
            print("Sampling Start : Successful completion")
            #----------------------------------------
            # [Master] Clear the memory
            #----------------------------------------
            lret.value = caio.AioResetAiMemory(master_id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Start Error")
                print(f"AioResetAiMemory Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Clear the status
            #----------------------------------------
            lret.value = caio.AioResetAiStatus(master_id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Start Error")
                print(f"AioResetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Start sampling
            #----------------------------------------
            lret.value = caio.AioStartAi(master_id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Start Error")
                print(f"AioStartAi Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Display the message that sampling start is completed
            #----------------------------------------
            print("\nSampling(Master)")
            print("Sampling Start : Successful completion\n")
        #--------------------
        # Get Status
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # [Master] Get the sampling count
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingCount(master_id, ctypes.byref(master_ai_sampling_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Get Status Error")
                print(f"AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Get the status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(master_id, ctypes.byref(master_ai_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Get Status Error")
                print(f"AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Create the status string
            #----------------------------------------
            master_ai_status_string = GetStatusString(master_ai_status)
            #----------------------------------------
            # [Master] Display the message that get status is completed
            #----------------------------------------
            print("\nSampling(Master)")
            print("Get Status : Successful completion")
            #----------------------------------------
            # [Master] Display the sampling count, status
            #----------------------------------------
            print(f"Sampling Count = {master_ai_sampling_count.value:<8d} Status = 0x{master_ai_status.value:08x}({master_ai_status_string:})")
            #----------------------------------------
            # [Slave] Get the sampling count
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingCount(slave_id, ctypes.byref(slave_ai_sampling_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Get Status Error")
                print(f"AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Get the status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(slave_id, ctypes.byref(slave_ai_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Get Status Error")
                print(f"AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Create the status string
            #----------------------------------------
            slave_ai_status_string = GetStatusString(slave_ai_status)
            #----------------------------------------
            # [Slave] Display the message that get status is completed
            #----------------------------------------
            print("\nSampling(Slave)")
            print("Get Status : Successful completion")
            #----------------------------------------
            # [Slave] Display the sampling count, status
            #----------------------------------------
            print(f"Sampling Count = {slave_ai_sampling_count.value:<8d} Status = 0x{slave_ai_status.value:08x}({slave_ai_status_string:})")
            print("")
        #--------------------
        # Sampling Stop
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # [Master] Stop sampling
            #----------------------------------------
            lret.value = caio.AioStopAi(master_id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Stop Error")
                print(f"AioStopAi Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Get the status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(master_id, ctypes.byref(master_ai_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Stop Error")
                print(f"AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] Create the status string
            #----------------------------------------
            master_ai_status_string = GetStatusString(master_ai_status)
            #----------------------------------------
            # [Master] Get the current sampling count
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingCount(master_id, ctypes.byref(master_ai_sampling_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Master)")
                print("Sampling Stop Error")
                print(f"AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Master] When the sampling count of the data acquired this time is 1 or more
            #----------------------------------------
            if master_ai_sampling_count.value > 0:
                #----------------------------------------
                # [Master] Allocate the array for storing conversion data
                #----------------------------------------
                try:
                    master_ai_data_type = ctypes.c_float * (master_ai_sampling_count.value * master_ai_channels.value)
                    g_master_sampling_data = master_ai_data_type()
                except:
                    print("\nSampling(Master)")
                    print("Sampling Stop Error")
                    print("Failed to allocate the array for storing data\n")
                    continue
                #----------------------------------------
                # [Master] Get the sampling data
                #----------------------------------------
                lret.value = caio.AioGetAiSamplingDataEx(master_id, ctypes.byref(master_ai_sampling_count), g_master_sampling_data)
                if lret.value != 0:
                    caio.AioGetErrorString(lret, error_buf)
                    print("\nSampling(Master)")
                    print("Sampling Stop Error")
                    print(f"AioGetAiSamplingDataEx Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    #----------------------------------------
                    # [Master] Release the array for storing conversion data if it has been allocated
                    #----------------------------------------
                    if g_master_sampling_data is not None:
                        g_master_sampling_data = None
                    continue
                #----------------------------------------
                # [Master] Open file
                #----------------------------------------
                try:
                    master_file = open("./SamplingDataMaster.csv", 'w')
                except:
                    print("\nSampling(Master)")
                    print("Sampling Stop Error")
                    print("Failed to create the file\n")
                    #----------------------------------------
                    # [Master] Release the array for storing conversion data if it has been allocated
                    #----------------------------------------
                    if g_master_sampling_data is not None:
                        g_master_sampling_data = None
                    continue
                #----------------------------------------
                # [Master] Create sampling data for file output
                #----------------------------------------
                #--------------------
                # Repeat the process up to the number of sampling data
                #--------------------
                for i in range(0, int(master_ai_sampling_count.value)):
                    #--------------------
                    # Generate the string
                    #--------------------
                    text_string = f"{(i + 1):5d},"
                    #--------------------
                    # Repeat the process for the specified number of channels
                    #--------------------
                    for j in range(0, master_ai_channels.value):
                        text_string += f" {g_master_sampling_data[i * master_ai_channels.value + j]:10.5f}"
                        #--------------------
                        # Add newline character for the last channel
                        #--------------------
                        if j == master_ai_channels.value - 1:
                            text_string += "\n"
                        #--------------------
                        # Add comma for channels other than the last channel
                        #--------------------
                        else:
                            text_string += ","
                    #----------------------------------------
                    # [Master] Write data
                    #----------------------------------------
                    master_file.write(text_string)
                #----------------------------------------
                # [Master] Close file
                #----------------------------------------
                master_file.close()
                #----------------------------------------
                # [Master] Release the array for storing conversion data if it has been allocated
                #----------------------------------------
                if g_master_sampling_data is not None:
                    g_master_sampling_data = None
                #----------------------------------------
                # [Master] Display the message that sampling stop is completed
                #----------------------------------------
                print("\nSampling(Master)")
                print("Sampling Stop : Successful completion")
                #----------------------------------------
                # [Master] Display the sampling count, status
                #----------------------------------------
                print(f"Sampling Count = {master_ai_sampling_count.value:<8d} Status = 0x{master_ai_status.value:08x}({master_ai_status_string:})")
                #----------------------------------------
                # [Master] Display the message that file output is completed
                #----------------------------------------
                print("Save data to \"SamplingDataMaster.csv\".")
            #----------------------------------------
            # [Master] When the sampling count of the data acquired this time is 0 or less
            #----------------------------------------
            else:
                #----------------------------------------
                # [Master] Display the message that sampling stop is completed
                #----------------------------------------
                print("\nSampling(Master)")
                print("Sampling Stop : Successful completion")
            #----------------------------------------
            # [Slave] Stop sampling
            #----------------------------------------
            lret.value = caio.AioStopAi(slave_id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Stop Error")
                print(f"AioStopAi Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Get the status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(slave_id, ctypes.byref(slave_ai_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Stop Error")
                print(f"AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] Create the status string
            #----------------------------------------
            slave_ai_status_string = GetStatusString(slave_ai_status)
            #----------------------------------------
            # [Slave] Get the current sampling count
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingCount(slave_id, ctypes.byref(slave_ai_sampling_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling(Slave)")
                print("Sampling Stop Error")
                print(f"AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # [Slave] When the sampling count of the data acquired this time is 1 or more
            #----------------------------------------
            if slave_ai_sampling_count.value > 0:
                #----------------------------------------
                # [Slave] Allocate the array for storing conversion data
                #----------------------------------------
                try:
                    slave_ai_data_type = ctypes.c_float * (slave_ai_sampling_count.value * slave_ai_channels.value)
                    g_slave_sampling_data = slave_ai_data_type()
                except:
                    print("\nSampling(Slave)")
                    print("Sampling Stop Error")
                    print("Failed to allocate the array for storing data\n")
                    continue
                #----------------------------------------
                # [Slave] Get the sampling data
                #----------------------------------------
                lret.value = caio.AioGetAiSamplingDataEx(slave_id, ctypes.byref(slave_ai_sampling_count), g_slave_sampling_data)
                if lret.value != 0:
                    caio.AioGetErrorString(lret, error_buf)
                    print("\nSampling(Slave)")
                    print("Sampling Stop Error")
                    print(f"AioGetAiSamplingDataEx Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                    #----------------------------------------
                    # [Slave] Release the array for storing conversion data if it has been allocated
                    #----------------------------------------
                    if g_slave_sampling_data is not None:
                        g_slave_sampling_data = None
                    continue
                #----------------------------------------
                # [Slave] Open file
                #----------------------------------------
                try:
                    slave_file = open("./SamplingDataSlave.csv", 'w')
                except:
                    print("\nSampling(Slave)")
                    print("Sampling Stop Error")
                    print("Failed to create the file\n")
                    #----------------------------------------
                    # [Slave] Release the array for storing conversion data if it has been allocated
                    #----------------------------------------
                    if g_slave_sampling_data is not None:
                        g_slave_sampling_data = None
                    continue
                #----------------------------------------
                # [Slave] Create sampling data for file output
                #----------------------------------------
                #--------------------
                # Repeat the process up to the number of sampling data
                #--------------------
                for i in range(0, int(slave_ai_sampling_count.value)):
                    #--------------------
                    # Generate the string
                    #--------------------
                    text_string = f"{(i + 1):5d},"
                    #--------------------
                    # Repeat the process for the specified number of channels
                    #--------------------
                    for j in range(0, slave_ai_channels.value):
                        text_string += f" {g_slave_sampling_data[i * slave_ai_channels.value + j]:10.5f}"
                        #--------------------
                        # Add newline character for the last channel
                        #--------------------
                        if j == slave_ai_channels.value - 1:
                            text_string += "\n"
                        #--------------------
                        # Add comma for channels other than the last channel
                        #--------------------
                        else:
                            text_string += ","
                    #----------------------------------------
                    # [Slave] Write data
                    #----------------------------------------
                    slave_file.write(text_string)
                #----------------------------------------
                # [Slave] Close file
                #----------------------------------------
                slave_file.close()
                #----------------------------------------
                # [Slave] Release the array for storing conversion data if it has been allocated
                #----------------------------------------
                if g_slave_sampling_data is not None:
                    g_slave_sampling_data = None
                #----------------------------------------
                # [Slave] Display the message that sampling stop is completed
                #----------------------------------------
                print("\nSampling(Slave)")
                print("Sampling Stop : Successful completion")
                #----------------------------------------
                # [Slave] Display the sampling count, status
                #----------------------------------------
                print(f"Sampling Count = {slave_ai_sampling_count.value:<8d} Status = 0x{slave_ai_status.value:08x}({slave_ai_status_string:})")
                #----------------------------------------
                # [Slave] Display the message that file output is completed
                #----------------------------------------
                print("Save data to \"SamplingDataSlave.csv\".\n")
            #----------------------------------------
            # [Slave] When the sampling count of the data acquired this time is 0 or less
            #----------------------------------------
            else:
                #----------------------------------------
                # [Slave] Display the message that sampling stop is completed
                #----------------------------------------
                print("\nSampling(Slave)")
                print("Sampling Stop : Successful completion\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # [Master] Exit process
            #----------------------------------------
            lret.value = caio.AioExit(master_id)
            caio.AioGetErrorString(lret, error_buf)
            print("\nSampling(Master)")
            print(f"AioExit Ret = {lret.value} {error_buf.value.decode('sjis')}")
            #----------------------------------------
            # [Slave] Exit process
            #----------------------------------------
            lret.value = caio.AioExit(slave_id)
            caio.AioGetErrorString(lret, error_buf)
            print("\nSampling(Slave)")
            print(f"AioExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Quit
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    #----------------------------------------
    # [Master] Exit process
    #----------------------------------------
    caio.AioExit(master_id)
    #----------------------------------------
    # [Slave] Exit process
    #----------------------------------------
    caio.AioExit(slave_id)
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_lock.release()
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


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