#================================================================
#================================================================
# API-AIO(WDM)
# Device internal synchronization (Generating/Sampling) sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import math
import caio
from CommonFunction import *
#----------------------------------------
# Declaration of global variables
#----------------------------------------
g_generating_data = None    # Output data
g_sampling_data = None      # Pointer to sampling data storage area


#========================================
# Function name    GeneratingMasterCallBackProc
# Parameter        id          Id get by AioInit
# Parameter        ao_event    The event that occurred
# Parameter        wParam      Parameter passed from driver
# Parameter        lParam      Parameter unique to each event
# Parameter        Param       Parameter specified in the AioSetAoCallBackProc function
# Details          Function registered with the AioSetAoCallBackProc function
#                  This function is called when an event occurs
# Return value     None
#========================================
def GeneratingMasterCallBackProc(id, ao_event, wParam, lParam, Param):
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_long()                          # For return code
    ao_generating_count = ctypes.c_long()           # Generating count
    ao_status = ctypes.c_long()                     # Anolog output status

    #----------------------------------------
    # Event that device operation end
    #----------------------------------------
    if ao_event == caio.AIOM_AOE_END:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = "Generating(Master)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            GeneratingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ao_status_string = GetAoStatusString(ao_status)
        #----------------------------------------
        # Get the generating count
        #----------------------------------------
        lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = "Generating(Master)"
            text_buf += f"\nDevice Operation End Event Process : AioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            GeneratingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Display the generating count, status
        #----------------------------------------
        text_buf = "Generating(Master)"
        text_buf += "\nDevice Operation End Event Process : Successful completion"
        text_buf += f"\nGenerating Count = {ao_generating_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string})"
        text_buf += "\n"
        GeneratingPrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that sampling clock error
    #----------------------------------------
    elif ao_event == caio.AIOM_AOE_SCERR:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = "Generating(Master)"
            text_buf += f"\nSampling Clock Error Occurrence Process : AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            GeneratingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ao_status_string = GetAoStatusString(ao_status)
        #----------------------------------------
        # Get the generating count
        #----------------------------------------
        lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = "Generating(Master)"
            text_buf += f"\nSampling Clock Error Occurrence Process : AioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            GeneratingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Display the generating count, status
        #----------------------------------------
        text_buf = "Generating(Master)"
        text_buf += "\nSampling Clock Error Occurrence Process : Successful completion"
        text_buf += f"\nGenerating Count = {ao_generating_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string})"
        text_buf += "\n"
        GeneratingPrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that DA conversion error
    #----------------------------------------
    elif ao_event == caio.AIOM_AOE_DAERR:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = "Generating(Master)"
            text_buf += f"\nDA Conversion Error Occurrence Process : AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            GeneratingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ao_status_string = GetAoStatusString(ao_status)
        #----------------------------------------
        # Get the generating count
        #----------------------------------------
        lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = "Generating(Master)"
            text_buf += f"\nDA Conversion Error Occurrence Process : AioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            text_buf += "\n\n"
            GeneratingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Display the generating count, status
        #----------------------------------------
        text_buf = "Generating(Master)"
        text_buf += "\nDA Conversion Error Occurrence Process : Successful completion"
        text_buf += f"\nGenerating Count = {ao_generating_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string})"
        text_buf += "\n"
        GeneratingPrintOnMultiLines(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
    ai_sampling_count = ctypes.c_long()             # Sampling count
    ai_status = ctypes.c_long()                     # Analog input status
    ai_channels = ctypes.c_short()                  # Number of analog input channels
    global g_sampling_data                          # Pointer to sampling data storage area

    #----------------------------------------
    # Event that AD conversion start
    #----------------------------------------
    if ai_event == caio.AIOM_AIE_START:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetAiStatusString(ai_status)
        #----------------------------------------
        # Get the sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Display the sampling count, status
        #----------------------------------------
        text_buf = "Sampling(Slave)"
        text_buf += "\nEvent that AD conversion start Process : Successful completion"
        text_buf += f"\nSampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        text_buf += "\n"
        SamplingPrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that device operation end
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_END:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetAiStatusString(ai_status)
        #----------------------------------------
        # Get the sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Get the number of channels
        #----------------------------------------
        lret.value = caio.AioGetAiChannels(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Allocate the array for storing conversion data
        #----------------------------------------
        try:
            ai_data_type = ctypes.c_float * (ai_sampling_count.value * ai_channels.value)
            g_sampling_data = 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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Get the sampling data
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingDataEx(id, ctypes.byref(ai_sampling_count), g_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"
            SamplingPrintOnMultiLines(text_buf, 4)
            #----------------------------------------
            # Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if g_sampling_data is not None:
                g_sampling_data = None
            return
        #----------------------------------------
        # Open file
        #----------------------------------------
        try:
            file = open("./SamplingData.csv", 'w')
        except:
            text_buf = "Sampling(Slave)"
            text_buf += f"\nDevice Operation End Event Process : Failed to create the file"
            text_buf += "\n\n"
            SamplingPrintOnMultiLines(text_buf, 4)
            #----------------------------------------
            # Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if g_sampling_data is not None:
                g_sampling_data = None
            return
        #----------------------------------------
        # Create sampling data for file output
        #----------------------------------------
        #--------------------
        # Repeat the process up to the number of sampling data
        #--------------------
        for i in range(0, int(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, ai_channels.value):
                text_string += f" {g_sampling_data[i * ai_channels.value + j]:10.5f}"
                #--------------------
                # Add newline character for the last channel
                #--------------------
                if j == ai_channels.value - 1:
                    text_string += "\n"
                #--------------------
                # Add comma for channels other than the last channel
                #--------------------
                else:
                    text_string += ","
            #----------------------------------------
            # Write data
            #----------------------------------------
            file.write(text_string)
        #----------------------------------------
        # Close file
        #----------------------------------------
        file.close()
        #----------------------------------------
        # Release the array for storing conversion data if it has been allocated
        #----------------------------------------
        if g_sampling_data is not None:
            g_sampling_data = None
        #----------------------------------------
        # Display the sampling count, status
        #----------------------------------------
        text_buf = "Sampling(Slave)"
        text_buf += "\nDevice Operation End Event Process : Successful completion"
        text_buf += f"\nSampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        text_buf += "\nSave data to \"SamplingData.csv\"."
        SamplingPrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that overflow
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_OFERR:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetAiStatusString(ai_status)
        #----------------------------------------
        # Get the sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Display the sampling count, status
        #----------------------------------------
        text_buf = "Sampling(Slave)"
        text_buf += "\nOverflow Occurrence Process : Successful completion"
        text_buf += f"\nSampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        text_buf += "\n"
        SamplingPrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that sampling clock error
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_SCERR:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetAiStatusString(ai_status)
        #----------------------------------------
        # Get the sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Display the sampling count, status
        #----------------------------------------
        text_buf = "Sampling(Slave)"
        text_buf += "\nSampling Clock Error Occurrence Process : Successful completion"
        text_buf += f"\nSampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        text_buf += "\n"
        SamplingPrintOnMultiLines(text_buf, 4)
    #----------------------------------------
    # Event that AD conversion error
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_ADERR:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetAiStatusString(ai_status)
        #----------------------------------------
        # Get the sampling count
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(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"
            SamplingPrintOnMultiLines(text_buf, 4)
            return
        #----------------------------------------
        # Display the sampling count, status
        #----------------------------------------
        text_buf = "Sampling(Slave)"
        text_buf += "\nAD Conversion Error Occurrence Process : Successful completion"
        text_buf += f"\nSampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        text_buf += "\n"
        SamplingPrintOnMultiLines(text_buf, 4)
    return


pao_callback = caio.PAIO_AO_CALLBACK(GeneratingMasterCallBackProc)
pai_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
    id = ctypes.c_short()                           # ID for device access
    ao_range = ctypes.c_short()                     # Analog output range
    ao_channels = ctypes.c_short()                  # Number of analog output channels
    ao_generating_clock = ctypes.c_float()          # Generating clock
    ao_generating_times = ctypes.c_long(1000)       # Number of generating for the output data
    ai_range = ctypes.c_short()                     # Analog input range
    ai_input_method = ctypes.c_short()              # Input method
    ai_channels = ctypes.c_short()                  # Number of analog input channels
    ao_generating_count = ctypes.c_long()           # Generating count
    ai_sampling_count = ctypes.c_long()             # Sampling count
    ao_status = ctypes.c_long()                     # Analog output status
    ai_status = ctypes.c_long()                     # Analog input status
    initialized = 0                                 # Whether the board has been initialized
    global g_generating_data                        # Output data
    global g_sampling_data                          # Pointer to sampling data storage area
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the generating count, 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
        #----------------------------------------
        #--------------------
        # Get the range value
        #--------------------
        lret.value = caio.AioGetAoRange(id, 0, ctypes.byref(ao_range))
        if lret.value != 0:
            ao_range_string = "-"
        else:
            ao_range_string = GetAoRangeString(ao_range)
        #--------------------
        # Get the number of channels
        #--------------------
        lret.value = caio.AioGetAoChannels(id, ctypes.byref(ao_channels))
        if lret.value != 0:
            ao_channels_string = "-"
        else:
            ao_channels_string = f"{ao_channels.value}"
        #--------------------
        # Get the generating clock period
        #--------------------
        lret.value = caio.AioGetAoSamplingClock(id, ctypes.byref(ao_generating_clock))
        if lret.value != 0:
            ao_generating_clock_string = "-"
        else:
            ao_generating_clock_string = f"{ao_generating_clock.value}[usec]"
        #--------------------
        # Get the number of generating for the output data
        #--------------------
        if initialized == 0:
            ao_generating_times_string = "-"
        else:
            ao_generating_times_string = f"{ao_generating_times.value}"
        #----------------------------------------
        # [Slave] Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the range value
        #--------------------
        lret.value = caio.AioGetAiRange(id, 0, ctypes.byref(ai_range))
        if lret.value != 0:
            ai_range_string = "-"
        else:
            ai_range_string = GetAiRangeString(ai_range)
        #--------------------
        # Get the input method
        #--------------------
        lret.value = caio.AioGetAiInputMethod(id, ctypes.byref(ai_input_method))
        if lret.value != 0:
            ai_input_method_string = "-"
        else:
            ai_input_method_string = GetInputMethodString(ai_input_method)
        #--------------------
        # Get the number of channels
        #--------------------
        lret.value = caio.AioGetAiChannels(id, ctypes.byref(ai_channels))
        if lret.value != 0:
            ai_channels_string = "-"
        else:
            ai_channels_string = f"{ai_channels.value}"
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print("====================")
        print("Generating(Master)")
        print("====================")
        print(f"Range                   : {ao_range_string}")
        print(f"Number of Channels      : {ao_channels_string}")
        print(f"Generating Clock Period : {ao_generating_clock_string}")
        print(f"Generating Times        : {ao_generating_times_string}")
        print("====================")
        print("Sampling(Slave)")
        print("====================")
        print(f"Range                   : {ai_range_string}")
        print(f"Input Method            : {ai_input_method_string}")
        print(f"Number of Channels      : {ai_channels_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print(" 1 : AioInit")
        print(" 2 : AioResetDevice")
        print(" 3 : Analog I/O Set")
        print(" 4 : Generating/Sampling Set")
        print(" 5 : Sync Operation Set")
        print(" 6 : Output Data Set")
        print(" 7 : Generating/Sampling Start")
        print(" 8 : Get Status")
        print(" 9 : Generating/Sampling Stop")
        print("10 : 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 generating count, 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
        #----------------------------------------
        #--------------------
        # AioInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Input the device name
            #----------------------------------------
            print("\nPlease input the device name : ", end='', flush=True)
            #----------------------------------------
            # Unlock
            #----------------------------------------
            g_lock.release()
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # Lock
            #----------------------------------------
            g_lock.acquire()
            #----------------------------------------
            # If the generating count, 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
            #----------------------------------------
            # Initialization
            #----------------------------------------
            lret.value = caio.AioInit(buf.encode(), ctypes.byref(id))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioInit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            #----------------------------------------
            # Set the initialization flag
            #----------------------------------------
            if lret.value == 0:
                initialized = 1
            else:
                initialized = 0
        #--------------------
        # AioResetDevice
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # Reset the device
            #----------------------------------------
            lret.value = caio.AioResetDevice(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioResetDevice Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Analog I/O Set
        #--------------------
        elif buf == "3":
            print("\n----------------------------------------")
            print("Start the analog I/O set")
            print("----------------------------------------")
            #----------------------------------------
            # Input the analog output 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\t150 : 1-5[V]")
            while True:
                print("Please input the range of Generating(Master) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the generating count, 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
            ao_range = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the analog output range
            #----------------------------------------
            lret.value = caio.AioSetAoRangeAll(id, ao_range)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAoRangeAll Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                ao_range_string = GetAoRangeString(ao_range)
                print(f"Range = {ao_range.value}({ao_range_string})")
            else:
                print("")
                continue
            #----------------------------------------
            # Display the message that analog output set is completed
            #----------------------------------------
            print("\nGenerating(Master)")
            print("Analog Output Set : Successful completion\n")
            #----------------------------------------
            # Input the analog input 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 generating count, 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
            ai_range = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the analog input range
            #----------------------------------------
            lret.value = caio.AioSetAiRangeAll(id, ai_range)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiRangeAll Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                ai_range_string = GetAiRangeString(ai_range)
                print(f"Range = {ai_range.value}({ai_range_string})")
            else:
                print("")
                continue
            #----------------------------------------
            # 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 generating count, 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
            ai_input_method = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the input method
            #----------------------------------------
            lret.value = caio.AioSetAiInputMethod(id, ai_input_method)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiInputMethod Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                ai_input_method_string = GetInputMethodString(ai_input_method)
                print(f"Input Method = {ai_input_method.value}({ai_input_method_string})")
            else:
                print("")
                continue
            #----------------------------------------
            # Display the message that analong input set is completed
            #----------------------------------------
            print("\nSampling(Slave)")
            print("Analog Input Set : Successful completion\n")
        #--------------------
        # Generating/Sampling Set
        #--------------------
        elif buf == "4":
            print("\n----------------------------------------")
            print("Start the generating/sampling set")
            print("----------------------------------------")
            #----------------------------------------
            # Input the number of analog output channels
            #----------------------------------------
            while True:
                print("Please input the number of channels of Generating(Master) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the generating count, 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
            ao_channels = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the number of analog output channels
            #----------------------------------------
            lret.value = caio.AioSetAoChannels(id, ao_channels)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAoChannels Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Number of Channels = {ao_channels.value}")
            else:
                print("")
                continue
            #----------------------------------------
            # Set the data storage memory type to FIFO
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoMemoryType(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Set Error")
                print(f"AioSetAoMemoryType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the generating start condition to Software
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoStartTrigger(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Set Error")
                print(f"AioSetAoStartTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the clock type to Internal Clock
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoClockType(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Set Error")
                print(f"AioSetAoClockType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Input the generating clock period
            #----------------------------------------
            print("")
            while True:
                print("Please input the generating clock period of Generating(Master)[usec] : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the generating count, 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
            ao_generating_clock = ctypes.c_float(float(buf))
            #----------------------------------------
            # Set the generating clock period
            #----------------------------------------
            lret.value = caio.AioSetAoSamplingClock(id, ao_generating_clock)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAoSamplingClock Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Generating Clock Period = {ao_generating_clock.value}[usec]")
            else:
                print("")
                continue
            #----------------------------------------
            # Set the generating stop condition to Stop conversion by the specified times
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoStopTrigger(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Set Error")
                print(f"AioSetAoStopTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the event factor to 'Event that device operation end', 'Event that sampling clock error' and 'Event that DA conversion error'.
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoCallBackProc(id, pao_callback, (caio.AOE_END | caio.AOE_SCERR | caio.AOE_DAERR), 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Set Error")
                print(f"AioSetAoCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Input the generating times
            #----------------------------------------
            print("")
            while True:
                print("Please input the generating times of Generating(Master) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the generating count, 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
            ao_generating_times = ctypes.c_long(int(buf))
            print(f"\nGenerating Times = {ao_generating_times.value}")
            #----------------------------------------
            # Display the message that generating set is completed
            #----------------------------------------
            print("\nGenerating(Master)")
            print("Generating Set : Successful completion")
            #----------------------------------------
            # Input the number of analog input channels
            #----------------------------------------
            print("")
            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 generating count, 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
            ai_channels = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the number of analog input channels
            #----------------------------------------
            lret.value = caio.AioSetAiChannels(id, 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 = {ai_channels.value}")
            else:
                print("")
                continue
            #----------------------------------------
            # Set the data storage memory type to FIFO
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiMemoryType(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
            #----------------------------------------
            # 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(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
            #----------------------------------------
            # Set the clock type to Event controller output
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiClockType(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
            #----------------------------------------
            # 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(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
            #----------------------------------------
            # 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(id, pai_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
            #----------------------------------------
            # Display the message that sampling set is completed
            #----------------------------------------
            print("\nSampling(Slave)")
            print("Sampling Set : Successful completion\n")
        #--------------------
        # Sync Operation Set
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Event Controller Setting: Connect Analog output internal clock signal to Analog input sampling clock
            #----------------------------------------
            lret.value = caio.AioSetEcuSignal(id, caio.AIOECU_DEST_AI_CLK, caio.AIOECU_SRC_AO_CLK)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSync Operation Set Error")
                print(f"AioSetEcuSignal Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Event Controller Setting: Connect Ao software start signal to Analog input converting start signal
            #----------------------------------------
            lret.value = caio.AioSetEcuSignal(id, caio.AIOECU_DEST_AI_START, caio.AIOECU_SRC_START)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSync Operation Set Error")
                print(f"AioSetEcuSignal Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Event Controller Setting: Connect Analog output signal that data of the specified sampling times have been output (FIFO) to Analog input converting stop signal
            #----------------------------------------
            lret.value = caio.AioSetEcuSignal(id, caio.AIOECU_DEST_AI_STOP, caio.AIOECU_SRC_AO_STOP_FIFO)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSync Operation Set Error")
                print(f"AioSetEcuSignal Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that sync operation set is completed
            #----------------------------------------
            print("\nSync Operation Set : Successful completion\n")
        #--------------------
        # Output Data Set
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # Allocate the array for storing output data
            #----------------------------------------
            #--------------------
            # Release the array for storing output data if it has been allocated
            #--------------------
            if g_generating_data is not None:
                g_generating_data = None
            #--------------------
            # Allocate the array for storing output data
            #--------------------
            try:
                g_generating_data_type = ctypes.c_float * (ao_generating_times.value * ao_channels.value)
                g_generating_data = g_generating_data_type()
            except:
                print("\nGenerating(Master)")
                print("Output Data Set Error")
                print("Failed to allocate the array for storing data\n")
                continue
            #----------------------------------------
            # Create analog output data: sine waveform
            #----------------------------------------
            gain, offset = GetSineCoefficient(ao_range)
            for i in range(0, ao_generating_times.value):
                for j in range(0, ao_channels.value):
                    g_generating_data[i * ao_channels.value + j] = ctypes.c_float(gain * math.sin(2 * 3.14159265358979 * i / ao_generating_times.value + 3.14159265358979 / 2 * (j % 4)) + offset)
            #----------------------------------------
            # Set analog output data
            #----------------------------------------
            lret.value = caio.AioSetAoSamplingDataEx(id, ao_generating_times, g_generating_data)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Output Data Set Error")
                print(f"AioSetAoSamplingDataEx Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Open file
            #----------------------------------------
            try:
                file = open("./GeneratingData.csv", 'w')
            except:
                #----------------------------------------
                # Release the array for storing output data if it has been allocated
                #----------------------------------------
                if g_generating_data is not None:
                    g_generating_data = None
                print("\nGenerating(Master)")
                print("Output Data Set Error")
                print("Failed to create the file\n")
                continue
            #----------------------------------------
            # Create file
            #----------------------------------------
            for i in range(0, ao_generating_times.value):
                #--------------------
                # Generate the string
                #--------------------
                text_string = f"{i + 1:5d},"
                #--------------------
                # Repeat the process for the specified number of channels
                #--------------------
                for j in range(0, ao_channels.value):
                    text_string += f" {g_generating_data[i * ao_channels.value + j]:10.5f}"
                    #--------------------
                    # Add newline character for the last channel
                    #--------------------
                    if j == (ao_channels.value - 1):
                        text_string += "\n"
                    #--------------------
                    # Add comma for channels other than the last channel
                    #--------------------
                    else:
                        text_string += ","
                #----------------------------------------
                # Write data
                #----------------------------------------
                file.write(text_string)
            #----------------------------------------
            # Close file
            #----------------------------------------
            file.close()
            #----------------------------------------
            # Display the message that output data set is completed
            #----------------------------------------
            print("\nGenerating(Master)")
            print("Output Data Set : Successful completion\n")
        #--------------------
        # Generating/Sampling Start
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Clear the memory
            #----------------------------------------
            lret.value = caio.AioResetAiMemory(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
            #----------------------------------------
            # Clear the analog input status
            #----------------------------------------
            lret.value = caio.AioResetAiStatus(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
            #----------------------------------------
            # Start sampling
            #----------------------------------------
            lret.value = caio.AioStartAi(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
            #----------------------------------------
            # Display the message that sampling start is completed
            #----------------------------------------
            print("\nSampling(Slave)")
            print("Sampling Start : Successful completion")
            #----------------------------------------
            # Clear the analog output status
            #----------------------------------------
            lret.value = caio.AioResetAoStatus(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Start Error")
                print(f"AioResetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Start generating
            #----------------------------------------
            lret.value = caio.AioStartAo(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Start Error")
                print(f"AioStartAo Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that generating start is completed
            #----------------------------------------
            print("\nGenerating(Master)")
            print("Generating Start : Successful completion\n")
        #--------------------
        # Get Status
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Get the generating count
            #----------------------------------------
            lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Get Status Error")
                print(f"AioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Get the analog output status
            #----------------------------------------
            lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Get Status Error")
                print(f"AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ao_status_string = GetAoStatusString(ao_status)
            #----------------------------------------
            # Display the message that get status is completed
            #----------------------------------------
            print("\nGenerating(Master)")
            print("Get Status : Successful completion")
            print(f"Generating Count = {ao_generating_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string:})")
            #----------------------------------------
            # Get the sampling count
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(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
            #----------------------------------------
            # Get the analog input status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(id, ctypes.byref(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
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ai_status_string = GetAiStatusString(ai_status)
            #----------------------------------------
            # Display the message that get status is completed
            #----------------------------------------
            print("\nSampling(Slave)")
            print("Get Status : Successful completion")
            print(f"Sampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})\n")
        #--------------------
        # Generating/Sampling Stop
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # Stop generating
            #----------------------------------------
            lret.value = caio.AioStopAo(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Stop Error")
                print(f"AioStopAo Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Get the analog output status
            #----------------------------------------
            lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Stop Error")
                print(f"AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ao_status_string = GetAoStatusString(ao_status)
            #----------------------------------------
            # Get the generating count
            #----------------------------------------
            lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating(Master)")
                print("Generating Stop Error")
                print(f"AioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that generating stop is completed
            #----------------------------------------
            print("\nGenerating(Master)")
            print("Generating Stop : Successful completion")
            print(f"Generating Count = {ao_generating_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string:})")
            #----------------------------------------
            # Stop sampling
            #----------------------------------------
            lret.value = caio.AioStopAi(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
            #----------------------------------------
            # Get the analog input status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(id, ctypes.byref(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
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ai_status_string = GetAiStatusString(ai_status)
            #----------------------------------------
            # Get the sampling count
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(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
            #----------------------------------------
            # When the sampling count of the data acquired this time is 1 or more
            #----------------------------------------
            if ai_sampling_count.value > 0:
                #----------------------------------------
                # Allocate the array for storing conversion data
                #----------------------------------------
                try:
                    ai_data_type = ctypes.c_float * (ai_sampling_count.value * ai_channels.value)
                    g_sampling_data = ai_data_type()
                except:
                    print("\nSampling(Slave)")
                    print("Sampling Stop Error")
                    print("Failed to allocate the array for storing data\n")
                    continue
                #----------------------------------------
                # Get the sampling data
                #----------------------------------------
                lret.value = caio.AioGetAiSamplingDataEx(id, ctypes.byref(ai_sampling_count), g_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")
                    #----------------------------------------
                    # Release the array for storing conversion data if it has been allocated
                    #----------------------------------------
                    if g_sampling_data is not None:
                        g_sampling_data = None
                    continue
                #----------------------------------------
                # Open file
                #----------------------------------------
                try:
                    file = open("./SamplingData.csv", 'w')
                except:
                    print("\nSampling(Slave)")
                    print("Sampling Stop Error")
                    print("Failed to create the file\n")
                    #----------------------------------------
                    # Release the array for storing conversion data if it has been allocated
                    #----------------------------------------
                    if g_sampling_data is not None:
                        g_sampling_data = None
                    continue
                #----------------------------------------
                # Create sampling data for file output
                #----------------------------------------
                #--------------------
                # Repeat the process up to the number of sampling data
                #--------------------
                for i in range(0, int(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, ai_channels.value):
                        text_string += f" {g_sampling_data[i * ai_channels.value + j]:10.5f}"
                        #--------------------
                        # Add newline character for the last channel
                        #--------------------
                        if j == ai_channels.value - 1:
                            text_string += "\n"
                        #--------------------
                        # Add comma for channels other than the last channel
                        #--------------------
                        else:
                            text_string += ","
                    #----------------------------------------
                    # Write data
                    #----------------------------------------
                    file.write(text_string)
                #----------------------------------------
                # Close file
                #----------------------------------------
                file.close()
                #----------------------------------------
                # Release the array for storing conversion data if it has been allocated
                #----------------------------------------
                if g_sampling_data is not None:
                    g_sampling_data = None
                #----------------------------------------
                # Display the message that sampling stop is completed
                #----------------------------------------
                print("\nSampling(Slave)")
                print("Sampling Stop : Successful completion")
                print(f"Sampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})")
                print("Save data to \"SamplingData.csv\".\n")
            #----------------------------------------
            # When the sampling count of the data acquired this time is 0 or less
            #----------------------------------------
            else:
                #----------------------------------------
                # Display the message that sampling stop is completed
                #----------------------------------------
                print("\nSampling(Slave)")
                print("Sampling Stop : Successful completion\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # Release the array for storing output data if it has been allocated
            #----------------------------------------
            if g_generating_data is not None:
                g_generating_data = None
            #----------------------------------------
            # Exit process
            #----------------------------------------
            lret.value = caio.AioExit(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            #----------------------------------------
            # Set the initialization flag
            #----------------------------------------
            if lret.value == 0:
                initialized = 0
        #--------------------
        # Quit
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    #----------------------------------------
    # Release the array for storing output data if it has been allocated
    #----------------------------------------
    if g_generating_data is not None:
        g_generating_data = None
    #----------------------------------------
    # Exit process
    #----------------------------------------
    caio.AioExit(id)
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_lock.release()
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


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