
from pymtn_lib20 import *

def DevInit():
    print("控制器初始化开始")
    ''' 搜索控制器'''
    (devNum, devinfolist, ret) = pymtn.NMC_DevSearch(pymtn.TSearchMode.Internet)
    if ret != 0:
        print("控制器搜索出错,返回值为:", ret)
        exit()
    if ret == 0:
        print("the count of devices: (%s)" % (devNum))
        for i in range(0, devNum):
            print(devinfolist[i].address)
            print(devinfolist[i].idStr)
            print(devinfolist[i].description)
            print(devinfolist[i].ID)
    if devNum <= 0:
        print("没有找到控制器")
        exit()

    ''' 打开第一个控制器'''
    (devHandle, ret) = pymtn.NMC_DevOpenByID(devinfolist[0].idStr)
    if ret != pymtn.RTN_CMD_SUCCESS:
        print("控制器打开出错", ret)
        exit()

    # ''' 打开第一个控制器--只有一张卡的时候，直接打开，不用搜索'''
    # (devHandle, ret) = pymtn.NMC_DevOpen(0)
    # if ret != pymtn.RTN_CMD_SUCCESS:
    #     print("控制器打开出错", ret)
    #     exit()

    (Info, ret) = pymtn.NMC_GetCardInfo(devHandle)
    num = Info.axisNum
    axisHandle = [c_ushort(0)] * num
    for i in range(0, num):
        (axisHandle[i], ret) = pymtn.NMC_MtOpen(devHandle, i)
        if ret != pymtn.RTN_CMD_SUCCESS:
            print("控制器打开出错", ret)
            exit()

    print("控制器初始化结束")
    return (devHandle, axisHandle)

"""--------------------手轮--------------------"""
def Ext_HandWheelCom(devHandle, axisHandle):
    print("手轮 测试开始")

    # 先关闭所有手脉
    ret = pymtn.NMC_ClrHandWheel(devHandle)
    if ret != 0:
        print(f"退出手轮失败，错误码: {ret}")
    else:
        print("退出手轮成功")

    # 选择手轮跟随的编码器通道
    ret = pymtn.NMC_SetHandWheelInput(devHandle, 0)
    if ret != 0:
        print(f"设置手轮编码器通道失败，错误码: {ret}")
    else:
        print("设置手轮编码器通道成功")

    # 设置手轮跟随倍率
    ret = pymtn.NMC_SetHandWheelRatio(devHandle, 2.0)
    if ret != 0:
        print(f"设置手轮倍率失败，错误码: {ret}")
    else:
        print("设置手轮倍率成功")

    # 启动手轮功能
    axis = 0  # 轴号0
    ratio = 1.0  # 跟随倍率
    acc = 1000.0  # 加速度
    vel = 500.0  # 速度

    ret = pymtn.NMC_SetHandWheel(devHandle, axis, ratio, acc, vel)
    if ret != 0:
        print(f"启动手轮失败，错误码: {ret}")
    else:
        print("启动手轮成功")

    # 退出手轮功能
    ret = pymtn.NMC_ClrHandWheel(devHandle)
    if ret != 0:
        print(f"退出手轮失败，错误码: {ret}")
    else:
        print("退出手轮成功")

    print("手轮 测试结束")
if __name__ == "__main__":

    devHandle, axisHandle = DevInit()
    Ext_HandWheelCom(devHandle, axisHandle[0])