package com.bonait.bnframework.HBL.Communication.Modbus;

import static com.bonait.bnframework.HBL.DataUtil.DataConvertLib.ByteToShort;

import com.bonait.bnframework.HBL.Communication.CommBase;
import com.bonait.bnframework.HBL.DataUtil.FloatLib;
import com.bonait.bnframework.HBL.DataUtil.IntLib;
import com.bonait.bnframework.HBL.DataUtil.ShortLib;
import com.bonait.bnframework.HBL.Enum.DataFormat;
import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.HBL.Result.OperateResult;
import com.bonait.bnframework.HBL.Result.OperateResultT;
import com.licheedev.modbus4android.ModbusCallback;
import com.licheedev.modbus4android.ModbusParam;
import com.licheedev.modbus4android.ModbusRespException;
import com.licheedev.modbus4android.ModbusWorker;
import com.licheedev.modbus4android.param.SerialParam;
import com.licheedev.modbus4android.param.TcpParam;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsResponse;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;

public class ModbusMaster implements IRead,IWrite ,IModbusMaster{

    private boolean IsConnected=false;

    private ModbusWorker mw = new ModbusWorker();

    public void DisConnect(){  mw.release(); }

    public boolean IsReconnection=true;
    public DataFormat WriteDataFormat= DataFormat.ABCD;

    public DataFormat ReadDataFormat= DataFormat.BADC;

    public int SlaveId=1;

    @Override
    public OperateResult TcpConnect(String ip, int port) {
        try{
            MessageLog.ShowInfo("开始验证网络："+ip );
            boolean status = false;
            while (!status&&IsReconnection) {
                try {
                    status =new CommBase().NetPing(ip,1,1);//status为0则代表通，为1则代表不通。
                    Thread.sleep(1000);
                } catch (Exception e) {
                    MessageLog.ShowInfo("设备 " + ip + " 网络验证失败");
                }
            }
            MessageLog.ShowInfo("开始连接Modbus TCP" );
            ModbusParam param= TcpParam.create(ip, port).setTimeout(1000).setRetries(0).setEncapsulated(false).setKeepAlive(true);
            AtomicReference<String> errorInfo=new AtomicReference<>("");
            while (IsConnected==false)
            {
                errorInfo.set("");
                mw.init(param, new ModbusCallback<com.serotonin.modbus4j.ModbusMaster>() {
                    @Override
                    public void onSuccess(com.serotonin.modbus4j.ModbusMaster modbusMaster) {
                        IsConnected=true;
                        MessageLog.ShowInfo("Modbus TCP 连接成功" );
                    }
                    @Override
                    public void onFailure(Throwable tr) {
                        IsConnected = false;
                        errorInfo.set(tr.getMessage());
                        MessageLog.ShowInfo("Modbus TCP 连接失败" );
                    }
                    @Override
                    public void onFinally() {

                    }
                });
                if(!IsReconnection)break;
                if(IsConnected==false) Thread.sleep(5000);
            }
            if(IsConnected)return OperateResult.CreateSuccess();
            else return OperateResult.CreateFailed(errorInfo.get());
        }catch(Exception ex){
            return OperateResult.CreateFailed(ex);
        }
    }

    @Override
    public OperateResult RtuConnect(String com, int baudRate) {
        try{
            MessageLog.ShowInfo("开始连接Modbus RTU" );
            ModbusParam param= SerialParam.create(com, baudRate) // 串口地址和波特率
                    .setDataBits(8) // 数据位
                    .setParity(0) // 校验位
                    .setStopBits(1) // 停止位
                    .setTimeout(500).setRetries(0); // 不重试
            AtomicReference<String> errorInfo=new AtomicReference<>("");
            while (IsConnected==false)
            {
                mw.init(param, new ModbusCallback<com.serotonin.modbus4j.ModbusMaster>() {
                    @Override
                    public void onSuccess(com.serotonin.modbus4j.ModbusMaster modbusMaster) {
                        IsConnected=true;
                        MessageLog.ShowInfo("Modbus RTU 连接成功" );
                    }
                    @Override
                    public void onFailure(Throwable tr) {
                        IsConnected = false;
                        errorInfo.set(tr.getMessage());
                        MessageLog.ShowInfo("Modbus RTU 连接失败" );
                    }
                    @Override
                    public void onFinally() {

                    }
                });
                if(!IsReconnection)break;
                if(IsConnected==false) Thread.sleep(5000);
            }
            if(IsConnected)return OperateResult.CreateSuccess();
            else return OperateResult.CreateFailed(errorInfo.get());
        }catch(Exception ex){
            return OperateResult.CreateFailed(ex);
        }
    }

    @Override
    public boolean getConnected() {
        return IsConnected;
    }

    public <T> OperateResultT<T> Read(String address, int length){
//        if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
        AtomicReference<OperateResultT<T>>resultValue=new AtomicReference<OperateResultT<T>>();
        try{
            String typeName=  resultValue.get().Content.getClass().getCanonicalName();
            switch(typeName){
                case "java.lang.String":
                    resultValue.set((OperateResultT<T>)ReadString(address,length));
                    break;
                case "java.lang.Byte":
                    resultValue.set((OperateResultT<T>)ReadByte(address,1));
                    break;
                case "java.lang.Integer":
                    resultValue.set((OperateResultT<T>)ReadInt(address));
                    break;
                case "java.lang.Float":
                    resultValue.set((OperateResultT<T>)ReadFloat(address));
                    break;
                case "java.lang.Short":
                    resultValue.set((OperateResultT<T>)ReadShort(address));
                    break;
                case "java.lang.Boolean":
                    resultValue.set((OperateResultT<T>)ReadBool(address));
                    break;
                case "int[]":
                    resultValue.set((OperateResultT<T>)ReadInt(address,length));
                    break;
                case "float[]":
                    resultValue.set((OperateResultT<T>)ReadFloat(address,length));
                    break;
                case "short[]":
                    resultValue.set((OperateResultT<T>)ReadShort(address,length));
                    break;
                case "boolean[]":
                    resultValue.set((OperateResultT<T>)ReadBool(address,length));
                    break;
                default:
                    resultValue.set(OperateResultT.CreateFailed("不匹配的数据类型："+typeName));
                    break;
            }
        }catch(Exception ex){
            resultValue.set(OperateResultT.CreateFailed(ex));
        }
//        if(result!=null)result.Run(resultValue.get());
        return resultValue.get();
    }

    public <T> OperateResultT<T> Read(String address){
//        if(!getConnected()){ return OperateResultT.CreateFailedT("设备未连接");}
        AtomicReference<OperateResultT<T>>resultValue=new AtomicReference<>();
        resultValue.set(Read(address,1));
        return resultValue.get();
    }
    public <T> OperateResult Write(String address,T value) {
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        try{
            String typeName=  value.getClass().getCanonicalName();
            switch(typeName){
                case "java.lang.String":
                    resultValue.set(WriteString(address,value.toString(),SlaveId));
                    break;
                case "java.lang.Integer":
                    resultValue.set(WriteInt(address,Integer.parseInt(value.toString())));
                    break;
                case "java.lang.Float":
                    resultValue.set(WriteFloat(address,Float.parseFloat(value.toString())));
                    break;
                case "java.lang.Short":
                    resultValue.set(WriteShort(address,Short.parseShort(value.toString())));
                    break;
                case "java.lang.Boolean":
                    resultValue.set(WriteBool(address,Boolean.parseBoolean(value.toString())));
                    break;
                case "int[]":
                    resultValue.set(WriteInt(address,(int[])value));
                    break;
                case "float[]":
                    resultValue.set(WriteFloat(address,(float[])value));
                    break;
                case "short[]":
                    resultValue.set(WriteShort(address,(short[])value));
                    break;
                case "boolean[]":
                    resultValue.set(WriteBool(address,(boolean[])value));
                    break;
                default:
                    resultValue.set(OperateResult.CreateFailed("不匹配的数据类型："+typeName));
                    break;
            }
        }catch(Exception ex){
            resultValue.set(OperateResult.CreateFailed(ex));
        }
        return resultValue.get();
    }

    @Override
    public OperateResultT<boolean[]> ReadBool(String address, int length) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<boolean[]>>resultValue=new AtomicReference<>();
        new ExceptionServer(address, length, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                ReadCoilsResponse res = mw.syncReadCoil(SlaveId, add, length);
                boolean[] data = res.getBooleanData();
                boolean[] result = Arrays.copyOfRange(data, 0, length);
                resultValue.set(OperateResultT.CreateSuccess(result));
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResultT.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<Boolean> ReadBool(String address) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<Boolean>>resultValue=new AtomicReference<>();
        ReadBool(address,1).OnSource((s)->{
            resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
        }).OnFailed(s->{
            resultValue.set(OperateResultT.CreateFailed(s.message));
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<boolean[]> ReadInputCoil(String address, int length) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<boolean[]>>resultValue=new AtomicReference<>();
        new ExceptionServer(address, length, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                ReadDiscreteInputsResponse res = mw.syncReadDiscreteInput(SlaveId, add, length);
                boolean[] data = res.getBooleanData();
                boolean[] result = Arrays.copyOfRange(data, 0, length);
                resultValue.set(OperateResultT.CreateSuccess(result));
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResultT.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<Boolean> ReadInputCoil(String address) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<Boolean>>resultValue=new AtomicReference<>();
        ReadInputCoil(address,1).OnSource((s)->{
            resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
        }).OnFailed(s->{
            resultValue.set(OperateResultT.CreateFailed(s.message));
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<short[]> ReadShort(String address, int length) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<short[]>>resultValue=new AtomicReference<>();
        new ExceptionServer(address, length, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length);
                short[] data = res.getShortData();
                if (data.length == length) {
                    resultValue.set(OperateResultT.CreateSuccess(data));
                }
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResultT.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<Short> ReadShort(String address) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<Short>>resultValue=new AtomicReference<>();
        ReadShort(address,1).OnSource((s)->{
            resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
        }).OnFailed(s->{
            resultValue.set(OperateResultT.CreateFailed(s.message));
        });
        return resultValue.get();
    }
    @Override
    public OperateResultT<int[]> ReadInt(String address, int length) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<int[]>>resultValue=new AtomicReference<>();
        new ExceptionServer(address, length, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length * 2);
                int[] tempValues= IntLib.ToInts(res.getData(),ReadDataFormat);
                if(tempValues.length==length){
                    resultValue.set(OperateResultT.CreateSuccess(tempValues));
                }else{
                    resultValue.set(OperateResultT.CreateFailed(address+"，读取失败，返回长度和实际读取长度不匹配"));
                }
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResultT.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<Integer> ReadInt(String address) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<Integer>>resultValue=new AtomicReference<>();
        ReadInt(address,1).OnSource((s)->{
            resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
        }).OnFailed(s->{
            resultValue.set(OperateResultT.CreateFailed(s.message));
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<byte[]> ReadByte(String address, int length) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<byte[]>>resultValue=new AtomicReference<>();
        new ExceptionServer(address, length, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                int tempLength=length;
                if (length%2!=0){
                    tempLength++;
                }
                ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, tempLength );
                byte[] data = res.getData();
                if(data.length==tempLength){
                    byte[] result = Arrays.copyOfRange(data, 0, length);
                    resultValue.set(OperateResultT.CreateSuccess(result));
                }else{
                    resultValue.set(OperateResultT.CreateFailed(address+"，读取失败，返回长度和实际读取长度不匹配"));
                }
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResultT.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<String> ReadString(String address, int length) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<String>>resultValue=new AtomicReference<>();
        new ExceptionServer(address, length, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length);
                byte[] data = res.getData();
                try {
                    if (data.length ==length*2) {
                        resultValue.set(OperateResultT.CreateSuccess(new String(data, "UTF-8").trim()));
                    }
                } catch (UnsupportedEncodingException ex) {
                    resultValue.set(OperateResultT.CreateFailed(address+"，读取失败，字符串解析失败："+ex.toString()));
                }
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResultT.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<float[]> ReadFloat(String address, int length) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<float[]>>resultValue=new AtomicReference<>();
        new ExceptionServer(address, length, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                ReadHoldingRegistersResponse res = mw.syncReadHoldingRegisters(SlaveId, add, length*2);
                float[] tempValues = FloatLib.ToFloats(res.getData(),ReadDataFormat);
                if (tempValues.length == length) {
                    resultValue.set(OperateResultT.CreateSuccess(tempValues));
                }else{
                    resultValue.set(OperateResultT.CreateFailed(address+"，读取失败，返回长度和实际读取长度不匹配"));
                }
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResultT.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResultT<Float> ReadFloat(String address) {
        if(address==null||address.isEmpty()){ return OperateResultT.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResultT.CreateFailed("设备未连接");}
        AtomicReference<OperateResultT<Float>>resultValue=new AtomicReference<>();
        ReadFloat(address,1).OnSource((s)->{
            resultValue.set(OperateResultT.CreateSuccess(s.Content[0]));
        }).OnFailed(s->{
            resultValue.set(OperateResultT.CreateFailed(s.message));
        });
        return resultValue.get();
    }

    @Override
    public OperateResult WriteBool(String address, boolean value) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        return WriteBool(address,new boolean[]{value});
    }

    @Override
    public OperateResult WriteBool(String address, boolean[] value) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        new ExceptionServer(address, 1, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                mw.syncWriteCoils(SlaveId, add, value);
                resultValue.set(OperateResult.CreateSuccess());
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResult.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResult WriteBool(String address, boolean[] value, int slaveId) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        new ExceptionServer(address, 1, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                mw.syncWriteCoils(slaveId, add, value);
                resultValue.set(OperateResult.CreateSuccess());
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResult.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResult WriteShort(String address, short value) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        return WriteShort(address, new short[]{value});
    }

    @Override
    public OperateResult WriteShort(String address, short[] value) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        new ExceptionServer(address, 1, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                mw.syncWriteRegisters(SlaveId, add, value);
                resultValue.set(OperateResult.CreateSuccess());
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResult.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResult WriteShort(String address, short[] value, int slaveId) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        new ExceptionServer(address, 1, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                mw.syncWriteRegisters(slaveId, add, value);
                resultValue.set(OperateResult.CreateSuccess());
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResult.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResult WriteInt(String address, int value) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
       return WriteInt(address, new int[]{value});
    }

    @Override
    public OperateResult WriteInt(String address, int[] value) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        new ExceptionServer(address, 1, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                short[] send=ShortLib.ToShorts(value,WriteDataFormat);
                mw.syncWriteRegisters(SlaveId, add,send);
                resultValue.set(OperateResult.CreateSuccess());
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResult.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResult WriteInt(String address, int[] value, int slaveId) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        new ExceptionServer(address, 1, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                short[] send=ShortLib.ToShorts(value,WriteDataFormat);
                mw. syncWriteRegisters(slaveId, add,send);
                resultValue.set(OperateResult.CreateSuccess());
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResult.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResult WriteString(String address, String value, int slaveId) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        new ExceptionServer(address, 1, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                byte[] bytes= value.getBytes();
                short[] send =ByteToShort(bytes);
                mw.syncWriteRegisters(slaveId, add, send);
                resultValue.set(OperateResult.CreateSuccess());
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResult.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResult WriteFloat(String address, float value) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
       return WriteFloat(address, new float[]{value});
    }

    @Override
    public OperateResult WriteFloat(String address, float[] value) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        new ExceptionServer(address, 1, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                short[] send=ShortLib.ToShorts(value,WriteDataFormat);
                mw.syncWriteRegisters(SlaveId, add, send);
                resultValue.set(OperateResult.CreateSuccess());
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResult.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

    @Override
    public OperateResult WriteFloat(String address, float[] value, int slaveId) {
        if(address==null||address.isEmpty()){ return OperateResult.CreateFailed("无效的地址");}
        if(!getConnected()){ return OperateResult.CreateFailed("设备未连接");}
        AtomicReference<OperateResult>resultValue=new AtomicReference<>();
        new ExceptionServer(address, 1, new IExceptionHandling() {
            @Override
            public void onSuccess(int add) throws InterruptedException, ExecutionException, ModbusTransportException, ModbusInitException, ModbusRespException {
                short[] send=ShortLib.ToShorts(value,WriteDataFormat);
                mw.syncWriteRegisters(slaveId, add, send);
                resultValue.set(OperateResult.CreateSuccess());
            }

            @Override
            public void onFailure(String error){
                resultValue.set(OperateResult.CreateFailed(address+"，读取异常："+error));
            }
        });
        return resultValue.get();
    }

}
