#================================================================
#================================================================
# API-AIO(WDM)
# Finite sampling using attached data sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import caio
from CommonFunction import *
#----------------------------------------
# Declaration of global variables
#----------------------------------------
g_sampling_buffer = None      # User buffer
g_sampling_buffer_size = 0    # User buffer size
g_data_size = 1               # Data size(Number of packets)


#========================================
# 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_status = ctypes.c_long()                     # Status
    ai_transfer_count = ctypes.c_long()             # Transfer count
    sampling_data_count = 0                         # Number of sampling data
    global g_sampling_buffer                        # User buffer
    global g_sampling_buffer_size                   # User buffer size
    global g_data_size                              # Data size(number of packets)

    #----------------------------------------
    # Event that device operation end
    #----------------------------------------
    if 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')}"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Get the status string
        #----------------------------------------
        ai_status_string = GetStatusString(ai_status)
        #----------------------------------------
        # Get the transfer count
        #----------------------------------------
        lret.value = caio.AioGetAiTransferCount(id, ctypes.byref(ai_transfer_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDevice Operation End Event Process : AioGetAiTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Open file
        #----------------------------------------
        try:
            file = open("./SamplingData.csv", 'w')
        except:
            text_buf = f"\nDevice Operation End Event Process : Failed to create the file"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Calculate the number of sampling data
        #----------------------------------------
        #--------------------
        # When the transfer count exceeds the user buffer size
        #--------------------
        if ai_transfer_count.value > g_sampling_buffer_size:
            #--------------------
            # Limit the number of sampling data to the user buffer size
            #--------------------
            sampling_data_count = g_sampling_buffer_size
        #--------------------
        # When the transfer count is less than the user buffer size
        #--------------------
        else:
            #--------------------
            # Set the transfer count to the number of sampling data
            #--------------------
            sampling_data_count = ai_transfer_count.value
        #----------------------------------------
        # Create sampling data for file output
        #----------------------------------------
        #--------------------
        # Repeat the process up to the number of sampling data
        #--------------------
        for i in range(0, int(sampling_data_count / g_data_size)):
            #--------------------
            # Generate the string
            #--------------------
            text_string = f"{i + 1:5d},"
            #--------------------
            # Repeat the process for the data size (the number of packets)
            #--------------------
            for j in range(0, g_data_size):
                text_string += f" {ctypes.c_uint(g_sampling_buffer[i * g_data_size + j]).value:08X}"
                #--------------------
                # Add newline character for the last packet
                #--------------------
                if j == (g_data_size - 1):
                    text_string += "\n"
                #--------------------
                # Add comma for channels other than the last packet
                #--------------------
                else:
                    text_string += ","
            #----------------------------------------
            # Write data
            #----------------------------------------
            file.write(text_string)
        #----------------------------------------
        # Close file
        #----------------------------------------
        file.close()
        #----------------------------------------
        # Display the transfer position, status
        #----------------------------------------
        text_buf = f"\nDevice Operation End Event Process : Successful completion\nTransfer Position = {ai_transfer_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})\nSave data to \"SamplingData.csv\"."
        PrintOnMultiLines(text_buf, 3)
    #----------------------------------------
    # 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')}"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Get the status string
        #----------------------------------------
        ai_status_string = GetStatusString(ai_status)
        #----------------------------------------
        # Get the transfer count
        #----------------------------------------
        lret.value = caio.AioGetAiTransferCount(id, ctypes.byref(ai_transfer_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nOverflow Occurrence Process : AioGetAiTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Display the transfer position, status
        #----------------------------------------
        text_buf = f"\nOverflow Occurrence Process : Successful completion\nTransfer Position = {ai_transfer_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})\n"
        PrintOnMultiLines(text_buf, 3)
    #----------------------------------------
    # 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')}"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Get the status string
        #----------------------------------------
        ai_status_string = GetStatusString(ai_status)
        #----------------------------------------
        # Get the transfer count
        #----------------------------------------
        lret.value = caio.AioGetAiTransferCount(id, ctypes.byref(ai_transfer_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nSampling Clock Error Occurrence Process : AioGetAiTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Display the transfer position, status
        #----------------------------------------
        text_buf = f"\nSampling Clock Error Occurrence Process : Successful completion\nTransfer Position = {ai_transfer_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})\n"
        PrintOnMultiLines(text_buf, 3)
    #----------------------------------------
    # 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')}"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Get the status string
        #----------------------------------------
        ai_status_string = GetStatusString(ai_status)
        #----------------------------------------
        # Get the transfer count
        #----------------------------------------
        lret.value = caio.AioGetAiTransferCount(id, ctypes.byref(ai_transfer_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nAD Conversion Error Occurrence Process : AioGetAiTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Display the transfer position, status
        #----------------------------------------
        text_buf = f"\nAD Conversion Error Occurrence Process : Successful completion\nTransfer Position = {ai_transfer_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})\n"
        PrintOnMultiLines(text_buf, 3)
    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_sampling_clock = ctypes.c_float()            # Sampling clock period
    ai_scan_clock = ctypes.c_float()                # Conversion speed
    ai_stop_times = ctypes.c_long()                 # Stop times
    ai_sampling_times = ctypes.c_long()             # User buffer storage sampling times
    ai_status = ctypes.c_long()                     # Status
    ai_transfer_count = ctypes.c_long()             # Transfer count
    data_size = ctypes.c_short()                    # Data size(Number of packets)
    attached_data = ctypes.c_long()                 # Type of data attached in addition to AD conversion data
    aiat_ai = ctypes.c_long()                       # Attached information of analog input
    aiat_ao = ctypes.c_long()                       # Attached information of analog output
    aiat_dio = ctypes.c_long()                      # Attached information of digital input and output
    aiat_cnt0 = ctypes.c_long()                     # Attached information of counter channel 0
    aiat_cnt1 = ctypes.c_long()                     # Attached information of counter channel 1
    initialized = 0                                 # Whether the board has been initialized
    sampling_data_count = 0                         # Number of sampling data
    global g_lock                                   # Mutex
    global g_sampling_buffer                        # User buffer
    global g_sampling_buffer_size                   # User buffer size
    global g_data_size                              # Data size(Number of packets)
    global g_info_flag                              # A flag showing the transfer position, status in the callback

    #----------------------------------------
    # Initialize the variable
    #----------------------------------------
    g_info_flag.value = 0
    ai_sampling_times.value = 0
    attached_data.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 sampling clock period
        #--------------------
        lret.value = caio.AioGetAiSamplingClock(id, ctypes.byref(ai_sampling_clock))
        if lret.value != 0:
            ai_sampling_clock_string = "-"
        else:
            ai_sampling_clock_string = f"{ai_sampling_clock.value}[usec]"
        #--------------------
        # Get the conversion speed
        #--------------------
        lret.value = caio.AioGetAiScanClock(id, ctypes.byref(ai_scan_clock))
        if lret.value != 0:
            ai_scan_clock_string = "-"
        else:
            ai_scan_clock_string = f"{ai_scan_clock.value}[usec]"
        #--------------------
        # Get the stop times
        #--------------------
        lret.value = caio.AioGetAiStopTimes(id, ctypes.byref(ai_stop_times))
        if lret.value != 0:
            ai_stop_times_string = "-"
        else:
            ai_stop_times_string = f"{ai_stop_times.value}" 
        #--------------------
        # Check whether the AioSetAiAttachedData function is supported
        #--------------------
        lret.value = caio.AioSetAiAttachedData(id, attached_data)
        #--------------------
        # Get the attached data
        #--------------------
        if (initialized == 0) or (lret.value == 20001):
            attached_data_setting_string = "-\n"
        else:
            #--------------------
            # Clear the display string storage variable
            #--------------------
            attached_data_setting_string = ""
            #--------------------
            # When attached data 'Attached information of analog input' is ON
            #--------------------
            if (attached_data.value & caio.AIAT_AI) == caio.AIAT_AI:
                attached_data_setting_string = "Attached information of analog input\n"
            #--------------------
            # When attached data 'Data of analog output' is ON
            #--------------------
            if (attached_data.value & caio.AIAT_AO0) == caio.AIAT_AO0:
                if len(attached_data_setting_string):
                    attached_data_setting_string += "                                     Data of analog output\n"
                else:
                    attached_data_setting_string = "Data of analog output\n"
            #--------------------
            # When attached data 'Data of digital input and output' is ON
            #--------------------
            if (attached_data.value & caio.AIAT_DIO0) == caio.AIAT_DIO0:
                if len(attached_data_setting_string):
                    attached_data_setting_string += "                                     Data of digital input and output\n"
                else:
                    attached_data_setting_string = "Data of digital input and output\n"
            #--------------------
            # When attached data 'Data of counter channel 0' is ON
            #--------------------
            if (attached_data.value & caio.AIAT_CNT0) == caio.AIAT_CNT0:
                if len(attached_data_setting_string):
                    attached_data_setting_string += "                                     Data of counter channel 0\n"
                else:
                    attached_data_setting_string = "Data of counter channel 0\n"
            #--------------------
            # When attached data 'Data of counter channel 1' is ON
            #--------------------
            if (attached_data.value & caio.AIAT_CNT1) == caio.AIAT_CNT1:
                if len(attached_data_setting_string):
                    attached_data_setting_string += "                                     Data of counter channel 1\n"
                else:
                    attached_data_setting_string = "Data of counter channel 1\n"
            #--------------------
            # When there is no attached data
            #--------------------
            if attached_data.value == 0:
                attached_data_setting_string = "None\n"
        #--------------------
        # Get the user buffer storage sampling times
        #--------------------
        if initialized == 0:
            ai_sampling_times_string = "-"
        else:
            ai_sampling_times_string = f"{ai_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"Sampling Clock Period              : {ai_sampling_clock_string}")
        print(f"Conversion Speed                   : {ai_scan_clock_string}")
        print(f"Stop Times                         : {ai_stop_times_string}")
        print(f"Attached Data                      : {attached_data_setting_string}", end='', flush=True)
        print(f"User Buffer Storage Sampling Times : {ai_sampling_times_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print(" 1 : AioInit")
        print(" 2 : AioResetDevice")
        print(" 3 : AioSetAiRangeAll")
        print(" 4 : AioSetAiInputMethod")
        print(" 5 : AioSetAiChannels")
        print(" 6 : AioSetAiSamplingClock")
        print(" 7 : AioSetAiScanClock")
        print(" 8 : AioSetAiStopTimes")
        print(" 9 : AioSetAiAttachedData")
        print("10 : Basic Settings")
        print("11 : User Buffer Size Set")
        print("12 : Sampling Start")
        print("13 : AioGetAiTransferCount")
        print("14 : AioGetAiStatus")
        print("15 : Sampling Stop")
        print("16 : AioExit")
        print(" q : Exit")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Unlock
        #----------------------------------------
        g_lock.release()
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Lock
        #----------------------------------------
        g_lock.acquire()
        #----------------------------------------
        # If the transfer position, status are displayed in the callback, output three new line
        #----------------------------------------
        if g_info_flag.value == 1:
            print("\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 transfer position, status are displayed in the callback, output three new line
            #----------------------------------------
            if g_info_flag.value == 1:
                print("\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")
        #--------------------
        # 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 transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\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 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 transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\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})")
            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 transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\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 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("")
        #--------------------
        # AioSetAiSamplingClock
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # Input the sampling clock period
            #----------------------------------------
            print("")
            while True:
                print("Please input the sampling clock period[usec] : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 0):
                    continue
                break
            ai_sampling_clock = ctypes.c_float(float(buf))
            #----------------------------------------
            # Set the sampling clock period
            #----------------------------------------
            lret.value = caio.AioSetAiSamplingClock(id, ai_sampling_clock)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiSamplingClock Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Sampling Clock Period = {ai_sampling_clock.value}[usec]")
            print("")
        #--------------------
        # AioSetAiScanClock
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Input the conversion speed
            #----------------------------------------
            print("")
            while True:
                print("Please input the conversion speed[usec] : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 0):
                    continue
                break
            ai_scan_clock = ctypes.c_float(float(buf))
            #----------------------------------------
            # Set the conversion speed
            #----------------------------------------
            lret.value = caio.AioSetAiScanClock(id, ai_scan_clock)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiScanClock Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Conversion Speed = {ai_scan_clock.value}[usec]")
            print("")
        #--------------------
        # AioSetAiStopTimes
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Input the stop times
            #----------------------------------------
            print("")
            while True:
                print("Please input the stop times : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ai_stop_times = ctypes.c_long(int(buf))
            #----------------------------------------
            # Set the stop times
            #----------------------------------------
            lret.value = caio.AioSetAiStopTimes(id, ai_stop_times)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiStopTimes Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Stop Times = {ai_stop_times.value}")
            print("")
        #--------------------
        # AioSetAiAttachedData
        #--------------------
        elif buf == "9":
            print("\n----------------------------------------")
            print("Start the attached data setting")
            print("----------------------------------------")
            #----------------------------------------
            # Initialize the variable
            #----------------------------------------
            attached_data.value = 0
            #----------------------------------------
            # Input whether to attach
            #----------------------------------------
            print("----------------------------------------")
            print("Parameter(Attached information of analog input)")
            print("----------------------------------------")
            print("Attached information of analog input Not attached: 0 Attached: 1")
            while True:
                print("Please input whether to attach : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            aiat_ai = ctypes.c_long(int(buf))
            #----------------------------------------
            # Input whether to attach
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Data of analog output)")
            print("----------------------------------------")
            print("Data of analog output Not attached: 0 Attached: 1")
            while True:
                print("Please input whether to attach : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            aiat_ao = ctypes.c_long(int(buf))
            #----------------------------------------
            # Input whether to attach
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Data of digital input and output)")
            print("----------------------------------------")
            print("Data of digital input and output Not attached: 0 Attached: 1")
            while True:
                print("Please input whether to attach : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            aiat_dio = ctypes.c_long(int(buf))
            #----------------------------------------
            # Input whether to attach
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Data of counter channel 0)")
            print("----------------------------------------")
            print("Data of counter channel 0 Not attached: 0 Attached: 1")
            while True:
                print("Please input whether to attach : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            aiat_cnt0 = ctypes.c_long(int(buf))
            #----------------------------------------
            # Input whether to attach
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Data of counter channel 1)")
            print("----------------------------------------")
            print("Data of counter channel 1 Not attached: 0 Attached: 1")
            while True:
                print("Please input whether to attach : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            aiat_cnt1 = ctypes.c_long(int(buf))
            #----------------------------------------
            # Get the type of the attached data
            #----------------------------------------
            attached_data.value = ((caio.AIAT_AI if aiat_ai.value != 0 else 0) |
                                   (caio.AIAT_AO0 if aiat_ao.value != 0 else 0) |
                                   (caio.AIAT_DIO0 if aiat_dio.value != 0 else 0) |
                                   (caio.AIAT_CNT0 if aiat_cnt0.value != 0 else 0) |
                                   (caio.AIAT_CNT1 if aiat_cnt1.value != 0 else 0))
            #----------------------------------------
            # Set the attached data that are attached to the AD conversion data
            #----------------------------------------
            lret.value = caio.AioSetAiAttachedData(id, attached_data)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiAttachedData Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                #----------------------------------------
                # Create attached data string
                #----------------------------------------
                attached_data_string = GetAttachedDataString(attached_data)
                print(f"Attached Data = 0x{attached_data.value:08x}({attached_data_string:})")
            else:
                attached_data.value = 0
            print("")
        #--------------------
        # Basic Settings
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # Set the data storage memory type to Not overwrite the memory
            # 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("\nBasic Settings Error")
                print(f"AioSetAiMemoryType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the sampling start condition to Software
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiStartTrigger(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nBasic Settings Error")
                print(f"AioSetAiStartTrigger 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.AioSetAiClockType(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nBasic Settings Error")
                print(f"AioSetAiClockType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the sampling stop condition to Stop conversion by the specified times
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiStopTrigger(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nBasic Settings Error")
                print(f"AioSetAiStopTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the event factor to 'Event that device operation end', 'Event that overflow',
            # 'Event that sampling clock error', and 'Event that AD conversion error'.
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiCallBackProc(id, pai_callback, (caio.AIE_END | caio.AIE_OFERR | caio.AIE_SCERR | caio.AIE_ADERR), 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nBasic Settings Error")
                print(f"AioSetAiCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that basic settings is completed
            #----------------------------------------
            print("\nBasic Settings : Successful completion\n")
        #--------------------
        # User Buffer Size Set
        #--------------------
        elif buf == "11":
            #----------------------------------------
            # Set the analog input conversion data transfer mode to user buffer mode
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAiTransferMode(id, 1)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nUser Buffer Size Set Error")
                print(f"AioSetAiTransferMode Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # When the user buffer mode is used to transfer data, retrieves data size that is necessary for one sampling
            #----------------------------------------
            lret.value = caio.AioGetAiSamplingDataSize(id, ctypes.byref(data_size))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nUser Buffer Size Set Error")
                print(f"AioGetAiSamplingDataSize Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Input the user buffer storage sampling times
            #----------------------------------------
            print("")
            while True:
                print("Please input the user buffer storage sampling times : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, status are displayed in the callback, output three new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ai_sampling_times = ctypes.c_long(int(buf))
            #----------------------------------------
            # Allocate the user buffer for storing conversion data
            #----------------------------------------
            #--------------------
            # Release the user buffer for storing conversion data if it has been allocated
            #--------------------
            if g_sampling_buffer is not None:
                g_sampling_buffer = None
            #--------------------
            # User buffer size: number of packets that is necessary for one sampling x sampling times
            #--------------------
            g_data_size = data_size.value
            g_sampling_buffer_size = data_size.value * ai_sampling_times.value
            #--------------------
            # Allocate the user buffer for storing conversion data
            #--------------------
            try:
                sampling_buffer_type   = ctypes.c_int * g_sampling_buffer_size
                g_sampling_buffer = sampling_buffer_type()
            except:
                print("\nUser Buffer Size Set Error")
                print("Failed to allocate the user buffer\n")
                continue
            #----------------------------------------
            # Set user buffer
            #----------------------------------------
            lret.value = caio.AioSetAiTransferData(id, ctypes.c_long(g_sampling_buffer_size), ctypes.cast(g_sampling_buffer, ctypes.POINTER(ctypes.c_long)))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nUser Buffer Size Set Error")
                print(f"AioSetAiTransferData Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that user buffer setting is completed
            #----------------------------------------
            print("\nUser Buffer Size Set : Successful completion")
            print(f"User Buffer Storage Sampling Times = {ai_sampling_times.value}\n")
        #--------------------
        # Sampling Start
        #--------------------
        elif buf == "12":
            #----------------------------------------
            # 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
            #----------------------------------------
            # Start sampling
            #----------------------------------------
            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")
        #--------------------
        # AioGetAiTransferCount
        #--------------------
        elif buf == "13":
            #----------------------------------------
            # Get the transfer count
            #----------------------------------------
            lret.value = caio.AioGetAiTransferCount(id, ctypes.byref(ai_transfer_count))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetAiTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Transfer Position = {ai_transfer_count.value}")
            print("")
        #--------------------
        # AioGetAiStatus
        #--------------------
        elif buf == "14":
            #----------------------------------------
            # 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 == "15":
            #----------------------------------------
            # 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
            #----------------------------------------
            lret.value = caio.AioGetAiStatus(id, ctypes.byref(ai_status))
            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 transfer count
            #----------------------------------------
            lret.value = caio.AioGetAiTransferCount(id, ctypes.byref(ai_transfer_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nSampling Stop Error")
                print(f"AioGetAiTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Open file
            #----------------------------------------
            try:
                file = open("./SamplingData.csv", 'w')
            except:
                print("\nSampling Stop Error")
                print("Failed to create the file\n")
                continue
            #----------------------------------------
            # Calculate the number of sampling data
            #----------------------------------------
            #--------------------
            # When the transfer count exceeds the user buffer size
            #--------------------
            if ai_transfer_count.value > g_sampling_buffer_size:
                #--------------------
                # Limit the number of sampling data to the user buffer size
                #--------------------
                sampling_data_count = g_sampling_buffer_size
            #--------------------
            # When the transfer count is less than the user buffer size
            #--------------------
            else:
                #--------------------
                # Set the transfer count to the number of sampling data
                #--------------------
                sampling_data_count = ai_transfer_count.value
            #----------------------------------------
            # Create sampling data for file output
            #----------------------------------------
            #--------------------
            # Repeat the process up to the number of sampling data
            #--------------------
            for i in range(0, int(sampling_data_count / g_data_size)):
                #--------------------
                # Generate the string
                #--------------------
                text_string = f"{i + 1:5d},"
                #--------------------
                # Repeat the process for the data size (the number of packets)
                #--------------------
                for j in range(0, g_data_size):
                    text_string += f" {ctypes.c_uint(g_sampling_buffer[i * g_data_size + j]).value:08X}"
                    #--------------------
                    # Add newline character for the last packet
                    #--------------------
                    if j == (g_data_size - 1):
                        text_string += "\n"
                    #--------------------
                    # Add comma for channels other than the last packet
                    #--------------------
                    else:
                        text_string += ","
                #----------------------------------------
                # Write data
                #----------------------------------------
                file.write(text_string)
            #----------------------------------------
            # Close file
            #----------------------------------------
            file.close()
            #----------------------------------------
            # Display the message that sampling stop is completed
            #----------------------------------------
            print("\nSampling Stop : Successful completion")
            #----------------------------------------
            # Display the transfer position, status
            #----------------------------------------
            print(f"Transfer Position = {ai_transfer_count.value:<8d} Status = 0x{ai_status.value:08x}({ai_status_string:})")
            #----------------------------------------
            # Display the message that file output is completed
            #----------------------------------------
            print("Save data to \"SamplingData.csv\".\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "16":
            #----------------------------------------
            # Release the user buffer for storing conversion data if it has been allocated
            #----------------------------------------
            if g_sampling_buffer is not None:
                g_sampling_buffer = 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 user buffer for storing conversion data if it has been allocated
    #----------------------------------------
    if g_sampling_buffer is not None:
        g_sampling_buffer = None
    #----------------------------------------
    # Exit process
    #----------------------------------------
    caio.AioExit(id)
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_lock.release()
    #----------------------------------------
    # Application exit
    #----------------------------------------
    sys.exit()


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