#================================================================
#================================================================
# API-AIO(WDM)
# Digital general purpose input and 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
    port_no = ctypes.c_short()                      # Port number
    bit_no = ctypes.c_short()                       # Bit number
    data = ctypes.c_short()                         # I/O data
    direction = ctypes.c_long()                     # I/O direction

    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the I/O direction
        #--------------------
        lret.value = caio.AioGetDioDirection(id, ctypes.byref(direction))
        if lret.value != 0:
            direction_string = "-"
        else:
            direction_string = GetDirectionString(direction)
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"I/O Direction : {direction_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print("1 : AioInit")
        print("2 : AioResetDevice")
        print("3 : AioSetDioDirection")
        print("4 : AioInputDiByte")
        print("5 : AioInputDiBit")
        print("6 : AioOutputDoByte")
        print("7 : AioOutputDoBit")
        print("8 : 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")
        #--------------------
        # 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")
        #--------------------
        # AioSetDioDirection
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Input the I/O direction
            #----------------------------------------
            print("")
            while True:
                print("Please input the I/O direction[Dec] : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            direction = ctypes.c_long(int(buf))
            #----------------------------------------
            # Set the I/O direction
            #----------------------------------------
            lret.value = caio.AioSetDioDirection(id, direction)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioSetDioDirection Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                direction_string = GetDirectionString(direction)
                print(f"I/O Direction = {direction_string}")
            print("")
        #--------------------
        # AioInputDiByte
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # Input the port number
            #----------------------------------------
            print("")
            while True:
                print("Please input the port number[Dec] : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            port_no = ctypes.c_short(int(buf))
            #----------------------------------------
            # One port digital input
            #----------------------------------------
            lret.value = caio.AioInputDiByte(id, port_no, ctypes.byref(data))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioInputDiByte Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Port{port_no.value} Input Data = 0x{data.value:02X}")
            print("")
        #--------------------
        # AioInputDiBit
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Input the bit number
            #----------------------------------------
            print("")
            while True:
                print("Please input the bit number[Dec] : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            bit_no = ctypes.c_short(int(buf))
            #----------------------------------------
            # One bit digital input
            #----------------------------------------
            lret.value = caio.AioInputDiBit(id, bit_no, ctypes.byref(data))
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioInputDiBit Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Bit{bit_no.value} Input Data = {data.value}")
            print("")
        #--------------------
        # AioOutputDoByte
        #--------------------
        elif buf == "6":
            print("\n----------------------------------------")
            print("Start AioOutputDoByte")
            print("----------------------------------------")
            #----------------------------------------
            # Input the port number
            #----------------------------------------
            while True:
                print("Please input the port number[Dec] : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            port_no = ctypes.c_short(int(buf))
            #----------------------------------------
            # Input the output data
            #----------------------------------------
            print("")
            while True:
                print("Please input the output data[Hex] : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 16):
                    continue
                break
            data = ctypes.c_short(int(buf, 16))
            #----------------------------------------
            # One port digital output
            #----------------------------------------
            lret.value = caio.AioOutputDoByte(id, port_no, data)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioOutputDoByte Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # AioOutputDoBit
        #--------------------
        elif buf == "7":
            print("\n----------------------------------------")
            print("Start AioOutputDoBit")
            print("----------------------------------------")
            #----------------------------------------
            # Input the bit number
            #----------------------------------------
            while True:
                print("Please input the bit number[Dec] : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            bit_no = ctypes.c_short(int(buf))
            #----------------------------------------
            # Input the output data
            #----------------------------------------
            print("")
            while True:
                print("Please input the output data[Dec] : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            data = ctypes.c_short(int(buf))
            #----------------------------------------
            # One bit digital output
            #----------------------------------------
            lret.value = caio.AioOutputDoBit(id, bit_no, data)
            caio.AioGetErrorString(lret, error_buf)
            print(f"\nAioOutputDoBit Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # AioExit
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # 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()
