#================================================================
#================================================================
# API-AIO(WDM)
# Infinite generating using user buffer sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import math
import caio
from CommonFunction import *
from GeneratingSetting import *


#========================================
# Function name    CallBackProc
# Parameter        id          Id get by AioInit
# Parameter        ao_event    The event that occurred
# Parameter        wParam      Parameter passed from driver
# Parameter        lParam      Parameter unique to each event
# Parameter        Param       Parameter specified in the AioSetAoCallBackProc function
# Details          Register this function in AioSetAoCallBackProc function
#                  Function registered with the AioSetAoCallBackProc function
# Return value     None
#========================================
def CallBackProc(id, ao_event, wParam, lParam, Param):
    error_buf = ctypes.create_string_buffer(256)    # Error code string
    lret = ctypes.c_long()                          # For return code
    ao_transfer_count = ctypes.c_long()             # Transfer count
    ao_status = ctypes.c_long()                     # Status
    lap = ctypes.c_long()                           # Repeat times

    #----------------------------------------
    # Event that the specified number of data are transferred
    #----------------------------------------
    if ao_event == caio.AIOM_AOE_DATA_TSF:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nEvent that the specified number of data are transferred Process : AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ao_status_string = GetStatusString(ao_status)
        #----------------------------------------
        # Get the number of data that are transferred from the user memory
        #----------------------------------------
        lret.value = caio.AioGetAoTransferCount(id, ctypes.byref(ao_transfer_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nEvent that the specified number of data are transferred Process : AioGetAoTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Get repeat times
        #----------------------------------------
        lret.value = caio.AioGetAoTransferLap(id, ctypes.byref(lap))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nEvent that the specified number of data are transferred Process : AioGetAoTransferLap Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Display the transfer position, repeat count, status
        #----------------------------------------
        text_buf = f"\nTransfer Position = {ao_transfer_count.value:<8d} Repeat Count = {lap.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string:})"
        PrintOnOneLine(text_buf)
    #----------------------------------------
    # Event that device operation end
    #----------------------------------------
    elif ao_event == caio.AIOM_AOE_END:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDevice Operation End Event Process : AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ao_status_string = GetStatusString(ao_status)
        #----------------------------------------
        # Get the number of data that are transferred from the user memory
        #----------------------------------------
        lret.value = caio.AioGetAoTransferCount(id, ctypes.byref(ao_transfer_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDevice Operation End Event Process : AioGetAoTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Get repeat times
        #----------------------------------------
        lret.value = caio.AioGetAoTransferLap(id, ctypes.byref(lap))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDevice Operation End Event Process : AioGetAoTransferLap Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Display the transfer position, repeat count, status
        #----------------------------------------
        text_buf = f"\nTransfer Position = {ao_transfer_count.value:<8d} Repeat Count = {lap.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string:})"
        PrintOnOneLine(text_buf)
    #----------------------------------------
    # Event that sampling clock error
    #----------------------------------------
    elif ao_event == caio.AIOM_AOE_SCERR:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nSampling Clock Error Occurrence Process : AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ao_status_string = GetStatusString(ao_status)
        #----------------------------------------
        # Get the number of data that are transferred from the user memory
        #----------------------------------------
        lret.value = caio.AioGetAoTransferCount(id, ctypes.byref(ao_transfer_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nSampling Clock Error Occurrence Process : AioGetAoTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Get repeat times
        #----------------------------------------
        lret.value = caio.AioGetAoTransferLap(id, ctypes.byref(lap))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nSampling Clock Error Occurrence Process : AioGetAoTransferLap Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Display the transfer position, repeat count, status
        #----------------------------------------
        text_buf = f"\nTransfer Position = {ao_transfer_count.value:<8d} Repeat Count = {lap.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string:})"
        PrintOnOneLine(text_buf)
    #----------------------------------------
    # Event that DA conversion error
    #----------------------------------------
    elif ao_event == caio.AIOM_AOE_DAERR:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDA Conversion Error Occurrence Process : AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Create the status string
        #----------------------------------------
        ao_status_string = GetStatusString(ao_status)
        #----------------------------------------
        # Get the number of data that are transferred from the user memory
        #----------------------------------------
        lret.value = caio.AioGetAoTransferCount(id, ctypes.byref(ao_transfer_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDA Conversion Error Occurrence Process : AioGetAoTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Get repeat times
        #----------------------------------------
        lret.value = caio.AioGetAoTransferLap(id, ctypes.byref(lap))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDA Conversion Error Occurrence Process : AioGetAoTransferLap Ret = {lret.value} {error_buf.value.decode('sjis')}"
            PrintOnOneLine(text_buf)
            return
        #----------------------------------------
        # Display the transfer position, repeat count, status
        #----------------------------------------
        text_buf = f"\nTransfer Position = {ao_transfer_count.value:<8d} Repeat Count = {lap.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string:})"
        PrintOnOneLine(text_buf)
    return


pao_callback = caio.PAIO_AO_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
    ao_range = ctypes.c_short()                     # Range
    ao_channels = ctypes.c_short()                  # Number of channels
    ao_event_transfer_times = ctypes.c_long()       # Event data transfer times
    ao_status = ctypes.c_long()                     # Status
    ao_transfer_count = ctypes.c_long()             # Transfer count
    lap = ctypes.c_long()                           # Repeat times
    data_size = ctypes.c_short()                    # Data size
    ao_generating_buffer = None                     # User buffer
    ao_generating_buffer_size = ctypes.c_long()     # User buffer size
    ao_resolution =  ctypes.c_short()               # Analog output resolution
    initialized = 0                                 # Whether the board has been initialized
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the transfer position, repeat count, status in the callback
    
    #----------------------------------------
    # Initialize the variable
    #----------------------------------------
    g_info_flag.value   = 0
    ao_generating_times = 0
    #----------------------------------------
    # Lock
    #----------------------------------------
    g_lock.acquire()
    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the range value
        #--------------------
        lret.value = caio.AioGetAoRange(id, 0, ctypes.byref(ao_range))
        if lret.value != 0:
            ao_range_string = "-"
        else:
            ao_range_string = GetRangeString(ao_range)
        #--------------------
        # Get the number of channels
        #--------------------
        lret.value = caio.AioGetAoChannels(id, ctypes.byref(ao_channels))
        if lret.value != 0:
            ao_channels_string = "-"
        else:
            ao_channels_string = f"{ao_channels.value}"
        #--------------------
        # Get the number of generating for user buffer storage
        #--------------------
        if initialized == 0:
            ao_generating_times_string = "-"
        else:
            ao_generating_times_string = f"{ao_generating_times}"
        #--------------------
        # Get the event data transfer times
        #--------------------
        lret.value = caio.AioGetAoEventTransferTimes(id, ctypes.byref(ao_event_transfer_times))
        if lret.value != 0:
            ao_event_transfer_times_string = "-"
        else:
            ao_event_transfer_times_string = f"{ao_event_transfer_times.value}"
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"Range                                : {ao_range_string}")
        print(f"Number of Channels                   : {ao_channels_string}")
        print(f"User Buffer Storage Generating Times : {ao_generating_times_string}")
        print(f"Event Data Transfer Times            : {ao_event_transfer_times_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu(Top)")
        print("========================================")
        print(" 1 : AioInit")
        print(" 2 : AioResetDevice")
        print(" 3 : AioSetAoRangeAll")
        print(" 4 : AioSetAoChannels")
        print(" 5 : Condition Set")
        print(" 6 : User Buffer Set")
        print(" 7 : AioSetAoEventTransferTimes")
        print(" 8 : Generating Start")
        print(" 9 : AioGetAoTransferCount")
        print("10 : AioGetAoTransferLap")
        print("11 : AioGetAoStatus")
        print("12 : Generating Stop")
        print("13 : 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 transfer position, repeat 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 transfer position, repeat 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")
            #----------------------------------------
            # 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")
        #--------------------
        # AioSetAoRangeAll
        #--------------------
        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\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, repeat 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
            ao_range = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the range
            #----------------------------------------
            lret.value = caio.AioSetAoRangeAll(id, ao_range)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAoRangeAll Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                ao_range_string = GetRangeString(ao_range)
                print(f"Range = {ao_range.value}({ao_range_string})")
            print("")
        #--------------------
        # AioSetAoChannels
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # 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, repeat 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
            ao_channels = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the number of analog output channels used for conversion
            #----------------------------------------
            lret.value = caio.AioSetAoChannels(id, ao_channels)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAoChannels Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Number of Channels = {ao_channels.value}")
            print("")
        #--------------------
        # Condition Set
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Set the analog output conversion data transfer mode to user buffer mode
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoTransferMode(id, 1)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCondition Set Error")
                print(f"AioSetAoTransferMode Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the data storage memory type to Repeat output
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoMemoryType(id, 1)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCondition Set Error")
                print(f"AioSetAoMemoryType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("")
            #----------------------------------------
            # Display the condition set menu
            #----------------------------------------
            GeneratingSetting(id)
            #----------------------------------------
            # Repeat times: Infinite
            #----------------------------------------
            lret.value = caio.AioSetAoRepeatTimes(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCondition Set Error")
                print(f"AioSetAoRepeatTimes Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the event factor to 'Event that device operation end', 'Event that the specified number of data are transferred',
            # 'Event that sampling clock error', and 'Event that DA conversion error'.
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoCallBackProc(id, pao_callback, caio.AOE_END | caio.AOE_DATA_TSF | caio.AOE_SCERR | caio.AOE_DAERR, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nCondition Set Error")
                print(f"AioSetAoCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            print("")
        #--------------------
        # User Buffer Set
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # Input the generating times for user buffer storage
            #----------------------------------------
            print("")
            while True:
                print("Please input the generating times for user buffer storage : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, repeat 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
            ao_generating_times = int(buf)
            #----------------------------------------
            # When the user buffer mode is used to transfer data, it is necessary to get data size for one generating
            #----------------------------------------
            lret.value = caio.AioGetAoSamplingDataSize(id, ctypes.byref(data_size))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nUser Buffer Set Error")
                print(f"AioGetAoSamplingDataSize Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Allocate the user buffer for storing output data
            #----------------------------------------
            #--------------------
            # Release the user buffer for storing output data if it has been allocated
            #--------------------
            if ao_generating_buffer is not None:
                ao_generating_buffer = None
            #--------------------
            # User buffer size: number of packets required for one generating x generating times
            #--------------------
            ao_generating_buffer_size = ctypes.c_long(data_size.value * ao_generating_times)
            #--------------------
            # Allocate the user buffer for storing output data
            #--------------------
            try:
                ao_generating_buffer_type = ctypes.c_int * ao_generating_buffer_size.value
                ao_generating_buffer = ao_generating_buffer_type()
            except:
                print("\nUser Buffer Set Error")
                print("Failed to allocate the user buffer\n")
                continue
            #----------------------------------------
            # Get the resolution of analog output
            #----------------------------------------
            lret.value = caio.AioGetAoResolution(id, ctypes.byref(ao_resolution))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nUser Buffer Set Error")
                print(f"AioGetAoResolution Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Create analog output data: sine waveform
            #----------------------------------------
            #--------------------
            # 16 bit resolution
            #--------------------
            if ao_resolution.value == 16:
                gain = 0xffff / 2
                offset = gain
            #--------------------
            # 12 bit resolution
            #--------------------
            else:
                gain = 0xfff / 2
                offset = gain
            #--------------------
            # Create data
            #--------------------
            for i in range(0, ao_generating_times):
                for j in range(0, data_size.value):
                    if (j * 2 + 1) >= ao_channels.value:
                        data1 = ctypes.c_int(int(gain * math.sin(2 * 3.14159265358979 * i / ao_generating_times + 3.14159265358979 / 2 * ((j * 2) % 4)) + offset))
                        data2 = ctypes.c_int(0)
                    else:
                        data1 = ctypes.c_int(int(gain * math.sin(2 * 3.14159265358979 * i / ao_generating_times + 3.14159265358979 / 2 * ((j * 2) % 4)) + offset))
                        data2 = ctypes.c_int(int(gain * math.sin(2 * 3.14159265358979 * i / ao_generating_times + 3.14159265358979 / 2 * ((j * 2 + 1) % 4)) + offset))
                    ao_generating_buffer[i * data_size.value + j] = (data2.value & 0x0000ffff) << 16 | (data1.value & 0x0000ffff)
            #----------------------------------------
            # Open file
            #----------------------------------------
            try:
                file = open("./GeneratingData.csv", 'w')
            except:
                #----------------------------------------
                # Release the user buffer for storing output data if it has been allocated
                #----------------------------------------
                if ao_generating_buffer is not None:
                    ao_generating_buffer = None
                print("\nUser Buffer Set Error")
                print("Failed to create the file\n")
                continue
            #----------------------------------------
            # Create file
            #----------------------------------------
            for i in range(0, ao_generating_times):
                #--------------------
                # Generate the string
                #--------------------
                text_string = f"{i + 1:5d},"
                #--------------------
                # Repeat the process for the specified number of packets
                #--------------------
                for j in range(0, data_size.value):
                    text_string += f" {ctypes.c_uint(ao_generating_buffer[i * data_size.value + j]).value:08X}"
                    #--------------------
                    # Add newline character for the last packet
                    #--------------------
                    if j == (data_size.value - 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()
            #----------------------------------------
            # Set the user buffer
            #----------------------------------------
            lret.value = caio.AioSetAoTransferData(id, ao_generating_buffer_size, ctypes.cast(ao_generating_buffer, ctypes.POINTER(ctypes.c_long)))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nUser Buffer Set Error")
                print(f"AioSetAoTransferData Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that user buffer set is completed
            #----------------------------------------
            print("\nUser Buffer Set : Successful completion")
            print(f"User Buffer Storage Generating Times = {ao_generating_times}\n")
        #--------------------
        # AioSetAoEventTransferTimes
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Input the event data transfer times
            #----------------------------------------
            print("")
            while True:
                print("Please input the event data transfer times : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the transfer position, repeat 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
            ao_event_transfer_times = ctypes.c_long(int(buf))
            #----------------------------------------
            # Set the data transfer times when the "Event that the specified number of data are transferred" is used
            #----------------------------------------
            lret.value = caio.AioSetAoEventTransferTimes(id, ao_event_transfer_times)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAoEventTransferTimes Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Event Data Transfer Times = {ao_event_transfer_times.value}")
            print("")
        #--------------------
        # Generating Start
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Reset the analog output status
            #----------------------------------------
            lret.value = caio.AioResetAoStatus(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating Start Error")
                print(f"AioResetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Start generating
            #----------------------------------------
            lret.value = caio.AioStartAo(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating Start Error")
                print(f"AioStartAo Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that generating start is completed
            #----------------------------------------
            print("\nGenerating Start : Successful completion\n")
        #--------------------
        # AioGetAoTransferCount
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # Get the number of data that are transferred from the user memory
            #----------------------------------------
            lret.value = caio.AioGetAoTransferCount(id, ctypes.byref(ao_transfer_count))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetAoTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Transfer Position = {ao_transfer_count.value}")
            print("")
        #--------------------
        # AioGetAoTransferLap
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # Get repeat times
            #----------------------------------------
            lret.value = caio.AioGetAoTransferLap(id, ctypes.byref(lap))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetAoTransferLap Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Repeat Count = {lap.value}")
            print("")
        #--------------------
        # AioGetAoStatus
        #--------------------
        elif buf == "11":
            #----------------------------------------
            # Get the status
            #----------------------------------------
            lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                #----------------------------------------
                # Create the status string
                #----------------------------------------
                ao_status_string = GetStatusString(ao_status)
                print(f"Status = 0x{ao_status.value:08x}({ao_status_string:})")
            print("")
        #--------------------
        # Generating Stop
        #--------------------
        elif buf == "12":
            #----------------------------------------
            # Stop generating
            #----------------------------------------
            lret.value = caio.AioStopAo(id)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating Stop Error")
                print(f"AioStopAo Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Get the status
            #----------------------------------------
            while True:
                lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
                if lret.value != 0 or (ao_status.value & caio.AOS_BUSY) != caio.AOS_BUSY:
                    break
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating Stop Error")
                print(f"AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Create the status string
            #----------------------------------------
            ao_status_string = GetStatusString(ao_status)
            #----------------------------------------
            # Get the number of data that are transferred from the user memory
            #----------------------------------------
            lret.value = caio.AioGetAoTransferCount(id, ctypes.byref(ao_transfer_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating Stop Error")
                print(f"AioGetAoTransferCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Get repeat times
            #----------------------------------------
            lret.value = caio.AioGetAoTransferLap(id, ctypes.byref(lap))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating Stop Error")
                print(f"AioGetAoTransferLap Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that generating stop is completed
            #----------------------------------------
            print("\nGenerating Stop : Successful completion")
            print(f"Transfer Position = {ao_transfer_count.value:<8d} Repeat Count = {lap.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string:})\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "13":
            #----------------------------------------
            # Release the user buffer for storing output data if it has been allocated
            #----------------------------------------
            if ao_generating_buffer is not None:
                ao_generating_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 output data if it has been allocated
    #----------------------------------------
    if ao_generating_buffer is not None:
        ao_generating_buffer = None
    #----------------------------------------
    # Exit process
    #----------------------------------------
    caio.AioExit(id)
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_lock.release()
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


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