"""--------------------控制器初始化--------------------"""
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)

"""--------------------PT--------------------"""
def Ext_PTCom(devHandle, axisHandle):
    print("PT 测试开始")

    ret = pymtn.NMC_MtSetPrfMode(axisHandle, pymtn.MT_PT_PRF_MODE); # 设置轴为PT运动模式
    if ret != 0:
        print(f"设置PT运动模式失败，错误码: {ret}")
    else:
        print("设置PT运动模式成功")

    # 设置PT运动数据驻存模式
    onOff = 1  # 1：数据驻存模式
    loopCount = 5  # 循环5次
    ret = pymtn.NMC_MtPtSetStatic(axisHandle, onOff, loopCount)
    if ret != 0:
        print(f"设置PT数据驻存模式失败，错误码: {ret}")
    else:
        print("设置PT数据驻存模式成功")

    # 清空PT数据
    ret = pymtn.NMC_MtPtBufClr(axisHandle)
    if ret != 0:
        print(f"清空PT数据失败，错误码: {ret}")
    else:
        print("清空PT数据成功")

    # 查询PT数据剩余空间大小
    Space, Used, ret = pymtn.NMC_MtPtGetSpace(axisHandle)
    if ret != 0:
        print(f"查询PT数据空间失败，错误码: {ret}")
    else:
        print(f"PT数据剩余空间: {Space.value} 段")
        print(f"PT数据已使用: {Used.value} 段")


    # 向PT运动缓存区压入运动数据段
    count = 4
    PosArray = [100.0, 200.0, 150.0, 300]  # 段运行距离
    TimeArray = [1000, 2000, 3000, 4000]  # 段运行时间
    TypeArray = [pymtn.MT_PT_NORMAL, pymtn.MT_PT_NORMAL, pymtn.MT_PT_STOP]  # 段类型

    ret = pymtn.NMC_MtPtPush(axisHandle, count, PosArray, TimeArray, TypeArray)
    if ret != 0:
        print(f"压入PT运动数据失败，错误码: {ret}")
    else:
        print("压入PT运动数据成功")

    # 启动PT运动
    otherSynAxCnts = 0  # 无其他同步启动轴
    OtherSynAxArray = []  # 空数组

    ret = pymtn.NMC_MtPtStartMtn(axisHandle, otherSynAxCnts, OtherSynAxArray)
    if ret != 0:
        print(f"启动PT运动失败，错误码: {ret}")
    else:
        print("启动PT运动成功")
    print("PT 测试结束")

if __name__ == "__main__":

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