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表示设备序号）
        checkError(rtn,"打开控制器出错");
        devHandle = pDevHandle.getHandle();
        rtn = NMC_MtOpen(devHandle, axisNum, pAxisHandle); // 打开轴
        checkError(rtn,"打开轴出错");
        axisHandle = pAxisHandle.getHandle();
        rtn = NMC_MtSetSvOn(axisHandle);//打开轴使能(根据实际情况使用)
        checkError(rtn,"轴使能出错");

        rtn = NMC_MtSetPosErrLmt(axisHandle, new NativeLong(30000));	// 设置轴位置的允许误差
        checkError(rtn,"设置轴位置的允许误差出错");
        rtn = NMC_MtLmtSns(axisHandle, (short) 0, (short) 0);	// 限位开关触发电平设置为低电平
        checkError(rtn,"限位开关触发电平设置出错");
        rtn = NMC_MtLmtOnOff(axisHandle, (short) 1, (short) 1);	// 启动限位开关检查
        checkError(rtn,"启动限位开关检查出错");
        rtn = NMC_MtAlarmSns(axisHandle, (short) 1);	// 设置伺服报警开关电平为高电平
        checkError(rtn,"设置伺服报警开关电平出错");
        rtn = NMC_MtAlarmOnOff(axisHandle, (short) 0);	// 伺服报警检查开启
        checkError(rtn,"伺服报警检查开启出错");
        rtn = NMC_MtSwLmtValue(axisHandle, new NativeLong(30000), new NativeLong(-30000));	// 设置软件限位数值
        checkError(rtn,"设置软件限位数值出错");
        rtn = NMC_MtSwLmtOnOff(axisHandle, (short) 1);	// 软件限位检查开启
        checkError(rtn,"软件限位检查开启出错");
        TSafePara safePrm = new TSafePara();
        safePrm.maxAcc = 50;
        safePrm.maxVel = 100;
        safePrm.estpDec = 50;
        rtn = NMC_MtSetSafePara(axisHandle, safePrm);// 设置轴安全参数
        checkError(rtn,"设置轴安全参数出错");
        rtn = NMC_MtSetStepMode(axisHandle, (short) 0, (short) 0);// 设置脉冲输出模式为脉冲+方向
        checkError(rtn,"设置脉冲输出模式为脉冲+方向出错");
    }
}
