#================================================================
#================================================================
# API-SMC(WDM)
# bankarc SAMPLE
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================

import ctypes
import ctypes.wintypes
import sys
import math
import csmc

#================================================================
# Macro definition
#================================================================
CSMC_CW = 0
CSMC_CCW = 1
CSMC_SINGLE = 4
CSMC_LOOP = 5


#================================================================
# External variables
#================================================================
smc_id          = ctypes.c_short(0)
axis_no         = ctypes.c_short(0)
bank_num        = ctypes.c_short(0)
motion_type     = ctypes.c_short(0)
arc_speed       = ctypes.c_double(0)
arc_start_dir   = ctypes.c_short(0)


#================================================================
# Function that checks if a string can be converted to a float
#================================================================
def isfloat(str):
    try:
            float(str)
    except:
        return False
    return True


#================================================================
# Parameter setting
#================================================================
def set_bank_param():
    global smc_id, axis_no, bank_num, arc_speed, arc_start_dir
    err_str = ctypes.create_string_buffer(256)

    #----------------------------------------
    # Set the number of banks
    #----------------------------------------
    lret = csmc.SmcWSetBankNumber(smc_id, axis_no, bank_num)
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWSetBankNumber = {lret}: {err_str.value.decode('sjis')}")
        return -1
    #----------------------------------------
    # Set the axis for the interpolation
    #----------------------------------------
    cal1 = int(math.pow(2, (axis_no.value - 1)))
    cal2 = int(math.pow(2, axis_no.value))
    inter_axis = cal1 | cal2
    #----------------------------------------
    # Set the interpolation type
    #----------------------------------------
    inter_type = 3
    #----------------------------------------
    # Set mode the terminal is automatically drawn in
    # when the circular arc interpolation operation ends
    #----------------------------------------
    auto_end_point_pull = 1
    reserved = 0
    for bank_no in range(1, bank_num.value+1):
        lret = csmc.SmcWSetBankInterpolation(smc_id, axis_no, bank_no, inter_type, inter_axis, reserved)
        if lret != 0:
            csmc.SmcWGetErrorString(lret, err_str)
            print(f"SmcWSetBankInterpolation = {lret}: {err_str.value.decode('sjis')}")
            return -1
        lret = csmc.SmcWSetBankArcParam(smc_id, axis_no, bank_no, arc_start_dir, auto_end_point_pull)
        if lret != 0:
            csmc.SmcWGetErrorString(lret, err_str)
            print(f"SmcWSetBankArcParam = {lret}: {err_str.value.decode('sjis')}")
            return -1
    #----------------------------------------
    # Set the speed and the coordinates position of a circular arc interpolation
    #----------------------------------------
    coordinates = 5000
    center_x = coordinates
    center_y = 0
    if arc_start_dir.value == CSMC_CW:
        end_x = coordinates
        end_y = coordinates
    else:
        end_x = coordinates
        end_y = (-1) * coordinates
    lret = csmc.SmcWSetBankArcPoint(smc_id, axis_no, 1, arc_speed, center_x, center_y, end_x, end_y)
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWSetBankArcPoint = {lret}: {err_str.value.decode('sjis')}")
        return -1
    if arc_start_dir.value == CSMC_CW:
        center_x = 0
        center_y = (-1) * coordinates
        end_x = coordinates
        end_y = (-1) * coordinates
    else:
        center_x = 0
        center_y = coordinates
        end_x = coordinates
        end_y = coordinates
    lret = csmc.SmcWSetBankArcPoint(smc_id, axis_no, 2, arc_speed, center_x, center_y, end_x, end_y)
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWSetBankArcPoint = {lret}: {err_str.value.decode('sjis')}")
        return -1
    center_x = (-1) * coordinates
    center_y = 0
    if arc_start_dir.value == CSMC_CW:
        end_x = (-1) * coordinates
        end_y = (-1) * coordinates
    else:
        end_x = (-1) * coordinates
        end_y = coordinates
    lret = csmc.SmcWSetBankArcPoint(smc_id, axis_no, 3, arc_speed, center_x, center_y, end_x, end_y)
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWSetBankArcPoint = {lret}: {err_str.value.decode('sjis')}")
        return -1
    if arc_start_dir.value == CSMC_CW:
        center_x = 0
        center_y = coordinates
        end_x = (-1) * coordinates
        end_y = coordinates
    else:
        center_x = 0
        center_y = (-1) * coordinates
        end_x = (-1) * coordinates
        end_y = (-1) * coordinates
    lret = csmc.SmcWSetBankArcPoint(smc_id, axis_no, 4, arc_speed, center_x, center_y, end_x, end_y)
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWSetBankArcPoint = {lret}: {err_str.value.decode('sjis')}")
        return -1
    return 0


#================================================================
# Motion type setting
#================================================================
def set_motion_type():
    global motion_type

    #----------------------------------------
    # Setting change
    #----------------------------------------
    while True:
        print('')
        print('[Motion type setting menu]---------------')
        print('  1:Single')
        print('  2:Loop')
        print('  q:Back')
        print('-----------------------------------------')
        menu = input('Please enter a number :')
        #----------------------------------------
        # Single
        #----------------------------------------
        if menu == '1':
            motion_type.value = CSMC_SINGLE
            break
        #----------------------------------------
        # Loop
        #----------------------------------------
        if menu == '2':
            motion_type.value = CSMC_LOOP
            break
        #----------------------------------------
        # End
        #----------------------------------------
        if menu == 'q':
            return -1
    return 0


#================================================================
# Operation start
#================================================================
def start_motion():
    global smc_id, axis_no, motion_type
    err_str = ctypes.create_string_buffer(256)

    ret = set_motion_type()
    if ret != 0:
        return -1
    #----------------------------------------
    # Set parameters in the driver
    #----------------------------------------
    ret = set_bank_param()
    if ret != 0:
        return -1
    #----------------------------------------
    # Preparing to start operation
    #----------------------------------------
    lret = csmc.SmcWSetBankReady(smc_id, axis_no, motion_type)
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWSetBankReady = {lret}: {err_str.value.decode('sjis')}")
        return -1
    #----------------------------------------
    # Start motor operation
    #----------------------------------------
    lret = csmc.SmcWMotionStart(smc_id, axis_no)
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWMotionStart = {lret}: {err_str.value.decode('sjis')}")
        return -1
    return 0


#================================================================
# Stop
#================================================================
def stop_motion():
    global smc_id, axis_no
    err_str = ctypes.create_string_buffer(256)

    lret = csmc.SmcWMotionStop(smc_id, axis_no)
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWMotionStop = {lret}: {err_str.value.decode('sjis')}")
        return -1
    return 0


#================================================================
# Main function
#================================================================
def main():
    err_str = ctypes.create_string_buffer(256)
    global smc_id, axis_no, bank_num, motion_type, arc_speed, arc_start_dir

    axis_no.value = 1
    bank_num.value = 4
    motion_type.value = CSMC_SINGLE
    arc_speed.value = 10000
    #----------------------------------------
    # Display title
    #----------------------------------------
    print('----------------------------------')
    print('<<< bankarc SAMPLE >>>')
    print('----------------------------------')
    #----------------------------------------
    # Confirm input of device name
    #----------------------------------------
    dev_name = input('Enter the device name of the board to be used. \nDevice name: ')
    #----------------------------------------
    # Device init
    #----------------------------------------
    lret = csmc.SmcWInit(dev_name.encode(), ctypes.byref(smc_id))
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWInit = {lret}: {err_str.value.decode('sjis')}")
        sys.exit()
    #----------------------------------------
    # Input waiting loop
    #----------------------------------------
    while True:
        print('')
        print('[Circular interpolation operation menu]------')
        print('  1:Change axis')
        print('  2:Change the number of banks')
        print('  3:Display circular interpolation speed')
        print('  4:Change circular interpolation speed')
        print('  5:CW')
        print('  6:CCW')
        print('  7:Stop')
        print('  q:Exit')
        print('-----------------------------------------')
        menu = input('Please enter a number :')
        #----------------------------------------
        # Change axis
        #----------------------------------------
        if menu == '1':
            while True:
                menu = input('Enter the axis number. (Next axis and interpolation target axis):')
                #----------------------------------------
                # Check whether the input data is a number 
                #----------------------------------------
                if menu.isdigit() != True:
                    continue
                axis_no.value = int(menu)
                if axis_no.value >= 1:
                    break
            continue
        #----------------------------------------
        # Change the number of banks
        #----------------------------------------
        if menu == '2':
            while True:
                menu = input('Enter the number of banks from 1 to 4 :')
                #----------------------------------------
                # Check whether the input data is a number
                #----------------------------------------
                if menu.isdigit() != True:
                    continue
                bank_num.value = int(menu)
                if bank_num.value >= 1 and bank_num.value <= 4:
                    break
            continue
        #----------------------------------------
        # Display circular interpolation speed
        #----------------------------------------
        if menu == '3':
            print(f"[Circular interpolation speed] : {arc_speed.value:.1f}[PPS]")
        #----------------------------------------
        # Change circular interpolation speed
        #----------------------------------------
        if menu == '4':
            while True:
                menu = input('Enter the circular interpolation speed [PPS]:')
                #----------------------------------------
                # Check whether the input data is a float
                #----------------------------------------
                if isfloat(menu) == False:
                    continue
                arc_speed.value = float(menu)
                break
            continue
        #----------------------------------------
        # CW
        #----------------------------------------
        if menu == '5':
            arc_start_dir.value = CSMC_CW
            start_motion()
        #----------------------------------------
        # CCW
        #----------------------------------------
        if menu == '6':
            arc_start_dir.value = CSMC_CCW
            start_motion()
        #----------------------------------------
        # Stop
        #----------------------------------------
        if menu == '7':
            stop_motion()
        #----------------------------------------
        # Exit
        #----------------------------------------
        if menu == 'q':
            break
    #----------------------------------------
    # Device exit
    #----------------------------------------
    lret = csmc.SmcWExit(smc_id)
    if lret != 0:
        csmc.SmcWGetErrorString(lret, err_str)
        print(f"SmcWExit = {lret}: {err_str.value.decode('sjis')}")
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


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