﻿#================================================================
#================================================================
# API-DIO(WDM) (BusMaster)
# Sync Sampling Sample
# main file
#                                                 CONTEC Co.,Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import subprocess
import os
import ctypes
import MCondition
import SCondition
import cdio
from SyncUI import SyncUI


#========================================
# Sync class
#========================================
class Sync:
    #========================================
    # Initialization function
    #========================================
    def __init__(self):
        #----------------------------------------
        # Macro definition
        #----------------------------------------
        self.DATA_SIZE = 1000                                     # Buffer size for busmaster
        #----------------------------------------
        # Variable
        #----------------------------------------
        self.m_id = ctypes.c_short()                              # ID for master device access
        self.s_id = ctypes.c_short()                              # ID for slave device access
        self.m_data_buff = (ctypes.c_ulong * self.DATA_SIZE)()    # Pointer to master data buffer storage area
        self.s_data_buff = (ctypes.c_ulong * self.DATA_SIZE)()    # Pointer to slave data buffer storage area
        self.m_data_num = ctypes.c_ulong(500)                     # Number of master data
        self.s_data_num = ctypes.c_ulong(500)                     # Number of slave data
        self.m_is_ring = ctypes.c_short(cdio.DIODM_WRITE_ONCE)    # Master transfer condition
        self.s_is_ring = ctypes.c_short(cdio.DIODM_WRITE_ONCE)    # Slave transfer condition
        self.m_start_trg = cdio.DIODM_START_SOFT                  # Start condition for initialization of master condition setting screen
        self.m_cmp_ptn = 0x55                                     # Compare pattern for initialization of master condition setting screen
        self.m_ptn_mask = 0xFF                                    # Pattern mask for initialization of master condition setting screen
        self.m_clock_trg = cdio.DIODM_CLK_CLOCK                   # Clock condition for initialization of master condition setting screen
        self.m_internal_clock = 1000                              # Internal clock for initialization of master condition setting screen
        self.m_stop_trg = cdio.DIODM_STOP_SOFT                    # Stop condition for initialization of master condition setting screen
        self.m_stop_number = 1000                                 # Stop number for initialization of master condition setting screen
        self.s_start_trg = cdio.DIODM_START_EXTSIG_2              # Start condition for initialization of slave condition setting screen
        self.s_clock_trg = cdio.DIODM_CLK_EXTSIG_1                # Clock condition for initialization of slave condition setting screen
        self.s_stop_trg = cdio.DIODM_STOP_EXTSIG_3                # Stop condition for initialization of slave condition setting screen
        self.s_stop_number = 1000                                 # Stop number for initialization of slave condition setting screen
        self.pm_stop_callback = None                              # Point to callback function
        self.pm_count_callback = None                             # Point to callback function
        self.ps_stop_callback = None                              # Point to callback function
        self.ps_count_callback = None                             # Point to callback function
        self.user_data = None                                     # User data of callback function
        #----------------------------------------
        # Start creating the UI
        #----------------------------------------
        self.ui = SyncUI()
        #----------------------------------------
        # Set the callback function for the UI control
        #----------------------------------------
        self.ui.setup_commands(
            command_m_dio_init=self.OnClickedButtonMDioInit,
            command_m_condition=self.OnClickedButtonMCondition,
            command_m_start=self.OnClickedButtonMStart,
            command_m_stop=self.OnClickedButtonMStop,
            command_m_data=self.OnClickedButtonMData,
            command_m_count=self.OnClickedButtonMCount,
            command_m_status=self.OnClickedButtonMStatus,
            command_m_dio_exit=self.OnClickedButtonMDioExit,
            command_s_dio_init=self.OnClickedButtonSDioInit,
            command_s_condition=self.OnClickedButtonSCondition,
            command_s_start=self.OnClickedButtonSStart,
            command_s_stop=self.OnClickedButtonSStop,
            command_s_data=self.OnClickedButtonSData,
            command_s_count=self.OnClickedButtonSCount,
            command_s_status=self.OnClickedButtonSStatus,
            command_s_dio_exit=self.OnClickedButtonSDioExit,
            command_exit=self.OnClickedButtonExit
        )

    #========================================
    # Function name    MStopCallBackProc
    # 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 DioDmSetStopCallBackProc function
    # Details          Function registered with the DioDmSetStopCallBackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def MStopCallBackProc(id, wparam, lparam, param):
        lret = ctypes.c_long()      # For return code
        count = ctypes.c_ulong()    # Transfer count
        carry = ctypes.c_ulong()    # Carry count

        #----------------------------------------
        # Create the class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value

        #----------------------------------------
        # Master transfer stop
        #----------------------------------------
        self.ui.textbox_m_status_var.set("Stopped!")
        lret.value = cdio.DioDmGetCount(self.m_id, cdio.DIODM_DIR_IN, ctypes.byref(count), ctypes.byref(carry))
        text_buf = f"{count.value}"
        self.ui.textbox_m_trans_count_var.set(text_buf)

    #========================================
    # Function name    SStopCallBackProc
    # 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 DioDmSetStopCallBackProc function
    # Details          Function registered with the DioDmSetStopCallBackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def SStopCallBackProc(id, wparam, lparam, param):
        lret = ctypes.c_long()      # For return code
        count = ctypes.c_ulong()    # Transfer count
        carry = ctypes.c_ulong()    # Carry count

        #----------------------------------------
        # Create the class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value

        #----------------------------------------
        # Slave transfer stop
        #----------------------------------------
        self.ui.textbox_s_status_var.set("Stopped!")
        lret.value = cdio.DioDmGetCount(self.s_id, cdio.DIODM_DIR_IN, ctypes.byref(count), ctypes.byref(carry))
        text_buf = f"{count.value}"
        self.ui.textbox_s_trans_count_var.set(text_buf)

    #========================================
    # Function name    MCountCallBackProc
    # 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 DioDmSetCountCallBackProc function
    # Details          Function registered with the DioDmSetCountCallBackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def MCountCallBackProc(id, wparam, lparam, param):
        lret = ctypes.c_long()      # For return code
        count = ctypes.c_ulong()    # Transfer count
        carry = ctypes.c_ulong()    # Carry count

        #----------------------------------------
        # Create the class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Master transfer specified number of data completion message
        #----------------------------------------
        lret.value = cdio.DioDmGetCount(self.m_id, cdio.DIODM_DIR_IN, ctypes.byref(count), ctypes.byref(carry))
        text_buf = f"{count.value}"
        self.ui.textbox_m_trans_count_var.set(text_buf)

    #========================================
    # Function name    SCountCallBackProc
    # 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 DioDmSetCountCallBackProc function
    # Details          Function registered with the DioDmSetCountCallBackProc function
    #                  This function is called when an event occurs
    # Return value     None
    #========================================
    @staticmethod
    def SCountCallBackProc(id, wparam, lparam, param):
        lret = ctypes.c_long()      # For return code
        count = ctypes.c_ulong()    # Transfer count
        carry = ctypes.c_ulong()    # Carry count

        #----------------------------------------
        # Create the class object
        #----------------------------------------
        obj_ptr = ctypes.cast(param, ctypes.POINTER(ctypes.py_object))
        self = obj_ptr.contents.value
        #----------------------------------------
        # Slave transfer specified number of data completion message
        #----------------------------------------
        lret.value = cdio.DioDmGetCount(self.s_id, cdio.DIODM_DIR_IN, ctypes.byref(count), ctypes.byref(carry))
        text_buf = f"{count.value}"
        self.ui.textbox_s_trans_count_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonMDioInit
    # Parameter        None
    # Details          Master DioInit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonMDioInit(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_m_device_name_var.get()
        #----------------------------------------
        # Execute initialization function and get ID
        #----------------------------------------
        lret.value = cdio.DioInit(device_name.encode(), ctypes.byref(self.m_id))
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioInit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_m_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonMCondition
    # Parameter        None
    # Details          Master Set Conditions button click event function
    # Return value     None
    #========================================
    def OnClickedButtonMCondition(self):
        #----------------------------------------
        # Open the condition setting dialog
        #----------------------------------------
        MCondition.ConditionWindow(self)

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

        self.pm_stop_callback = cdio.PDIO_DM_STOP_CALLBACK(self.MStopCallBackProc)
        self.pm_count_callback = cdio.PDIO_DM_COUNT_CALLBACK(self.MCountCallBackProc)
        self.user_data = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p)
        #----------------------------------------
        # Set transfer stop event
        #----------------------------------------
        lret.value = cdio.DioDmSetStopEvent(self.m_id, cdio.DIODM_DIR_IN, 0)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetStopEvent = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_m_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set callback routine
        #----------------------------------------
        lret.value = cdio.DioDmSetStopCallBackProc(self.m_id, self.pm_stop_callback, self.user_data)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetStopCallBackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_m_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set specified number transfer completion event
        #----------------------------------------
        lret.value = cdio.DioDmSetCountEvent(self.m_id, cdio.DIODM_DIR_IN, self.m_data_num, 0)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetCountEvent = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_m_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set callback routine
        #----------------------------------------
        lret.value = cdio.DioDmSetCountCallBackProc(self.m_id, self.pm_count_callback, self.user_data)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetCountCallBackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_m_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Reset FIFO (input)
        #----------------------------------------
        lret.value = cdio.DioDmFifoReset(self.m_id, cdio.DIODM_RESET_FIFO_IN)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmFifoReset = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_m_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set data buffer
        #----------------------------------------
        for i in range(self.DATA_SIZE):
            self.m_data_buff[i] = 0
        lret.value = cdio.DioDmSetBuffer(self.m_id, cdio.DIODM_DIR_IN, self.m_data_buff, self.DATA_SIZE, self.m_is_ring)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetBuffer = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_m_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Start transfer
        #----------------------------------------
        lret.value = cdio.DioDmTransferStart(self.m_id, cdio.DIODM_DIR_IN)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmTransferStart = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_m_return_string_var.set(text_buf)
            return
        self.ui.textbox_m_trans_count_var.set("")
        self.ui.textbox_m_status_var.set("")
        self.ui.textbox_m_error_var.set("")

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

        #----------------------------------------
        # Stop transfer
        #----------------------------------------
        lret.value = cdio.DioDmTransferStop(self.m_id, cdio.DIODM_DIR_IN)
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioDmTransferStop = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_m_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonMData
    # Parameter        None
    # Details          Master Get Data button click event function
    # Return value     None
    #========================================
    def OnClickedButtonMData(self):
        file_name = 'MSamplingData.csv'    # Data file name

        #----------------------------------------
        # Open file
        #----------------------------------------
        try:
            file = open(file_name, 'w')
        except:
            text_buf = "open : file open error."
            self.ui.textbox_m_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Write data into file
        #----------------------------------------
        for i in range(self.DATA_SIZE):
            buf = f"{i:d},{self.m_data_buff[i]:08X}\n"
            file.write(buf)
        #----------------------------------------
        # Close file
        #----------------------------------------
        file.close()
        #----------------------------------------
        # notepad
        #----------------------------------------
        if os.path.exists(file_name):
            subprocess.run(['notepad', file_name], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

    #========================================
    # Function name    OnClickedButtonMCount
    # Parameter        None
    # Details          Master Transfer Count button click event function
    # Return value     None
    #========================================
    def OnClickedButtonMCount(self):
        count = ctypes.c_ulong()                           # Count number
        carry = ctypes.c_ulong()                           # Carry count
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get transfer count
        #----------------------------------------
        lret.value = cdio.DioDmGetCount(self.m_id, cdio.DIODM_DIR_IN, ctypes.byref(count), ctypes.byref(carry))
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioDmGetCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_m_return_string_var.set(text_buf)
        if lret.value == cdio.DIO_ERR_SUCCESS:
            text_buf = f"{count.value}"
            self.ui.textbox_m_trans_count_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonMStatus
    # Parameter        None
    # Details          Master Transfer Status button click event function
    # Return value     None
    #========================================
    def OnClickedButtonMStatus(self):
        status = ctypes.c_ulong()                          # Status
        err = ctypes.c_ulong()                             # Error
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get transfer status
        #----------------------------------------
        lret.value = cdio.DioDmGetStatus(self.m_id, cdio.DIODM_DIR_IN, ctypes.byref(status), ctypes.byref(err))
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioDmGetStatus = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_m_return_string_var.set(text_buf)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # Status
        #----------------------------------------
        text_buf = ''
        if status.value & cdio.DIODM_STATUS_BMSTOP:    text_buf += 'BmStop,'
        if status.value & cdio.DIODM_STATUS_PIOSTART:  text_buf += 'PioStart,'
        if status.value & cdio.DIODM_STATUS_PIOSTOP:   text_buf += 'PioStop,'
        if status.value & cdio.DIODM_STATUS_TRGIN:     text_buf += 'TrgIn,'
        if status.value & cdio.DIODM_STATUS_OVERRUN:   text_buf += 'Overrun'
        self.ui.textbox_m_status_var.set(text_buf)
        #----------------------------------------
        # Error
        #----------------------------------------
        text_buf = ''
        if err.value & cdio.DIODM_STATUS_FIFOEMPTY:    text_buf += 'FifoEmpty,'
        if err.value & cdio.DIODM_STATUS_FIFOFULL:     text_buf += 'FifoFull,'
        if err.value & cdio.DIODM_STATUS_SGOVERIN:     text_buf += 'S/GOverIn,'
        if err.value & cdio.DIODM_STATUS_TRGERR:       text_buf += 'TrgErr,'
        if err.value & cdio.DIODM_STATUS_CLKERR:       text_buf += 'ClkErr,'
        if err.value & cdio.DIODM_STATUS_SLAVEHALT:    text_buf += 'SlaveHalt,'
        if err.value & cdio.DIODM_STATUS_MASTERHALT:   text_buf += 'MasterHalt'
        self.ui.textbox_m_error_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonMDioExit
    # Parameter        None
    # Details          Master DioExit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonMDioExit(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.m_id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioExit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_m_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonSDioInit
    # Parameter        None
    # Details          Slave DioInit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonSDioInit(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_s_device_name_var.get()
        #----------------------------------------
        # Execute initialization function and get ID
        #----------------------------------------
        lret.value = cdio.DioInit(device_name.encode(), ctypes.byref(self.s_id))
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioInit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_s_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonSCondition
    # Parameter        None
    # Details          Slave Set Conditions button click event function
    # Return value     None
    #========================================
    def OnClickedButtonSCondition(self):
        #----------------------------------------
        # Open the condition setting dialog
        #----------------------------------------
        SCondition.ConditionWindow(self)

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

        self.ps_stop_callback = cdio.PDIO_DM_STOP_CALLBACK(self.SStopCallBackProc)
        self.ps_count_callback = cdio.PDIO_DM_COUNT_CALLBACK(self.SCountCallBackProc)
        self.user_data = ctypes.cast(ctypes.pointer(ctypes.py_object(self)), ctypes.c_void_p)
        #----------------------------------------
        # Set transfer stop event
        #----------------------------------------
        lret.value = cdio.DioDmSetStopEvent(self.s_id, cdio.DIODM_DIR_IN, 0)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetStopEvent = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_s_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set callback routine
        #----------------------------------------
        lret.value = cdio.DioDmSetStopCallBackProc(self.s_id, self.ps_stop_callback, self.user_data)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetStopCallBackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_s_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set specified number transfer completion event
        #----------------------------------------
        lret.value = cdio.DioDmSetCountEvent(self.s_id, cdio.DIODM_DIR_IN, self.s_data_num, 0)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetCountEvent = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_s_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set callback routine
        #----------------------------------------
        lret.value = cdio.DioDmSetCountCallBackProc(self.s_id, self.ps_count_callback, self.user_data)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetCountCallBackProc = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_s_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Reset FIFO (input)
        #----------------------------------------
        lret.value = cdio.DioDmFifoReset(self.s_id, cdio.DIODM_RESET_FIFO_IN)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmFifoReset = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_s_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Set data buffer
        #----------------------------------------
        for i in range(self.DATA_SIZE):
            self.s_data_buff[i] = 0
        lret.value = cdio.DioDmSetBuffer(self.s_id, cdio.DIODM_DIR_IN, self.s_data_buff, self.DATA_SIZE, self.s_is_ring)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmSetBuffer = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_s_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Start transfer
        #----------------------------------------
        lret.value = cdio.DioDmTransferStart(self.s_id, cdio.DIODM_DIR_IN)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            cdio.DioGetErrorString(lret, error_string)
            text_buf = f"DioDmTransferStart = {lret.value} : {error_string.value.decode('sjis')}"
            self.ui.textbox_s_return_string_var.set(text_buf)
            return
        self.ui.textbox_s_trans_count_var.set("")
        self.ui.textbox_s_status_var.set("")
        self.ui.textbox_s_error_var.set("")

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

        #----------------------------------------
        # Stop transfer
        #----------------------------------------
        lret.value = cdio.DioDmTransferStop(self.s_id, cdio.DIODM_DIR_IN)
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioDmTransferStop = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_s_return_string_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonSData
    # Parameter        None
    # Details          Slave Get Data button click event function
    # Return value     None
    #========================================
    def OnClickedButtonSData(self):
        file_name = 'SSamplingData.csv'    # Data file name

        #----------------------------------------
        # Open file
        #----------------------------------------
        try:
            file = open(file_name, 'w')
        except:
            text_buf = "open : file open error."
            self.ui.textbox_s_return_string_var.set(text_buf)
            return
        #----------------------------------------
        # Write data into file
        #----------------------------------------
        for i in range(self.DATA_SIZE):
            buf = f"{i:d},{self.s_data_buff[i]:08X}\n"
            file.write(buf)
        #----------------------------------------
        # Close file
        #----------------------------------------
        file.close()
        #----------------------------------------
        # notepad
        #----------------------------------------
        if os.path.exists(file_name):
            subprocess.run(['notepad', file_name], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

    #========================================
    # Function name    OnClickedButtonSCount
    # Parameter        None
    # Details          Slave Transfer Count button click event function
    # Return value     None
    #========================================
    def OnClickedButtonSCount(self):
        count = ctypes.c_ulong()                           # Count number
        carry = ctypes.c_ulong()                           # Carry count
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get transfer count
        #----------------------------------------
        lret.value = cdio.DioDmGetCount(self.s_id, cdio.DIODM_DIR_IN, ctypes.byref(count), ctypes.byref(carry))
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioDmGetCount = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_s_return_string_var.set(text_buf)
        if lret.value == cdio.DIO_ERR_SUCCESS:
            text_buf = f"{count.value}"
            self.ui.textbox_s_trans_count_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonSStatus
    # Parameter        None
    # Details          Slave Transfer Status button click event function
    # Return value     None
    #========================================
    def OnClickedButtonSStatus(self):
        status = ctypes.c_ulong()                          # Status
        err = ctypes.c_ulong()                             # Error
        error_string = ctypes.create_string_buffer(256)    # Error code string
        lret = ctypes.c_long()                             # For return code

        #----------------------------------------
        # Get transfer status
        #----------------------------------------
        lret.value = cdio.DioDmGetStatus(self.s_id, cdio.DIODM_DIR_IN, ctypes.byref(status), ctypes.byref(err))
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioDmGetStatus = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_s_return_string_var.set(text_buf)
        if lret.value != cdio.DIO_ERR_SUCCESS:
            return
        #----------------------------------------
        # Status
        #----------------------------------------
        text_buf = ''
        if status.value & cdio.DIODM_STATUS_BMSTOP:    text_buf += 'BmStop,'
        if status.value & cdio.DIODM_STATUS_PIOSTART:  text_buf += 'PioStart,'
        if status.value & cdio.DIODM_STATUS_PIOSTOP:   text_buf += 'PioStop,'
        if status.value & cdio.DIODM_STATUS_TRGIN:     text_buf += 'TrgIn,'
        if status.value & cdio.DIODM_STATUS_OVERRUN:   text_buf += 'Overrun'
        self.ui.textbox_s_status_var.set(text_buf)
        #----------------------------------------
        # Error
        #----------------------------------------
        text_buf = ''
        if err.value & cdio.DIODM_STATUS_FIFOEMPTY:    text_buf += 'FifoEmpty,'
        if err.value & cdio.DIODM_STATUS_FIFOFULL:     text_buf += 'FifoFull,'
        if err.value & cdio.DIODM_STATUS_SGOVERIN:     text_buf += 'S/GOverIn,'
        if err.value & cdio.DIODM_STATUS_TRGERR:       text_buf += 'TrgErr,'
        if err.value & cdio.DIODM_STATUS_CLKERR:       text_buf += 'ClkErr,'
        if err.value & cdio.DIODM_STATUS_SLAVEHALT:    text_buf += 'SlaveHalt,'
        if err.value & cdio.DIODM_STATUS_MASTERHALT:   text_buf += 'MasterHalt'
        self.ui.textbox_s_error_var.set(text_buf)

    #========================================
    # Function name    OnClickedButtonSDioExit
    # Parameter        None
    # Details          Slave DioExit button click event function
    # Return value     None
    #========================================
    def OnClickedButtonSDioExit(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.s_id)
        #----------------------------------------
        # Error process
        #----------------------------------------
        cdio.DioGetErrorString(lret, error_string)
        text_buf = f"DioExit = {lret.value} : {error_string.value.decode('sjis')}"
        self.ui.textbox_s_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.m_id)
        cdio.DioExit(self.s_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 Sync
    #----------------------------------------
    instance = Sync()
    instance.run()

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