#================================================================
#================================================================
# API-AIO(WDM)
# Simple analog output sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import caio
from CommonFunction import *


#========================================
# 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_channel = ctypes.c_short()                   # Channel number
    ao_data_single = ctypes.c_float()               # Single output data
    ao_channels = ctypes.c_short()                  # Number of channels
    ao_data_multi_type = ctypes.c_float * 256       # Create the array type(Multi output data)
    ao_data_multi = ao_data_multi_type()            # Multi output data

    #----------------------------------------
    # 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)
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"Range : {ao_range_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print("1 : AioInit")
        print("2 : AioSetAoRangeAll")
        print("3 : AioSingleAoEx")
        print("4 : AioMultiAoEx")
        print("5 : AioExit")
        print("q : Quit")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # AioInit
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Input the device name
            #----------------------------------------
            print("\nPlease input the device name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            #----------------------------------------
            # 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")
        #--------------------
        # AioSetAoRangeAll
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # 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)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # 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("")
        #--------------------
        # AioSingleAoEx
        #--------------------
        elif buf == "3":
            print("\n----------------------------------------")
            print("Start AioSingleAoEx")
            print("----------------------------------------")
            #----------------------------------------
            # Input the channel number
            #----------------------------------------
            while True:
                print("Please input the channel number : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channel = ctypes.c_short(int(buf))
            #----------------------------------------
            # Input the output data
            #----------------------------------------
            print("")
            while True:
                print("Please input the output data : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 0):
                    continue
                break
            ao_data_single = ctypes.c_float(float(buf))
            #----------------------------------------
            # Analog output once from the specified channel
            #----------------------------------------
            lret.value = caio.AioSingleAoEx(id, ao_channel, ao_data_single)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSingleAoEx Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # AioMultiAoEx
        #--------------------
        elif buf == "4":
            print("\n----------------------------------------")
            print("Start AioMultiAoEx")
            print("----------------------------------------")
            #----------------------------------------
            # Input the number of channels
            #----------------------------------------
            while True:
                print("Please input the number of channels : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channels = ctypes.c_short(int(buf))
            #----------------------------------------
            # Input the output data
            #----------------------------------------
            print("")
            print("Please input the output data")
            if (ao_range.value == caio.P20MA) or (ao_range.value == caio.P4TO20MA):
                for i in range(0, ao_channels.value):
                    while True:
                        print(f"Channel{i:<3d}[mA] : ", end='', flush=True)
                        #----------------------------------------
                        # Waiting for input
                        #----------------------------------------
                        buf = input()
                        #----------------------------------------
                        # Check if the input value is a number
                        #----------------------------------------
                        if False == isnum(buf, 0):
                            continue
                        break
                    ao_data_multi[i] = ctypes.c_float(float(buf))
            else:
                for i in range(0, ao_channels.value):
                    while True:
                        print(f"Channel{i:<3d}[V] : ", end='', flush=True)
                        #----------------------------------------
                        # Waiting for input
                        #----------------------------------------
                        buf = input()
                        #----------------------------------------
                        # Check if the input value is a number
                        #----------------------------------------
                        if False == isnum(buf, 0):
                            continue
                        break
                    ao_data_multi[i] = ctypes.c_float(float(buf))
            #----------------------------------------
            # Analog output once from multi-channels
            #----------------------------------------
            lret.value = caio.AioMultiAoEx(id, ao_channels, ao_data_multi)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioMultiAoEx Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Exit process
            #----------------------------------------
            lret.value = caio.AioExit(id)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioExit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # Quit
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    #----------------------------------------
    # Exit process
    #----------------------------------------
    caio.AioExit(id)
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


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