package com.example;

import static com.example.mtnlib.nmc_lib20.*;
import static com.example.mtnlib.nmc_lib20_ext.*;
import static com.example.mtnlib.nmc_lib20_oem.*;
import static com.example.mtnlib.nmc_lib20_err.*;
import com.example.mtnlib.nmc_lib20_com.*;
import com.sun.jna.ptr.*;
import com.sun.jna.NativeLong;

public class Main {
    private static void checkError(short rtn, String operation) {
        if (rtn != 0) {
            System.err.printf("错误: %s (代码: %d)\n", operation, rtn);
            System.exit(1);
        }
    }
    public static void main(String[] args) {

        short rtn;// 指令返回值
        short axisNum = 0;// 轴号，从0开始
        HAND devHandle = new HAND();// 设备句柄
        PHAND pDevHandle = new PHAND();
        HAND axisHandle = new HAND();// 轴句柄
        PHAND pAxisHandle = new PHAND();

        short[] devCount = new short[1];
        TDevInfo[] devInfoList = new TDevInfo[10];
        rtn = NMC_DevSearch(TSearchMode.Ethernet, devCount, devInfoList);
        checkError(rtn,"搜索设备出错");
        rtn = NMC_DevOpen((short)0, pDevHandle);				//打开控制器（0表示设备序号为0）
        checkError(rtn,"打开控制器出错");
        devHandle = pDevHandle.getHandle();
        rtn = NMC_MtOpen(devHandle, axisNum, pAxisHandle); // 打开轴
        checkError(rtn,"打开轴出错");
        axisHandle = pAxisHandle.getHandle();
        rtn = NMC_MtSetSvOn(axisHandle);//打开轴使能(根据实际情况使用)
        checkError(rtn,"轴使能出错");

        //设置捕获参数,DI0为捕获源，下降沿触发
        rtn = NMC_MtSetCaptSns(axisHandle, CAPT_MODE_IO, CAPT_IO_SRC_DI0, (short) 0);
        checkError(rtn,"设置捕获参数出错");
        rtn = NMC_MtSetCapt(axisHandle);						//启动捕获
        checkError(rtn,"启动捕获出错");
        /**************  此处省略轴的运动过程  **********************/
        ShortByReference sts = new ShortByReference();
        NativeLongByReference pos = new NativeLongByReference();
        while (true)
        {
            rtn = NMC_MtGetSts(axisHandle, sts);
            checkError(rtn,"读当前轴状态出错");
            if ((sts.getValue() & BIT_AXIS_CAPTSET) == BIT_AXIS_CAPTSET)	//已经捕获到
            {
                rtn = NMC_MtGetCaptPos(axisHandle, pos);		//读取捕获位置
                checkError(rtn,"读取捕获位置出错");
                break;
            }
        }
    }
}
