#================================================================
#================================================================
# API-DIO(WDM)
# Simple I/O Sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import cdio
from SimpleIOUI import SimpleIOUI


#========================================
# SimpleIO class
#========================================
class SimpleIO:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()    # ID for device access
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = SimpleIOUI()
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_dio_init=self.OnClickedButtonDioInit,
            command_dio_set_io_direction=self.OnClickedButtonDioSetIoDirection,
            command_dio_inp_byte=self.OnClickedButtonDioInpByte,
            command_dio_inp_bit=self.OnClickedButtonDioInpBit,
            command_dio_out_byte=self.OnClickedButtonDioOutByte,
            command_dio_echo_back_byte=self.OnClickedButtonDioEchoBackByte,
            command_dio_out_bit=self.OnClickedButtonDioOutBit,
            command_dio_echo_back_bit=self.OnClickedButtonDioEchoBackBit,
            command_dio_exit=self.OnClickedButtonDioExit,
            command_exit=self.OnClickedButtonExit
        )

    #========================================
    # Function name    isnum
    # Parameter        str     String
    # Parameter        base    Base
    # Details          Function to check 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    OnClickedButtonDioInit
    # Parameter        None
    # Details          DioInit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioInit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get device name from screen
        #----------------------------------------
        device_name = self.ui.textbox_device_name_var.get()
        #----------------------------------------
        # Execute initialization function and get ID
        #----------------------------------------
        lret.value = cdio.DioInit(device_name.encode(), ctypes.byref(self.id))
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioInit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Get I/O direction
        #----------------------------------------
        buf = self.ui.textbox_dir_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:
            dir = ctypes.c_ulong(int(buf))
        #----------------------------------------
        # Set I/O direction
        #----------------------------------------
        lret.value = cdio.DioSetIoDirection(self.id, dir)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioSetIoDirection = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Get port number from screen
        #----------------------------------------
        buf = self.ui.textbox_inp_port_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:
            inp_port_no = ctypes.c_short(int(buf))
        #----------------------------------------
        # Port input
        #----------------------------------------
        lret.value = cdio.DioInpByte(self.id, inp_port_no, ctypes.byref(inp_port_data))
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioInpByte = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # Data display
        #----------------------------------------
        text_buf = f"{inp_port_data.value:02X}"
        self.ui.textbox_inp_port_data_var.set(text_buf)

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

        #----------------------------------------
        # Get bit number from screen
        #----------------------------------------
        buf = self.ui.textbox_inp_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:
            inp_bit_no = ctypes.c_short(int(buf))
        #----------------------------------------
        # Bit input
        #----------------------------------------
        lret.value = cdio.DioInpBit(self.id, inp_bit_no, ctypes.byref(inp_bit_data))
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioInpBit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # Data display
        #----------------------------------------
        text_buf = f"{inp_bit_data.value:02X}"
        self.ui.textbox_inp_bit_data_var.set(text_buf)

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

        #----------------------------------------
        # Get port number from screen
        #----------------------------------------
        buf = self.ui.textbox_out_port_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:
            out_port_no = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get output data from screen
        #----------------------------------------
        buf = self.ui.textbox_out_port_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:
            out_port_data = ctypes.c_ubyte(int(buf, 16))
        #----------------------------------------
        # Port output
        #----------------------------------------
        lret.value = cdio.DioOutByte(self.id, out_port_no, out_port_data)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioOutByte = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Get bit number from screen
        #----------------------------------------
        buf = self.ui.textbox_out_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:
            out_bit_no = ctypes.c_short(int(buf))
        #----------------------------------------
        # Get output data from screen
        #----------------------------------------
        buf = self.ui.textbox_out_bit_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:
            out_bit_data = ctypes.c_ubyte(int(buf, 16))
        #----------------------------------------
        # Bit output
        #----------------------------------------
        lret.value = cdio.DioOutBit(self.id, out_bit_no, out_bit_data)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioOutBit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioEchoBackByte
    # Parameter        None
    # Details          DioEchoBackByte button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioEchoBackByte(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        out_port_data = ctypes.c_ubyte()                   # Output data

        #----------------------------------------
        # Get port number from screen
        #----------------------------------------
        buf = self.ui.textbox_out_port_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:
            out_port_no = ctypes.c_short(int(buf))
        #----------------------------------------
        # Port EchoBack
        #----------------------------------------
        lret.value = cdio.DioEchoBackByte(self.id, out_port_no, ctypes.byref(out_port_data))
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioEchoBackByte = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # Data display
        #----------------------------------------
        text_buf = f"{out_port_data.value:02X}"
        self.ui.textbox_out_port_data_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonDioEchoBackBit
    # Parameter        None
    # Details          DioEchoBackBit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonDioEchoBackBit(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        out_bit_data = ctypes.c_ubyte()                    # Output data

        #----------------------------------------
        # Get bit number from screen
        #----------------------------------------
        buf = self.ui.textbox_out_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:
            out_bit_no = ctypes.c_short(int(buf))
        #----------------------------------------
        # Bit EchoBack
        #----------------------------------------
        lret.value = cdio.DioEchoBackBit(self.id, out_bit_no, ctypes.byref(out_bit_data))
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioEchoBackBit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # Data display
        #----------------------------------------
        text_buf = f"{out_bit_data.value:02X}"
        self.ui.textbox_out_bit_data_var.set(text_buf)

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

        #----------------------------------------
        # Exit process
        #----------------------------------------
        lret.value = cdio.DioExit(self.id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioExit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonExit
    # Parameter        None
    # Details          Exit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonExit(self):
        #----------------------------------------
        # Exit process
        #----------------------------------------
        cdio.DioExit(self.id)
        #----------------------------------------
        # Exit the window
        #----------------------------------------
        self.ui.root.destroy()

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


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

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