#================================================================
#================================================================
# API-AIO(WDM)
# Finite 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 *


#========================================
# 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          Function registered with the AioSetAoCallBackProc function
#                  This function is called when an event occurs
# 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_status = ctypes.c_long()                     # Analog output status
    ao_transfer_count = ctypes.c_long()             # Transfer count

    #----------------------------------------
    # Event that device operation end
    #----------------------------------------
    if ao_event == caio.AIOM_AOE_END:
        #----------------------------------------
        # Get the status
        #----------------------------------------
        lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDevice Operation End Event Process : AioGetAoStatus Ret = {lret.value} {error_buf.value.decode('sjis')}\r"
            PrintOnMultiLines(text_buf, 1)
            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')}\r"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Display the transfer position, status
        #----------------------------------------
        text_buf = f"\nDevice Operation End Event Process : Successful completion\nTransfer Position = {ao_transfer_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string})\r"
        PrintOnMultiLines(text_buf, 2)
    #----------------------------------------
    # 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')}\r"
            PrintOnMultiLines(text_buf, 1)
            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')}\r"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Display the transfer position, status
        #----------------------------------------
        text_buf = f"\nSampling Clock Error Occurrence Process : Successful completion\nTransfer Position = {ao_transfer_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string})\r"
        PrintOnMultiLines(text_buf, 2)
    #----------------------------------------
    # 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')}\r"
            PrintOnMultiLines(text_buf, 1)
            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')}\r"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Display the transfer position, status
        #----------------------------------------
        text_buf = f"\nDA Conversion Error Occurrence Process : Successful completion\nTransfer Position = {ao_transfer_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string})\r"
        PrintOnMultiLines(text_buf, 2)
    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
    initialized = 0                                 # Whether the board has been initialized
    id = ctypes.c_short()                           # ID for device access
    ao_range = ctypes.c_short()                     # Range
    ao_status = ctypes.c_long()                     # Analog output status
    ao_channels = ctypes.c_short()                  # Number of channels
    ao_resolution = ctypes.c_short()                # Analog output resolution
    ao_transfer_count = ctypes.c_long()             # Transfer count
    ao_data_size = ctypes.c_short()                 # Data size
    ao_generating_buffer = None                     # User buffer
    ao_generating_buffer_size = ctypes.c_long()     # User buffer size
    data1 = ctypes.c_long()                         # Temporary output data
    data2 = ctypes.c_long()                         # Temporary output data
    ao_generating_clock = ctypes.c_float()          # Generating clock period
    ao_generating_times = 0                         # User buffer storage generation times
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the transfer position, status in the callback

    #----------------------------------------
    # Initialize the variable
    #----------------------------------------
    g_info_flag.value = 0
    #----------------------------------------
    # Lock
    #----------------------------------------
    g_lock.acquire()
    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the range value
        #--------------------
        lret.value = caio.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 generating clock period
        #--------------------
        lret.value = caio.AioGetAoSamplingClock(id, ctypes.byref(ao_generating_clock))
        if lret.value != 0:
            ao_generating_clock_string = "-"
        else:
            ao_generating_clock_string = f"{ao_generating_clock.value}[usec]"
        #--------------------
        # Get the user buffer storage generation times
        #--------------------
        if initialized == 0:
            ao_generating_times_string = "-"
        else:
            ao_generating_times_string = f"{ao_generating_times}"
        #----------------------------------------
        # 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"Generating Clock Period              : {ao_generating_clock_string}")
        print(f"User Buffer Storage Generation Times : {ao_generating_times_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print(" 1 : AioInit")
        print(" 2 : AioResetDevice")
        print(" 3 : AioSetAoRangeAll")
        print(" 4 : AioSetAoChannels")
        print(" 5 : AioSetAoSamplingClock")
        print(" 6 : Basic Settings")
        print(" 7 : User Buffer Settings")
        print(" 8 : Generating Start")
        print(" 9 : AioGetAoTransferCount")
        print("10 : AioGetAoStatus")
        print("11 : Generating Stop")
        print("12 : AioExit")
        print(" q : Quit")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Unlock
        #----------------------------------------
        g_lock.release()
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Lock
        #----------------------------------------
        g_lock.acquire()
        #----------------------------------------
        # If the transfer position, status are displayed in the callback, output two new line
        #----------------------------------------
        if g_info_flag.value == 1:
            print("\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 two new line
            #----------------------------------------
            if g_info_flag.value == 1:
                print("\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")
        #--------------------
        # 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, status are displayed in the callback, output two new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_range = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the 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, status are displayed in the callback, output two new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channels = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the number of analog output channels 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("")
        #--------------------
        # AioSetAoSamplingClock
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Input the generating clock period
            #----------------------------------------
            print("")
            while True:
                print("Please input the generating 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 two new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 0):
                    continue
                break
            ao_generating_clock = ctypes.c_float(float(buf))
            #----------------------------------------
            # Set the generating clock period
            #----------------------------------------
            lret.value = caio.AioSetAoSamplingClock(id, ao_generating_clock)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAoSamplingClock Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Generating Clock Period = {ao_generating_clock.value}[usec]")
            print("")
        #--------------------
        # Basic Settings
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # 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("\nBasic Settings Error")
                print(f"AioSetAoTransferMode Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the data storage memory type to Not repeat output
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoMemoryType(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nBasic Settings Error")
                print(f"AioSetAoMemoryType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the generating start condition to Software
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoStartTrigger(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nBasic Settings Error")
                print(f"AioSetAoStartTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the clock type to Internal Clock
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoClockType(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nBasic Settings Error")
                print(f"AioSetAoClockType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the generating stop condition to Stop conversion by the specified times
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoStopTrigger(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nBasic Settings Error")
                print(f"AioSetAoStopTrigger Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Set the event factor to 'Event that device operation end',
            # 'Event that sampling clock error', and 'Event that DA conversion error'.
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoCallBackProc(id, pao_callback, (caio.AOE_END | caio.AOE_SCERR | caio.AOE_DAERR), 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nBasic Settings Error")
                print(f"AioSetAoCallBackProc Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that basic setting is completed
            #----------------------------------------
            print("\nBasic Settings : Successful completion\n")
        #--------------------
        # User Buffer Settings
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # When the user buffer mode is used to transfer data, get data size that is necessary for one sampling
            #----------------------------------------
            lret.value = caio.AioGetAoSamplingDataSize(id, ctypes.byref(ao_data_size))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nUser Buffer Settings Error")
                print(f"AioGetAoSamplingDataSize Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Input the user buffer storage generation times
            #----------------------------------------
            print("")
            while True:
                print("Please input the user buffer storage generation 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 two new line
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n")
                    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)
            #----------------------------------------
            # 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 that is necessary for one generating x generating times
            #--------------------
            ao_generating_buffer_size = ctypes.c_long(ao_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 Settings Error")
                print("Failed to allocate the user buffer\n")
                continue
            #----------------------------------------
            # Get the resolution of the analog output
            #----------------------------------------
            lret.value = caio.AioGetAoResolution(id, ctypes.byref(ao_resolution))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nUser Buffer Settings 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, ao_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 * ao_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 Settings 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, ao_data_size.value):
                    text_string += f" {ctypes.c_uint(ao_generating_buffer[i * ao_data_size.value + j]).value:08X}"
                    #--------------------
                    # Add newline character for the last packet
                    #--------------------
                    if j == (ao_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 Settings Error")
                print(f"AioSetAoTransferData Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that user buffer settings is completed
            #----------------------------------------
            print("\nUser Buffer Settings : Successful completion")
            print(f"User Buffer Storage Generation Times = {ao_generating_times}\n")
        #--------------------
        # 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("")
        #--------------------
        # AioGetAoStatus
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # 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 == "11":
            #----------------------------------------
            # 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
            #----------------------------------------
            lret.value = caio.AioGetAoStatus(id, ctypes.byref(ao_status))
            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
            #----------------------------------------
            # Display the message that generating stop is completed
            #----------------------------------------
            print("\nGenerating Stop : Successful completion")
            #----------------------------------------
            # Display the transfer position, status
            #----------------------------------------
            print(f"Transfer Position = {ao_transfer_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string})\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "12":
            #----------------------------------------
            # 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()