#================================================================
#================================================================
# API-CNT(WDM) for Device with sampling function
# Infinite sampling sample
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import subprocess
import os
import ctypes
import ccnt
from InfiniteUI import InfiniteUI
import Mode
import Condition


#========================================
# Infinite Class
#========================================
class Infinite:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.CHANNEL_NUM = 4                                                            # Max channel number
        self.DATA_NUM = 1000                                                            # Data size
        self.id = ctypes.c_short()                                                      # ID for device access
        self.count_match = (ctypes.c_ulong * self.CHANNEL_NUM)()                        # Array for storing count match data
        self.sampling_data = (ctypes.c_ulong * (self.DATA_NUM * self.CHANNEL_NUM))()    # Data buffer
        self.number_of_data = ctypes.c_long(500)                                        # The number of sampling to notify
        self.file_name = "infinite.csv"                                                 # Name of saving file
        self.read_index = ctypes.c_ulong(0)                                             # Read pointer
        self.write_index = ctypes.c_ulong(0)                                            # Write pointer
        self.pre_count = ctypes.c_ulong(0)                                              # Last counter value
        self.pre_carry = ctypes.c_ulong(0)                                              # Last carry value
        self.psampling_stop_callback = None                                             # Point to callback function
        self.psampling_count_callback = None                                            # Point to callback function
        self.user_data = None                                                           # User data of callback function
        #----------------------------------------
        # Recording the last settings on the ConditionWindow screen
        #----------------------------------------
        self.condition_window_combobox_start_condition_last_selected = 0
        self.condition_window_combobox_stop_condition_last_selected = 0
        self.condition_window_combobox_clock_condition_last_selected = 0
        self.condition_window_textbox_start_compare_value_last_edit = "100"
        self.condition_window_textbox_stop_compare_value_last_edit = "200"
        self.condition_window_textbox_internal_clock_value_last_edit = "100000"
        self.condition_window_textbox_stop_number_value_last_edit = "1000"
        self.condition_window_radiobutton_counter_start_mode_last_selected = 1
        self.condition_window_radiobutton_counter_stop_mode_last_selected = 1
        self.condition_window_textbox_transfer_event_last_edit = "500"
        #----------------------------------------
        # Recording the last settings on the ModeWindow screen
        #----------------------------------------
        self.mode_window_combobox_counter_mode_last_selected = 0
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = InfiniteUI()
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_cnt_init = self.OnClickedButtonCntInit,
            command_cnt_mode = self.OnClickedButtonCntMode,
            command_cnt_condition = self.OnClickedButtonCondition,
            command_cnt_start = self.OnClickedButtonStart,
            command_cnt_stop = self.OnClickedButtonStop,
            command_cnt_data = self.OnClickedButtonData,
            command_cnt_count = self.OnClickedButtonCount,
            command_cnt_status = self.OnClickedButtonStatus,
            command_cnt_exit = self.OnClickedButtonCntExit,
            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    OnClickedButtonCntInit
    # Parameter        None
    # Details          CntInit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonCntInit(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()
        #----------------------------------------
        # Initialization
        #----------------------------------------
        lret.value = ccnt.CntInit(device_name.encode(), ctypes.byref(self.id))
        #----------------------------------------
        # Get error string
        #----------------------------------------
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntInit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonCntMode
    # Parameter        None
    # Details          Counter mode setting screen display
    # Return value     None
    #========================================
    def OnClickedButtonCntMode(self):
        #----------------------------------------
        # Counter mode setting screen display
        #----------------------------------------
        Mode.ModeWindow(self)

    #========================================
    # Function name    OnClickedButtonCondition
    # Parameter        None
    # Details          Condition setting screen display
    # Return value     None
    #========================================
    def OnClickedButtonCondition(self):
        #----------------------------------------
        # Condition setting screen display
        #----------------------------------------
        Condition.ConditionWindow(self)

    #========================================
    # Function name    OnClickedButtonStart
    # Parameter        None
    # Details          Start transfer
    # Return value     None
    #========================================
    def OnClickedButtonStart(self):
        error_string = ctypes.create_string_buffer(256)        # Error code string
        lret = ctypes.c_long()                                 # For return code
        ch_no = ctypes.c_short()                               # Channel No.
        ch_no_array = (ctypes.c_short * self.CHANNEL_NUM)()    # Array for storing number of channels

        self.psampling_stop_callback = ccnt.PCNT_SAMPLING_STOP_CALLBACK(self.SamplingStopCallBackProc)
        self.psampling_count_callback = ccnt.PCNT_SAMPLING_COUNT_CALLBACK(self.SamplingCountCallBackProc)
        self.user_data = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p)
        #----------------------------------------
        # Set message notification
        #----------------------------------------
        lret.value = ccnt.CntNotifySamplingStop(self.id, 0)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntNotifySamplingStop = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        lret.value = ccnt.CntNotifySamplingCount(self.id, self.number_of_data, 0)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntNotifySamplingCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Callback routine
        #----------------------------------------
        lret.value = ccnt.CntSamplingStopCallbackProc(self.id, self.psampling_stop_callback, self.user_data)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntSamplingStopCallbackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        lret.value = ccnt.CntSamplingCountCallbackProc(self.id, self.psampling_count_callback, self.user_data)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntSamplingCountCallbackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Reset FIFO (Input)
        #----------------------------------------
        lret.value = ccnt.CntSamplingFifoReset(self.id)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntSamplingFifoReset = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set data buffer
        #----------------------------------------
        ctypes.memset(self.sampling_data, 0, ctypes.sizeof(self.sampling_data))
        lret.value = ccnt.CntSamplingSetBuffer(self.id, self.sampling_data, self.CHANNEL_NUM, self.DATA_NUM, ccnt.CNTS_WRITE_RING)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntSamplingSetBuffer = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set parameter
        #----------------------------------------
        for ch_no.value in range(0, self.CHANNEL_NUM):
            ch_no_array[ch_no.value] = ch_no.value
        #----------------------------------------
        # Start count
        #----------------------------------------
        lret.value = ccnt.CntStartCount(self.id, ch_no_array, self.CHANNEL_NUM)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntStartCount = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Initialize count
        #----------------------------------------
        self.read_index.value = 0
        self.write_index.value = 0
        self.pre_count.value = 0
        self.pre_carry.value = 0
        #----------------------------------------
        # Delete data file
        #----------------------------------------
        if os.path.exists(self.file_name):
            os.remove(self.file_name)
        #----------------------------------------
        # Start transfer
        #----------------------------------------
        lret.value = ccnt.CntSamplingStart(self.id)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            ccnt.CntGetErrorString(lret, error_string)
            #----------------------------------------
            # Display the message
            #----------------------------------------
            text_buf = f"CntSamplingStart = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_return_string_var.set(text_buf)
            return
        self.ui.textbox_transfer_count_var.set("")
        self.ui.textbox_status_var.set("")
        self.ui.textbox_error_var.set("")

    #========================================
    # Function name    OnClickedButtonStop
    # Parameter        None
    # Details          Stop transfer
    # Return value     None
    #========================================
    def OnClickedButtonStop(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Stop transfer
        #----------------------------------------
        lret.value = ccnt.CntSamplingStop(self.id)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntSamplingStop = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonData
    # Parameter        None
    # Details          Display data file
    # Return value     None
    #========================================
    def OnClickedButtonData(self):
        #----------------------------------------
        # notepad
        #----------------------------------------
        if os.path.exists(self.file_name):
            subprocess.run(['notepad', self.file_name], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

    #========================================
    # Function name    OnClickedButtonCount
    # Parameter        None
    # Details          Transfer count
    # Return value     None
    #========================================
    def OnClickedButtonCount(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        count = ctypes.c_ulong()                           # Sampling count
        carry = ctypes.c_ulong()                           # Carry count

        #----------------------------------------
        # Get transfer count
        #----------------------------------------
        lret.value = ccnt.CntGetSamplingCount(self.id, ctypes.byref(count), ctypes.byref(carry))
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntGetSamplingCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value == ccnt.CNT_ERR_SUCCESS:
            self.ui.textbox_transfer_count_var.set(f"{count.value:d}")

    #========================================
    # Function name    OnClickedButtonStatus
    # Parameter        None
    # Details          Transfer status
    # Return value     None
    #========================================
    def OnClickedButtonStatus(self):
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code
        status = ctypes.c_ulong()                          # Status
        error = ctypes.c_ulong()                           # Error

        #----------------------------------------
        # Get transfer status
        #----------------------------------------
        lret.value = ccnt.CntGetSamplingStatus(self.id, ctypes.byref(status), ctypes.byref(error))
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntGetSamplingStatus = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_return_string_var.set(text_buf)
        if lret.value != ccnt.CNT_ERR_SUCCESS:
            return
        #--------------------
        # Status
        #--------------------
        buf = ""
        if status.value & ccnt.CNTS_STATUS_BMSTOP:
            buf += "BmStop,"
        if status.value & ccnt.CNTS_STATUS_CNTSTART:
            buf += "CntStart,"
        if status.value & ccnt.CNTS_STATUS_CNTSTOP:
            buf += "CntStop,"
        if status.value & ccnt.CNTS_STATUS_TRGIN:
            buf += "TrgIn,"
        if status.value & ccnt.CNTS_STATUS_OVERRUN:
            buf += "Overrun"
        self.ui.textbox_status_var.set(buf)
        #--------------------
        # Error
        #--------------------
        buf = ""
        if error.value & ccnt.CNTS_STATUS_FIFOFULL:
            buf += "FifoFull,"
        if error.value & ccnt.CNTS_STATUS_SGOVERIN:
            buf += "S/GOverIn,"
        if error.value & ccnt.CNTS_STATUS_TRGERR:
            buf += "TrgErr,"
        if error.value & ccnt.CNTS_STATUS_CLKERR:
            buf += "ClkErr,"
        if error.value & ccnt.CNTS_STATUS_SLAVEHALT:
            buf += "SlaveHalt,"
        if error.value & ccnt.CNTS_STATUS_MASTERHALT:
            buf += "MasterHalt"
        self.ui.textbox_error_var.set(buf)

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

        #----------------------------------------
        # Counter termination processing
        #----------------------------------------
        lret.value = ccnt.CntExit(self.id)
        ccnt.CntGetErrorString(lret, error_string)
        #----------------------------------------
        # Display the message
        #----------------------------------------
        text_buf = f"CntExit = {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
        #----------------------------------------
        ccnt.CntExit(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()

    #========================================
    # Function name  SamplingCountCallBackProc
    # Parameter      id        Id get by CntInit
    # Parameter      wParam    The parameter is passed by the driver
    # Parameter      lParam    The parameter is passed by the driver
    # Parameter      Param     The parameter which is passed in CntSetSamplingCountEvent is passed
    # Details        Function registered with the CntSamplingCountCallbackProc function
    #                This function is called when an event occurs
    # Return value   None
    #========================================
    @staticmethod
    def SamplingCountCallBackProc(id, wparam, lparam, param):
        lret = ctypes.c_long()           # For return code
        count = ctypes.c_ulong()         # Sampling count
        carry = ctypes.c_ulong()         # Carry count
        data_count = ctypes.c_ulong()    # Data count
        ch_no = ctypes.c_ulong()         # Channel No.

        #----------------------------------------
        # Create class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Retrieve transfer position on data buffer
        #----------------------------------------
        lret.value = ccnt.CntGetSamplingWritePointer(self.id, ctypes.byref(self.write_index), ctypes.byref(count), ctypes.byref(carry))
        #----------------------------------------
        # Check overflow error
        #----------------------------------------
        if carry.value == self.pre_carry.value:
            if (count.value > (self.pre_count.value + self.DATA_NUM)):
                text_buf = f"Overrun Error!(count = {count.value})"
                self.ui.textbox_error_var.set(text_buf)
                return
        #----------------------------------------
        # If count value is same as previous, exit current operation
        # (When it was called from the transfer completion message)
        #----------------------------------------
        if ((count.value == self.pre_count.value) and (carry.value == self.pre_carry.value)):
            return
        #----------------------------------------
        # Write transferred data to file
        #----------------------------------------
        #----------------------------------------
        # Open file
        #----------------------------------------
        try:
            the_file = open(self.file_name, 'a')
        except:
            self.ui.textbox_return_string_var.set('open : file open error.')
            return
        #----------------------------------------
        # Write data
        #----------------------------------------
        if self.write_index.value > self.read_index.value:
            cnt = count.value - (self.write_index.value - self.read_index.value)
            for data_count in range(self.read_index.value, self.write_index.value):
                buf = f'{cnt:d},'
                for ch_no in range(0, self.CHANNEL_NUM - 1):
                    index = data_count * self.CHANNEL_NUM + ch_no
                    buf = buf + f'{self.sampling_data[index]:08X},'
                index = data_count * self.CHANNEL_NUM + (ch_no + 1)
                buf = buf + f'{self.sampling_data[index]:08X}\n'
                the_file.write(buf) 
                cnt += 1
        else:
            cnt = count.value - (self.DATA_NUM - self.read_index.value + self.write_index.value)
            for data_count in range(self.read_index.value, self.DATA_NUM):
                buf = f'{cnt:d},'
                for ch_no in range(0, self.CHANNEL_NUM - 1):
                    index = data_count * self.CHANNEL_NUM + ch_no
                    buf = buf + f'{self.sampling_data[index]:08X},'
                index = data_count * self.CHANNEL_NUM + (ch_no + 1)
                buf = buf + f'{self.sampling_data[index]:08X}\n'
                the_file.write(buf) 
                cnt += 1
            for data_count in range(0, self.write_index.value):
                buf = f'{cnt:d},'
                for ch_no in range(0, self.CHANNEL_NUM - 1):
                    index = data_count * self.CHANNEL_NUM + ch_no
                    buf = buf + f'{self.sampling_data[index]:08X},'
                index = data_count * self.CHANNEL_NUM + (ch_no + 1)
                buf = buf + f'{self.sampling_data[index]:08X}\n'
                the_file.write(buf) 
                cnt += 1
        #----------------------------------------
        # Close file
        #----------------------------------------
        the_file.close()
        #----------------------------------------
        # Set read pointer
        #----------------------------------------
        self.read_index.value = self.write_index.value
        self.pre_count.value = count.value
        self.pre_carry.value = carry.value
        #----------------------------------------
        # Display transfer count value
        #----------------------------------------
        text_buf = f'{count.value:d}'
        self.ui.textbox_transfer_count_var.set(text_buf)

    #========================================
    # Function name  SamplingStopCallBackProc
    # Parameter      id        Id get by CntInit
    # Parameter      wParam    The parameter is passed by the driver
    # Parameter      lParam    The parameter is passed by the driver
    # Parameter      Param     The parameter which is passed in CntSetSamplingCountEvent is passed
    # Details        Function registered with the CntSamplingStopCallbackProc function
    #                This function is called when an event occurs
    # Return value   None
    #========================================
    @staticmethod
    def SamplingStopCallBackProc(id, wparam, lparam, param):
        #----------------------------------------
        # Create class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Transfer completion
        #----------------------------------------
        self.ui.textbox_status_var.set("Stopped!")
        self.SamplingCountCallBackProc(self.id, wparam, lparam, param)


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

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