#================================================================
#================================================================
# API-AIO(WDM)
# Digital general purpose input and output sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import caio
from DigitalIOUI import DigitalIOUI


#========================================
# DigitalIO class
#========================================
class DigitalIO:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()    # ID for device access
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = DigitalIOUI()
        #----------------------------------------
        # Set the callback function for the UI controls
        #----------------------------------------
        self.ui.setup_commands(
            command_aio_init=self.OnClickedButtonAioInit,
            command_aio_reset_device=self.OnClickedButtonAioResetDevice,
            command_aio_set_dio_direction=self.OnClickedButtonAioSetDioDirection,
            command_aio_input_di_byte=self.OnClickedButtonAioInputDiByte,
            command_aio_input_di_bit=self.OnClickedButtonAioInputDiBit,
            command_aio_output_do_byte=self.OnClickedButtonAioOutputDoByte,
            command_aio_output_do_bit=self.OnClickedButtonAioOutputDoBit,
            command_aio_exit=self.OnClickedButtonAioExit,
            command_close=self.OnClickedButtonClose
        )

    #========================================
    # Function name    isnum
    # Parameter        str     String
    # Parameter        base    Base
    # Details          Function to checks if a string can be converted to a number
    # Return value     True: Can be converted
    #                  False: Can not be converted
    #========================================
    @staticmethod
    def isnum(str, base):
        try:
            if 10 == base:
                int(str, 10)
            elif 16 == base:
                int(str, 16)
            else:
                float(str)
        except:
            return False
        return True

    #========================================
    # Function name    OnClickedButtonAioInit
    # Parameter        None
    # Details          AioInit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioInit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get device name from textbox
        #----------------------------------------
        device_name = self.ui.textbox_device_name_var.get()
        #----------------------------------------
        # Device initialization
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        lret.value = caio.AioInit(device_name.encode(), ctypes.byref(self.id))
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioInit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioResetDevice
    # Parameter        None
    # Details          AioResetDevice button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioResetDevice(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Reset device
        #----------------------------------------
        lret.value = caio.AioResetDevice(self.id)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioResetDevice = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioSetDioDirection
    # Parameter        None
    # Details          AioSetDioDirection button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioSetDioDirection(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get I/O direction from textbox
        #----------------------------------------
        buf = self.ui.textbox_io_direction_var.get()
        #----------------------------------------
        # Check if the input value is a number
        #----------------------------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            io_direction = ctypes.c_long(int(buf))
        #----------------------------------------
        # Set I/O direction of digital I/O ports
        #----------------------------------------
        lret.value = caio.AioSetDioDirection(self.id, io_direction)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioSetDioDirection = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioInputDiByte
    # Parameter        None
    # Details          AioInputDiByte button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioInputDiByte(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        di_data = ctypes.c_short()                         # Input data

        #----------------------------------------
        # Get port No. from textbox
        #----------------------------------------
        buf = self.ui.textbox_input_byte_no_var.get()
        #----------------------------------------
        # Check if the input value is a number
        #----------------------------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            di_port = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get specified port data
        #----------------------------------------
        lret.value = caio.AioInputDiByte(self.id, di_port, ctypes.byref(di_data))
        #----------------------------------------
        # Error process
        #----------------------------------------
        #--------------------
        # Get error string
        #--------------------
        caio.AioGetErrorString(lret, error_string)
        #--------------------
        # Display message
        #--------------------
        text_buf = f"AioInputDiByte = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #--------------------
        # Exit the process if not completed successfully
        #--------------------
        if lret.value != 0:
            return
        #----------------------------------------
        # Display specified port data
        #----------------------------------------
        text_buf = f"{di_data.value:02X}"
        self.ui.textbox_input_byte_data_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioInputDiBit
    # Parameter        None
    # Details          AioInputDiBit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioInputDiBit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        di_data = ctypes.c_short()                         # Input data

        #----------------------------------------
        # Get bit No. from textbox
        #----------------------------------------
        buf = self.ui.textbox_input_bit_no_var.get()
        #----------------------------------------
        # Check if the input value is a number
        #----------------------------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            di_bit = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get specified bit data
        #----------------------------------------
        lret.value = caio.AioInputDiBit(self.id, di_bit, ctypes.byref(di_data))
        #----------------------------------------
        # Error process
        #----------------------------------------
        #--------------------
        # Get error string
        #--------------------
        caio.AioGetErrorString(lret, error_string)
        #--------------------
        # Display message
        #--------------------
        text_buf = f"AioInputDiBit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #--------------------
        # Exit the process if not completed successfully
        #--------------------
        if lret.value != 0:
            return
        #----------------------------------------
        # Display specified bit data
        #----------------------------------------
        text_buf = f"{di_data.value}"
        self.ui.textbox_input_bit_data_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioOutputDoByte
    # Parameter        None
    # Details          AioOutputDoByte button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioOutputDoByte(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get port No. from textbox
        #----------------------------------------
        buf = self.ui.textbox_output_byte_no_var.get()
        #----------------------------------------
        # Check if the input value is a number
        #----------------------------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            do_port = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get output data from textbox
        #----------------------------------------
        buf = self.ui.textbox_output_byte_data_var.get()
        #----------------------------------------
        # Check if the input value is a number
        #----------------------------------------
        if False == self.isnum(buf, 16):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            do_data = ctypes.c_short(int(buf, 16))
        #----------------------------------------
        # Output data to specified digital output byte
        #----------------------------------------
        lret.value = caio.AioOutputDoByte(self.id, do_port, do_data)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioOutputDoByte = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioOutputDoBit
    # Parameter        None
    # Details          AioOutputDoBit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioOutputDoBit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get bit No. from textbox
        #----------------------------------------
        buf = self.ui.textbox_output_bit_no_var.get()
        #----------------------------------------
        # Check if the input value is a number
        #----------------------------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            do_bit = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get output data from textbox
        #----------------------------------------
        buf = self.ui.textbox_output_bit_data_var.get()
        #----------------------------------------
        # Check if the input value is a number
        #----------------------------------------
        if False == self.isnum(buf, 10):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            do_data = ctypes.c_short(int(buf))
        #----------------------------------------
        # Output data to specified digital output bit
        #----------------------------------------
        lret.value = caio.AioOutputDoBit(self.id, do_bit, do_data)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioOutputDoBit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonAioExit
    # Parameter        None
    # Details          AioExit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonAioExit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Exit process
        #----------------------------------------
        lret.value = caio.AioExit(self.id)
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioExit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonClose
    # Parameter        None
    # Details          Close button click event function
    # Return value     None
    #========================================
    def OnClickedButtonClose(self):
        #----------------------------------------
        # Exit process
        #----------------------------------------
        caio.AioExit(self.id)
        #----------------------------------------
        # Close window
        #----------------------------------------
        self.ui.root.destroy()

    #========================================
    # Function name    run
    # Parameter        None
    # Details          Run the application function
    # Return value     None
    #========================================
    def run(self):
        self.ui.run()


#========================================
# main function
#========================================
def main():
    #----------------------------------------
    # Create and Run DigitalIO
    #----------------------------------------
    instance = DigitalIO()
    instance.run()

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