﻿#================================================================
#================================================================
# API-AIO(WDM)
# Timer sample
# main file
#                                                 CONTEC Co.,Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import caio
from TimerUI import TimerUI


#========================================
# Timer class
#========================================
class Timer:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.id = ctypes.c_short()              # ID for device access
        self.timer_id = ctypes.c_short(0)       # Timer ID
        self.event_count = 0                    # Interval elapsed event occurrence count
        self.ptm_callback = None                # Pointer to callback function
        self.user_data = None                   # User data of callback function
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = TimerUI()
        #----------------------------------------
        # Set the callback function for the UI controls
        #----------------------------------------
        self.ui.setup_commands(
            command_aio_init=self.OnClickedButtonAioInit,
            command_aio_reset_device=self.OnClickedButtonAioResetDevice,
            command_interval_start=self.OnClickedButtonIntervalStart,
            command_interval_stop=self.OnClickedButtonIntervalStop,
            command_watch_start=self.OnClickedButtonWatchStart,
            command_aio_lap_tm_count=self.OnClickedButtonAioLapTmCount,
            command_aio_reset_tm_count=self.OnClickedButtonAioResetTmCount,
            command_watch_stop=self.OnClickedButtonWatchStop,
            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    CallBackProc
    # Parameter        id          Id get by AioInit
    # Parameter        tm_event    The event that occurred
    # Parameter        wParam      Parameter passed from driver
    # Parameter        lParam      Parameter unique to each event
    # Parameter        Param       Parameter specified in the AioSetTmCallBackProc function
    # Details          Function registered with the AioSetTmCallBackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def CallBackProc(id, tm_event, wParam, lParam, Param):
        #----------------------------------------
        # Create class object
        #----------------------------------------
        obj_ptr = ctypes.cast(Param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Process of Event that interval elapses
        #----------------------------------------
        if tm_event == caio.AIOM_TME_INT:
            #----------------------------------------
            # Display the interval elapsed event occurrence count
            #----------------------------------------
            self.event_count += 1
            text_buf = f"{self.event_count}"
            self.ui.textbox_event_count_var.set(text_buf)

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

        #----------------------------------------
        # Set the callback routine: 'Event that interval elapses'.
        # Caution for modify this function (if modified, the application may not work)
        #----------------------------------------
        self.ptm_callback = caio.PAIO_TM_CALLBACK(self.CallBackProc)
        self.user_data = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p)
        lret.value = caio.AioSetTmCallBackProc(self.id, self.timer_id, self.ptm_callback, (caio.TME_INT), self.user_data)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Operation Start : AioSetTmCallBackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Initialize notification count
        #----------------------------------------
        self.event_count = 0
        #----------------------------------------
        # Get the interval from textbox
        #----------------------------------------
        buf = self.ui.textbox_interval_var.get()
        #----------------------------------------
        # Check if the input value is a number
        #----------------------------------------
        if False == self.isnum(buf, 0):
            self.ui.show_error("Error", "The input value is invalid.")
            return
        else:
            interval = ctypes.c_float(float(buf))
        #----------------------------------------
        # Start operation
        #----------------------------------------
        lret.value = caio.AioStartTmTimer(self.id, self.timer_id, interval)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Operation Start : AioStartTmTimer = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display the message that operation start is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Operation Start : Successful completion")

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

        #----------------------------------------
        # Stop operation
        #----------------------------------------
        lret.value = caio.AioStopTmTimer(self.id, self.timer_id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Operation Stop : AioStopTmTimer = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display the message that operation stop is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Operation Stop : Successful completion")

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

        #----------------------------------------
        # Start measurement
        #----------------------------------------
        lret.value = caio.AioStartTmCount(self.id, self.timer_id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Operation Start : AioStartTmCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display the message that measurement start is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Operation Start : Successful completion")

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

        #----------------------------------------
        # Get the elapsed time
        #----------------------------------------
        lret.value = caio.AioLapTmCount(self.id, self.timer_id, ctypes.byref(lap))
        #----------------------------------------
        # Get error string
        #----------------------------------------
        caio.AioGetErrorString(lret, error_string)
        #----------------------------------------
        # Display message
        #----------------------------------------
        text_buf = f"AioLapTmCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        #----------------------------------------
        # When the elapsed time acquisition function is completed successfully
        #----------------------------------------
        if lret.value == 0:
            #----------------------------------------
            # Display the elapsed time
            #----------------------------------------
            text_buf = f"{lap.value}"
            self.ui.textbox_lap_time_var.set(text_buf)

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

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

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

        #----------------------------------------
        # Stop measurement
        #----------------------------------------
        lret.value = caio.AioStopTmCount(self.id, self.timer_id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        if lret.value != 0:
            #--------------------
            # Get error string
            #--------------------
            caio.AioGetErrorString(lret, error_string)
            #--------------------
            # Display message
            #--------------------
            text_buf = f"Operation Stop : AioStopTmCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Display the message that measurement stop is completed
        #----------------------------------------
        self.ui.textbox_return_string_var.set("Operation Stop : Successful completion")

    #========================================
    # 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 Timer
    #----------------------------------------
    instance = Timer()
    instance.run()

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