import static lib.mtn_lib20.*;
import static lib.mtn_lib20_com.*;
import static lib.mtn_lib20_ext.*;
import static lib.mtn_lib20_oem.*;
import static lib.mtn_lib20_err.*;
import com.sun.jna.*;
import com.sun.jna.ptr.*;

public class Main {
    static {
        String libPath = System.getProperty("user.dir") + "\\lib";
        System.setProperty("java.library.path", libPath);
        System.load(libPath + "\\msvcr100.dll");
        System.load(libPath + "\\msvcp100.dll");
        System.load(libPath + "\\nmc_lib20.dll");
    }
    // 错误处理工具类
    private static class ErrorHandler {
        public static void checkError(short rtn) {
            if (rtn != 0) {
                throw new RuntimeException(String.format("操作失败，错误代码: %d", rtn));
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("龙门功能测试开始...");

        try {
            short devNum = 0;                       // 设备序号，从0开始
            short axisNum = 0;                      // 轴号从0开始
            PHAND pDevHandle = new PHAND();         // 设备句柄
            HAND[] axisHandles = new HAND[2];       // 轴句柄
            
            //打开控制器
            short rtn = NMC_DevOpen(devNum, pDevHandle);
            ErrorHandler.checkError(rtn);
            System.out.println("打开设备 - 成功");

            //打开轴,并获得轴句柄
            HAND devHandle = pDevHandle.getHandle();
            for (short i = 0; i < 2; i++) {
                PHAND pAxisHandle = new PHAND();
                rtn = NMC_MtOpen(devHandle, (short)(axisNum + i), pAxisHandle);
                ErrorHandler.checkError(rtn);
                System.out.printf("打开轴%d - 成功\n", axisNum + i);
                axisHandles[i] = pAxisHandle.getHandle();

                //打开轴使能
                rtn = NMC_MtSetSvOn(axisHandles[i]);
                ErrorHandler.checkError(rtn);
                System.out.printf("轴%d伺服使能 - 成功\n", axisNum + i);
            }

            //设置龙门主轴,组号为0
            rtn = NMC_SetGantryMaster(axisHandles[0], (short)0);
            ErrorHandler.checkError(rtn);
            System.out.println("设置轴0为龙门主轴 - 成功");
            
            //设置龙门组的从轴，允许误差为2000脉冲
            NativeLong deviationThreshold = new NativeLong(2000);
            rtn = NMC_SetGantrySlave(axisHandles[1], (short)0, deviationThreshold);
            ErrorHandler.checkError(rtn);
            System.out.println("设置轴1为龙门从轴 - 成功");

            // 这里可以添加运动控制代码
            // 例如让主轴运动，从轴会跟随
            
        } catch (Exception e) {
            System.err.println("测试过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            System.out.println("\n释放资源...");
            // 实际应用中需要添加关闭轴和设备的代码
            // NMC_MtClose(axisHandles[0]);
            // NMC_MtClose(axisHandles[1]);
            // NMC_DevClose(pDevHandle.getHandle());
        }
        
        System.out.println("龙门功能测试完成");
    }
}