#================================================================
#================================================================
# API-AIO(WDM)
# Finite generating using device buffer sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import math
import caio
from CommonFunction import *
#----------------------------------------
# Declaration of global variables
#----------------------------------------
g_generating_data = None    # Output data

#========================================
# 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_generating_count = ctypes.c_long()           # Generating 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 current generating count
        #----------------------------------------
        lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDevice Operation End Event Process : AioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\r"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Display the generating count, status
        #----------------------------------------
        text_buf = f"\nDevice Operation End Event Process : Successful completion\nGenerating Count = {ao_generating_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 current generating count
        #----------------------------------------
        lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nSampling Clock Error Occurrence Process : AioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\r"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Display the generating count, status
        #----------------------------------------
        text_buf = f"\nSampling Clock Error Occurrence Process : Successful completion\nGenerating Count = {ao_generating_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 current generating count
        #----------------------------------------
        lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
        if lret.value != 0:
            caio.AioGetErrorString(lret, error_buf)
            text_buf = f"\nDA Conversion Error Occurrence Process : AioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\r"
            PrintOnMultiLines(text_buf, 1)
            return
        #----------------------------------------
        # Display the generating count, status
        #----------------------------------------
        text_buf = f"\nDA Conversion Error Occurrence Process : Successful completion\nGenerating Count = {ao_generating_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_generating_clock = ctypes.c_float()          # Generating clock period
    ao_generating_times = ctypes.c_long(1000)       # Generating times
    ao_generating_count = ctypes.c_long(0)          # Generating count
    global g_generating_data                        # Output data
    global g_lock                                   # Mutex
    global g_info_flag                              # A flag showing the generating count, status in the callback

    #----------------------------------------
    # Initialize the variable
    #----------------------------------------
    g_info_flag.value = 0
    #----------------------------------------
    # Lock
    #----------------------------------------
    g_lock.acquire()
    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the range value
        #--------------------
        lret.value = caio.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 generating times
        #--------------------
        if initialized == 0:
            ao_generating_times_string = "-"
        else:
            ao_generating_times_string = f"{ao_generating_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"Generating Clock Period : {ao_generating_clock_string}")
        print(f"Generating 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 : Generate Output Data")
        print(" 8 : AioSetAoSamplingDataEx")
        print(" 9 : Generating Start")
        print("10 : AioGetAoSamplingCount")
        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 generating count, 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 generating count, 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 generating count, 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 generating count, 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 generating count, 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 data storage memory type to FIFO
            # Caution for modify this function (if modified, the application may not work)
            #----------------------------------------
            lret.value = caio.AioSetAoMemoryType(id, 0)
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\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")
        #--------------------
        # Generate Output Data
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Input the generating times
            #----------------------------------------
            print("")
            while True:
                print("Please input the generating times : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_lock.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_lock.acquire()
                #----------------------------------------
                # If the generating count, 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 = ctypes.c_long(int(buf))
            #----------------------------------------
            # Allocate the array for storing output data
            #----------------------------------------
            #--------------------
            # Release the array for storing output data if it has been allocated
            #--------------------
            if g_generating_data is not None:
                g_generating_data = None
            #--------------------
            # Allocate the array for storing output data
            #--------------------
            try:
                g_generating_data_type = ctypes.c_float * (ao_generating_times.value * ao_channels.value)
                g_generating_data = g_generating_data_type()
            except:
                ao_generating_times.value = 0
                print("\nGenerate Output Data Error")
                print("Failed to allocate the array for storing data\n")
                continue
            #----------------------------------------
            # Create analog output data : sine waveform
            #----------------------------------------
            gain, offset = GetSineCoefficient(ao_range)
            for i in range(0, ao_generating_times.value):
                for j in range(0, ao_channels.value):
                    g_generating_data[i * ao_channels.value + j] = float(gain * math.sin(2 * 3.14159265358979 * i / ao_generating_times.value + 3.14159265358979 / 2 * (j % 4)) + offset)
            #----------------------------------------
            # Open file
            #----------------------------------------
            try:
                file = open("./GeneratingData.csv", 'w')
            except:
                #----------------------------------------
                # Release the array for storing output data if it has been allocated
                #----------------------------------------
                if g_generating_data is not None:
                    g_generating_data = None
                ao_generating_times.value = 0
                print("\nGenerate Output Data Error")
                print("Failed to create the file\n")
                continue
            #----------------------------------------
            # Create file
            #----------------------------------------
            for i in range(0, ao_generating_times.value):
                #--------------------
                # Generate the string
                #--------------------
                text_string = f"{i + 1:5d},"
                #--------------------
                # Repeat the process for the specified number of channels
                #--------------------
                for j in range(0, ao_channels.value):
                    text_string += f" {g_generating_data[i * ao_channels.value + j]:10.5f}"
                    #--------------------
                    # Add newline character for the last channel
                    #--------------------
                    if j == ao_channels.value - 1:
                        text_string += "\n"
                    #--------------------
                    # Add comma for channels other than the last channel
                    #--------------------
                    else:
                        text_string += ","
                #----------------------------------------
                # Write data
                #----------------------------------------
                file.write(text_string)
            #----------------------------------------
            # Close file
            #----------------------------------------
            file.close()
            #----------------------------------------
            # Display the message that output data generation is completed
            #----------------------------------------
            print("\nGenerate Output Data : Successful completion")
            print(f"Generating Times = {ao_generating_times.value}\n")
        #--------------------
        # AioSetAoSamplingDataEx
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Set analog output data
            #----------------------------------------
            lret.value = caio.AioSetAoSamplingDataEx(id, ao_generating_times, g_generating_data)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAoSamplingDataEx Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Generating Start
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # 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
            #----------------------------------------
            # If the output data does not exist
            #----------------------------------------
            if g_generating_data is None:
                #----------------------------------------
                # Allocate the array for storing output data
                #----------------------------------------
                try:
                    g_generating_data_type = ctypes.c_float * (ao_generating_times.value * ao_channels.value)
                    g_generating_data = g_generating_data_type()
                except:
                    ao_generating_times.value = 0
                    print("\nGenerating Start Error")
                    print("Failed to allocate the array for storing data\n")
                    continue
                #----------------------------------------
                # Create analog output data : sine waveform
                #----------------------------------------
                gain, offset = GetSineCoefficient(ao_range)
                for i in range(0, ao_generating_times.value):
                    for j in range(0, ao_channels.value):
                        g_generating_data[i * ao_channels.value + j] = float(gain * math.sin(2 * 3.14159265358979 * i / ao_generating_times.value + 3.14159265358979 / 2 * (j % 4)) + offset)
                #----------------------------------------
                # Set analog output data
                #----------------------------------------
                lret.value = caio.AioSetAoSamplingDataEx(id, ao_generating_times, g_generating_data)
                if lret.value != 0:
                    caio.AioGetErrorString(lret, error_buf)
                    print("\nGenerating Start Error")
                    print(f"AioSetAoSamplingDataEx 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")
        #--------------------
        # AioGetAoSamplingCount
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # Get the generating count
            #----------------------------------------
            lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Generating Count = {ao_generating_count.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
            #----------------------------------------
            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 generating count
            #----------------------------------------
            lret.value = caio.AioGetAoSamplingCount(id, ctypes.byref(ao_generating_count))
            if lret.value != 0:
                caio.AioGetErrorString(lret, error_buf)
                print("\nGenerating Stop Error")
                print(f"AioGetAoSamplingCount Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
                continue
            #----------------------------------------
            # Display the message that generating stop is completed
            #----------------------------------------
            print("\nGenerating Stop : Successful completion")
            #----------------------------------------
            # Display the generating count, status
            #----------------------------------------
            print(f"Generating Count = {ao_generating_count.value:<8d} Status = 0x{ao_status.value:08x}({ao_status_string})\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "13":
            #----------------------------------------
            # Release the array for storing output data if it has been allocated
            #----------------------------------------
            if g_generating_data is not None:
                g_generating_data = None
            #----------------------------------------
            # Exit process
            #----------------------------------------
            lret.value = caio.AioExit(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
            #----------------------------------------
            # Set the initialization flag
            #----------------------------------------
            if lret.value == 0:
                initialized = 0
        #--------------------
        # Quit
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    #----------------------------------------
    # Release the array for storing output data if it has been allocated
    #----------------------------------------
    if g_generating_data is not None:
        g_generating_data = None
    #----------------------------------------
    # Exit process
    #----------------------------------------
    caio.AioExit(id)
    #----------------------------------------
    # Unlock
    #----------------------------------------
    g_lock.release()
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


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