#================================================================
#================================================================
# API-AIO(WDM)
# Infinite sampling using device buffer sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import os
import caio
from CommonFunction import *
from SamplingSetting import *
#----------------------------------------
# Declaration of global variables
#----------------------------------------
g_total_sampling_count = 0    # Total sampling count


#========================================
# Function name    CallBackProc
# Parameter        id          Id get by AioInit
# Parameter        ai_event    The event that occurred
# Parameter        wParam      Parameter passed from driver
# Parameter        lParam      Parameter unique to each event
# Parameter        Param       Parameter specified in the AioSetAiCallBackProc function
# Details          Function registered with the AioSetAiCallBackProc function
#                  This function is called when an event occurs
# Return value     None
#========================================
def CallBackProc(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()                     # Status
    ai_channels = ctypes.c_short()                  # Number of channels
    global g_total_sampling_count                   # Total sampling count

    #----------------------------------------
    # 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 = f"\nEvent that AD conversion start Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetStatusString(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 = f"\nEvent that AD conversion start Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Display the total sampling count, sampling count, status
        #----------------------------------------
        text_buf = f"\nTotal Sampling Count = {g_total_sampling_count:<8d} Sampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        PrintOnOneLine(text_buf)
    #----------------------------------------
    # Event that the specified number of data are stored
    #----------------------------------------
    elif ai_event == caio.AIOM_AIE_DATA_NUM:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAiStatus(id, ctypes.byref(ai_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nEvent that the specified number of data are stored Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetStatusString(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 = f"\nEvent that the specified number of data are stored Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            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 = f"\nEvent that the specified number of data are stored Process : AioGetAiChannels Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Allocate the array for storing conversion data
        #----------------------------------------
        try:
            ai_data_type = ctypes.c_float * (ai_sampling_count.value * ai_channels.value)
            ai_data = ai_data_type()
        except:
            text_buf = "\nEvent that the specified number of data are stored Process : Failed to allocate the array for storing data"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Get the sampling data
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingDataEx(id, ctypes.byref(ai_sampling_count), ai_data)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nEvent that the specified number of data are stored Process : AioGetAiSamplingDataEx Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            #----------------------------------------
            # Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if ai_data is not None:
                ai_data = None
            return
        #----------------------------------------
        # Open file
        #----------------------------------------
        try:
            file = open("./SamplingData.csv", 'a')
        except:
            text_buf = "\nEvent that the specified number of data are stored Process : Failed to create the file"
            PrintOnOneLine(text_buf)
            #----------------------------------------
            # Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if ai_data is not None:
                ai_data = None
            return
        #----------------------------------------
        # Create file
        #----------------------------------------
        for i in range(0, ai_sampling_count.value):
            #--------------------
            # Generate the string
            #--------------------
            text_string = f"{g_total_sampling_count + i + 1:5d},"
            #--------------------
            # Repeat the process for the specified number of channels
            #--------------------
            for j in range(0, ai_channels.value):
                text_string += f" {ai_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()
        #----------------------------------------
        # Update the total sampling count
        #----------------------------------------
        g_total_sampling_count += ai_sampling_count.value
        #----------------------------------------
        # Release the array for storing conversion data if it has been allocated
        #----------------------------------------
        if ai_data is not None:
            ai_data = None
        #----------------------------------------
        # Display the total sampling count, sampling count, status
        #----------------------------------------
        text_buf = f"\nTotal Sampling Count = {g_total_sampling_count:<8d} Sampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        PrintOnOneLine(text_buf)
    #----------------------------------------
    # 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 = f"\nDevice Operation End Event Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetStatusString(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 = f"\nDevice Operation End Event Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            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 = f"\nDevice Operation End Event Process : AioGetAiChannels Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Allocate the array for storing conversion data
        #----------------------------------------
        try:
            ai_data_type = ctypes.c_float * (ai_sampling_count.value * ai_channels.value)
            ai_data = ai_data_type()
        except:
            text_buf = "\nDevice Operation End Event Process : Failed to allocate the array for storing data"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Get the sampling data
        #----------------------------------------
        lret.value = caio.AioGetAiSamplingDataEx(id, ctypes.byref(ai_sampling_count), ai_data)
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDevice Operation End Event Process : AioGetAiSamplingDataEx Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            #----------------------------------------
            # Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if ai_data is not None:
                ai_data = None
            return
        #----------------------------------------
        # Open file
        #----------------------------------------
        try:
            file = open("./SamplingData.csv", 'a')
        except:
            text_buf = "\nDevice Operation End Event Process : Failed to create the file"
            PrintOnOneLine(text_buf)
            #----------------------------------------
            # Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if ai_data is not None:
                ai_data = None
            return
        #----------------------------------------
        # Create file
        #----------------------------------------
        for i in range(0, ai_sampling_count.value):
            #--------------------
            # Generate the string
            #--------------------
            text_string = f"{g_total_sampling_count + i + 1:5d},"
            #--------------------
            # Repeat the process for the specified number of channels
            #--------------------
            for j in range(0, ai_channels.value):
                text_string += f" {ai_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()
        #----------------------------------------
        # Update the total sampling count
        #----------------------------------------
        g_total_sampling_count += ai_sampling_count.value
        #----------------------------------------
        # Release the array for storing conversion data if it has been allocated
        #----------------------------------------
        if ai_data is not None:
            ai_data = None
        #----------------------------------------
        # Display the total sampling count, sampling count, status
        #----------------------------------------
        text_buf = f"\nTotal Sampling Count = {g_total_sampling_count:<8d} Sampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        PrintOnOneLine(text_buf)
    #----------------------------------------
    # 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 = f"\nOverflow Occurrence Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetStatusString(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 = f"\nOverflow Occurrence Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Display the total sampling count, sampling count, status
        #----------------------------------------
        text_buf = f"\nTotal Sampling Count = {g_total_sampling_count:<8d} Sampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        PrintOnOneLine(text_buf)
    #----------------------------------------
    # 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 = f"\nSampling Clock Error Occurrence Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetStatusString(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 = f"\nSampling Clock Error Occurrence Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Display the total sampling count, sampling count, status
        #----------------------------------------
        text_buf = f"\nTotal Sampling Count = {g_total_sampling_count:<8d} Sampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        PrintOnOneLine(text_buf)
    #----------------------------------------
    # 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 = f"\nAD Conversion Error Occurrence Process : AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ai_status_string = GetStatusString(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 = f"\nAD Conversion Error Occurrence Process : AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Display the total sampling count, sampling count, status
        #----------------------------------------
        text_buf = f"\nTotal Sampling Count = {g_total_sampling_count:<8d} Sampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})"
        PrintOnOneLine(text_buf)
    return


pai_callback = caio.PAIO_AI_CALLBACK(CallBackProc)


#========================================
# 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
    ai_range = ctypes.c_short()                     # Range
    ai_input_method = ctypes.c_short()              # Input method
    ai_channels = ctypes.c_short()                  # Number of channels
    ai_event_sampling_times = ctypes.c_long()       # Event sampling times
    ai_status = ctypes.c_long()                     # Status
    ai_sampling_count = ctypes.c_long()             # Sampling count
    global g_total_sampling_count                   # Total sampling count
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the total sampling 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:
        #----------------------------------------
        # 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 = GetRangeString(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}"
        #--------------------
        # Get the event sampling times
        #--------------------
        lret.value = caio.AioGetAiEventSamplingTimes(id, ctypes.byref(ai_event_sampling_times))
        if lret.value != 0:
            ai_event_sampling_times_string = "-"
        else:
            ai_event_sampling_times_string = f"{ai_event_sampling_times.value}"
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"Range                : {ai_range_string}")
        print(f"Input Method         : {ai_input_method_string}")
        print(f"Number of Channels   : {ai_channels_string}")
        print(f"Event Sampling Times : {ai_event_sampling_times_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu(Top)")
        print("========================================")
        print(" 1 : AioInit")
        print(" 2 : AioResetDevice")
        print(" 3 : AioSetAiRangeAll")
        print(" 4 : AioSetAiInputMethod")
        print(" 5 : AioSetAiChannels")
        print(" 6 : Condition Set")
        print(" 7 : AioSetAiEventSamplingTimes")
        print(" 8 : Sampling Start")
        print(" 9 : AioGetAiSamplingCount")
        print("10 : AioGetAiStatus")
        print("11 : Sampling Stop")
        print("12 : 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 total sampling count, sampling count, status are displayed in the callback, output a new line
        #----------------------------------------
        if g_info_flag.value == 1:
            print("")
            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 total sampling count, sampling count, status are displayed in the callback, output a new line
            #----------------------------------------
            if g_info_flag.value == 1:
                print("")
                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")
        #--------------------
        # 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")
        #--------------------
        # AioSetAiRangeAll
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Input the range
            #----------------------------------------
            print("\n----------------------------------------")
            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 : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the total sampling count, sampling count, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    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 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 = GetRangeString(ai_range)
                print(f"Range = {ai_range.value}({ai_range_string})")
            print("")
        #--------------------
        # AioSetAiInputMethod
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # 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 : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the total sampling count, sampling count, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    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})")
            print("")
        #--------------------
        # AioSetAiChannels
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Input the number of channels
            #----------------------------------------
            print("")
            while True:
                print("Please input the number of channels : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the total sampling count, sampling count, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    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 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}")
            print("")
        #--------------------
        # Condition Set
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # 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("\nCondition Set Error")
                print(f"AioSetAiMemoryType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("")
            #----------------------------------------
            # Display the condition set menu
            #----------------------------------------
            SamplingSetting(id)
            #----------------------------------------
            # Set the event
            #----------------------------------------
            lret.value = caio.AioSetAiCallBackProc(id, pai_callback, caio.AIE_START | caio.AIE_END | caio.AIE_DATA_NUM | caio.AIE_OFERR | caio.AIE_SCERR | caio.AIE_ADERR, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCondition Set Error")
                print(f"AioSetAiCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("")
        #--------------------
        # AioSetAiEventSamplingTimes
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Input the event sampling times
            #----------------------------------------
            print("")
            while True:
                print("Please input the event sampling times : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the total sampling count, sampling count, status are displayed in the callback, output a new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ai_event_sampling_times = ctypes.c_long(int(buf))
            #----------------------------------------
            # Set the event sampling times
            #----------------------------------------
            lret.value = caio.AioSetAiEventSamplingTimes(id, ai_event_sampling_times)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiEventSamplingTimes Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Event Sampling Times = {ai_event_sampling_times.value}")
            print("")
        #--------------------
        # Sampling Start
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Clear the memory
            #----------------------------------------
            lret.value = caio.AioResetAiMemory(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling Start Error")
                print(f"AioResetAiMemory Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Clear the status
            #----------------------------------------
            lret.value = caio.AioResetAiStatus(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling Start Error")
                print(f"AioResetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Delete the file if it exists
            #----------------------------------------
            if os.path.exists("./SamplingData.csv"):
                os.remove("./SamplingData.csv")
            #----------------------------------------
            # Start sampling
            #----------------------------------------
            g_total_sampling_count = 0
            lret.value = caio.AioStartAi(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling 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 Start : Successful completion\n")
        #--------------------
        # AioGetAiSamplingCount
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # Get the sampling count
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingCount(id, ctypes.byref(ai_sampling_count))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Sampling Count = {ai_sampling_count.value}")
            print("")
        #--------------------
        # AioGetAiStatus
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # Get the status
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(id, ctypes.byref(ai_status))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                #----------------------------------------
                # Create the status string
                #----------------------------------------
                ai_status_string = GetStatusString(ai_status)
                print(f"Status = 0x{ai_status.value:08x}({ai_status_string:})")
            print("")
        #--------------------
        # Sampling Stop
        #--------------------
        elif buf == "11":
            #----------------------------------------
            # Stop sampling
            #----------------------------------------
            lret.value = caio.AioStopAi(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling Stop Error")
                print(f"AioStopAi Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Get the status
            #----------------------------------------
            while True:
                lret.value = caio.AioGetAiStatus(id, ctypes.byref(ai_status))
                if lret.value != 0 or (ai_status.value & caio.AIS_BUSY) != caio.AIS_BUSY:
                    break
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling Stop Error")
                print(f"AioGetAiStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ai_status_string = GetStatusString(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 Stop Error")
                print(f"AioGetAiSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Get the number of channels
            #----------------------------------------
            lret.value = caio.AioGetAiChannels(id, ctypes.byref(ai_channels))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling Stop Error")
                print(f"AioGetAiChannels Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Allocate the array for storing conversion data
            #----------------------------------------
            try:
                ai_data_type = ctypes.c_float * (ai_sampling_count.value * ai_channels.value)
                ai_data = ai_data_type()
            except:
                print("\nSampling 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), ai_data)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling 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 ai_data is not None:
                    ai_data = None
                continue
            #----------------------------------------
            # Open file
            #----------------------------------------
            try:
                file = open("./SamplingData.csv", 'a')
            except:
                print("\nSampling Stop Error")
                print("Failed to create the file\n")
                #----------------------------------------
                # Release the array for storing conversion data if it has been allocated
                #----------------------------------------
                if ai_data is not None:
                    ai_data = None
                continue
            #----------------------------------------
            # Create file
            #----------------------------------------
            for i in range(0, ai_sampling_count.value):
                #--------------------
                # Generate the string
                #--------------------
                text_string = f"{g_total_sampling_count + i + 1:5d},"
                #--------------------
                # Repeat the process for the specified number of channels
                #--------------------
                for j in range(0, ai_channels.value):
                    text_string += f" {ai_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()
            #----------------------------------------
            # Update the total sampling count
            #----------------------------------------
            g_total_sampling_count += ai_sampling_count.value
            #----------------------------------------
            # Release the array for storing conversion data if it has been allocated
            #----------------------------------------
            if ai_data is not None:
                ai_data = None
            #----------------------------------------
            # Display the message that sampling stop is completed
            #----------------------------------------
            print("\nSampling Stop : Successful completion")
            print(f"Total Sampling Count = {g_total_sampling_count:<8d} Sampling Count = {ai_sampling_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "12":
            #----------------------------------------
            # Exit process
            #----------------------------------------
            lret.value = caio.AioExit(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioExit 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
    #----------------------------------------
    # Exit process
    #----------------------------------------
    caio.AioExit(id)
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_lock.release()
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


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