#================================================================
#================================================================
# API-DIO(WDM)
# Interrupt Sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import cdio
from InterruptUI import InterruptUI


#========================================
# Interrupt class
#========================================
class Interrupt:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()            # ID for device access
        self.up_count = [0] * 4               # Up counter
        self.down_count = [0] * 4             # Down counter
        self.textbox_up_var = [None] * 8      # Up counter display
        self.textbox_down_var = [None] * 8    # Down counter display
        self.pint_callback = None             # Point to callback function
        self.user_data = None                 # User data of callback function
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = InterruptUI()
        #----------------------------------------
        # Set the up counter array for the textbox
        #----------------------------------------
        self.textbox_up_var[0] = self.ui.textbox_up0_var
        self.textbox_up_var[1] = self.ui.textbox_up1_var
        self.textbox_up_var[2] = self.ui.textbox_up2_var
        self.textbox_up_var[3] = self.ui.textbox_up3_var
        #----------------------------------------
        # Set the down counter array for the textbox
        #----------------------------------------
        self.textbox_down_var[0] = self.ui.textbox_down0_var
        self.textbox_down_var[1] = self.ui.textbox_down1_var
        self.textbox_down_var[2] = self.ui.textbox_down2_var
        self.textbox_down_var[3] = self.ui.textbox_down3_var
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_dio_init=self.OnClickedButtonDioInit,
            command_int_start=self.OnClickedButtonIntstart,
            command_int_stop=self.OnClickedButtonIntstop,
            command_dio_exit=self.OnClickedButtonDioExit,
            command_exit=self.OnClickedButtonExit
        )

    #========================================
    # Function name    LOWORD
    # Parameter        a    The value to be converted
    # Details          Function to get the low-order word from the specified value.
    # Return value     Low-order word
    #========================================
    @staticmethod
    def LOWORD(a):
        return a & 0xffff

    #========================================
    # Function name    HIWORD
    # Parameter        a    The value to be converted
    # Details          Function to get the high-order word from the specified value.
    # Return value     High-order word
    #========================================
    @staticmethod
    def HIWORD(a):
        return (a >> 16) & 0xffff

    #========================================
    # Function name    CallBackProc
    # Parameter        id        Id get by DioInit
    # Parameter        wparam    Parameter passed from driver
    # Parameter        lparam    Parameter unique to each event
    # Parameter        param     Parameter specified in the DioSetInterruptCallBackProc function
    # Details          Function registered with the DioSetInterruptCallBackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def CallBackProc(id, wparam, lparam, param):
        #----------------------------------------
        # Create the class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Interrupt message process
        #----------------------------------------
        #----------------------------------------
        # Interrupt bit number
        #----------------------------------------
        bit_no = self.LOWORD(lparam)
        #----------------------------------------
        # Rising edge:1, Falling edge:2
        #----------------------------------------
        kind = self.HIWORD(lparam)
        #----------------------------------------
        # Up counter
        #----------------------------------------
        if kind == cdio.DIO_INT_RISE:
            self.up_count[bit_no] += 1
        #----------------------------------------
        # Down counter
        #----------------------------------------
        if kind == cdio.DIO_INT_FALL:
            self.down_count[bit_no] += 1
        #----------------------------------------
        # Display
        #----------------------------------------
        text_buf = f"{self.up_count[bit_no]}"
        self.textbox_up_var[bit_no].set(text_buf)
        text_buf = f"{self.down_count[bit_no]}"
        self.textbox_down_var[bit_no].set(text_buf)
        return

    #========================================
    # 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    OnClickedButtonIntstart
    # Parameter        None
    # Details          Start Interrupt button click event function
    # Return value     None
    #========================================
    def OnClickedButtonIntstart(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Set callback routine
        #----------------------------------------
        self.pint_callback = cdio.PDIO_INT_CALLBACK(self.CallBackProc)
        self.user_data = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p)
        lret.value = cdio.DioSetInterruptCallBackProc(self.id, self.pint_callback, self.user_data)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioSetInterruptCallBackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Parameters initialization
        #----------------------------------------
        for i in range(0, 4):
            self.up_count[i] = 0
            self.down_count[i] = 0
        #----------------------------------------
        # Get interrupt logic
        #----------------------------------------
        if self.ui.radio_logic_var.get() == 0:
            kind = cdio.DIO_INT_RISE
        else:
            kind = cdio.DIO_INT_FALL
        #----------------------------------------
        # Interrupt start
        #----------------------------------------
        for bit_no in range(0, 4):
            lret.value = cdio.DioNotifyInterrupt(self.id, bit_no, kind, 0)
            if lret.value != cdio.DIO_ERR_SUCCESS:
                break
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioNotifyInterrupt = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

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

        #----------------------------------------
        # Interrupt stop
        #----------------------------------------
        for bit_no in range(0, 4):
            lret.value = cdio.DioNotifyInterrupt(self.id, bit_no, cdio.DIO_INT_NONE, 0)
            if lret.value != cdio.DIO_ERR_SUCCESS:
                break
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioNotifyInterrupt = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_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 Interrupt
    #----------------------------------------
    instance = Interrupt()
    instance.run()

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