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 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();         // 设备句柄
            PHAND pAxisHandle = new PHAND();        // 轴句柄
            
            // 打开控制器
            short rtn = NMC_DevOpen(devNum, pDevHandle);
            ErrorHandler.checkError(rtn);
            System.out.println("打开设备 - 成功");

            //打开轴,并获得轴句柄
            HAND devHandle = pDevHandle.getHandle();
            rtn = NMC_MtOpen(devHandle, axisNum, pAxisHandle);
            ErrorHandler.checkError(rtn);
            System.out.printf("打开轴%d - 成功\n", axisNum);
            HAND axisHandle = pAxisHandle.getHandle();

            //打开轴使能(根据实际情况使用)
            rtn = NMC_MtSetSvOn(axisHandle);
            ErrorHandler.checkError(rtn);
            System.out.printf("轴%d伺服使能 - 成功\n", axisNum);

            
            short[] comPos = {10, 20, -10};    // 正向补偿值
            short[] comNeg = {5, -5, 5};       // 负向补偿值
            short pointNum = 3;                // 补偿点数
            NativeLong pitch = new NativeLong(10000);
            NativeLong interval = new NativeLong(20000);

            //设置螺距误差补偿参数,3个点段直线，起点，终点
            rtn = NMC_MtSetLeadScrewCompPara(axisHandle, pointNum, pitch, interval, comPos, comNeg);
            ErrorHandler.checkError(rtn);
            System.out.println("设置螺距误差补偿参数 - 成功");
            
            // 启用螺距误差补偿
            rtn = NMC_MtEnableLeadScrew(axisHandle, (short)1);
            ErrorHandler.checkError(rtn);
            System.out.println("启用螺距误差补偿 - 成功");
            
            System.out.println("螺距误差补偿功能已成功配置");
            
        } catch (Exception e) {
            System.err.println("测试过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            System.out.println("\n释放资源...");
            // 实际应用中需要添加关闭轴和设备的代码
            // NMC_MtClose(pAxisHandle.getHandle());
            // NMC_DevClose(pDevHandle.getHandle());
        }
        
        System.out.println("螺距误差补偿功能测试完成");
    }
}