#================================================================
#================================================================
# API-AIO(WDM)
# Simple analog input 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
    ai_range = ctypes.c_short()                     # Range
    ai_input_method = ctypes.c_short()              # Input method
    ai_channel = ctypes.c_short()                   # Channel number
    ai_data_single = ctypes.c_float()               # Single input data
    ai_channels = ctypes.c_short()                  # Number of channels
    ai_data_multi_type = ctypes.c_float * 256       # Create the array type (Multiple input data)
    ai_data_multi = ai_data_multi_type()            # Multi input data

    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the range value
        #--------------------
        lret.value = caio.AioGetAiRange(id, 0, ctypes.byref(ai_range))
        if lret.value != 0:
            ai_range_string = "-"
        else:
            ai_range_string = GetRangeString(ai_range)
        #--------------------
        # Get the input method
        #--------------------
        lret.value = caio.AioGetAiInputMethod(id, ctypes.byref(ai_input_method))
        if lret.value != 0:
            ai_input_method_string = "-"
        else:
            ai_input_method_string = GetInputMethodString(ai_input_method)
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"Range        : {ai_range_string}")
        print(f"Input Method : {ai_input_method_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print("1 : AioInit")
        print("2 : AioSetAiRangeAll")
        print("3 : AioSetAiInputMethod")
        print("4 : AioSingleAiEx")
        print("5 : AioMultiAiEx")
        print("6 : 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")
        #--------------------
        # AioSetAiRangeAll
        #--------------------
        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\t102 : +/-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
            ai_range = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the range
            #----------------------------------------
            lret.value = caio.AioSetAiRangeAll(id, ai_range)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiRangeAll Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                ai_range_string = GetRangeString(ai_range)
                print(f"Range = {ai_range.value}({ai_range_string})")
            print("")
        #--------------------
        # AioSetAiInputMethod
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Input the input method
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Input method)")
            print("----------------------------------------")
            print("0 : Single-end input")
            print("1 : Differential input")
            while True:
                print("Please input the input method : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ai_input_method = ctypes.c_short(int(buf))
            #----------------------------------------
            # Set the input method
            #----------------------------------------
            lret.value = caio.AioSetAiInputMethod(id, ai_input_method)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetAiInputMethod Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                ai_input_method_string = GetInputMethodString(ai_input_method)
                print(f"Input Method = {ai_input_method.value}({ai_input_method_string})")
            print("")
        #--------------------
        # AioSingleAiEx
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # Input the channel number
            #----------------------------------------
            print("")
            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
            ai_channel = ctypes.c_short(int(buf))
            #----------------------------------------
            # Analog input once from the specified channel
            #----------------------------------------
            lret.value = caio.AioSingleAiEx(id, ai_channel, ctypes.byref(ai_data_single))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSingleAiEx Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                if (ai_range.value == caio.P20MA) or (ai_range.value == caio.P4TO20MA) or (ai_range.value == caio.PM20MA):
                    print(f"Channel{ai_channel.value:<3d} Input Data = {ai_data_single.value:2.5f}[mA]")
                else:
                    print(f"Channel{ai_channel.value:<3d} Input Data = {ai_data_single.value:2.5f}[V]")
            print("")
        #--------------------
        # AioMultiAiEx
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Input the number of channels
            #----------------------------------------
            print("")
            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
            ai_channels = ctypes.c_short(int(buf))
            #----------------------------------------
            # Analog input once from multi-channels
            #----------------------------------------
            lret.value = caio.AioMultiAiEx(id, ai_channels, ai_data_multi)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioMultiAiEx Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                if (ai_range.value == caio.P20MA) or (ai_range.value == caio.P4TO20MA) or (ai_range.value == caio.PM20MA):
                    for i in range(0, ai_channels.value):
                        print(f"Channel{i:<3d} Input Data = {ai_data_multi[i]:2.5f}[mA]")
                else:
                    for i in range(0, ai_channels.value):
                        print(f"Channel{i:<3d} Input Data = {ai_data_multi[i]:2.5f}[V]")
            print("")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # 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()