using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TFT_MelsecMcNet
{
    public class MelsecMcNet
    {
        #region Global Member

        /// <summary>
        /// 单个数据字节的长度，西门子为2，三菱，欧姆龙，modbusTcp就为1，AB PLC无效
        /// </summary>
        /// <remarks>对设备来说，一个地址的数据对应的字节数，或是1个字节或是2个字节</remarks>
        public ushort WordLength { get; set; } = 1;
        /// <summary>
        /// 连接的IP地址
        /// </summary>
        private string ipAddress = "127.0.0.1";          // 连接的IP地址
        /// <summary>
        /// 端口号
        /// </summary>
        private int port = 10000;                        // 端口号
        /// <summary>
        /// TCP网络交互客户端对象
        /// </summary>
        private TcpClient tcpClient = null;
        /// <summary>
        /// 获取或是设置服务器的IP地址
        /// </summary>
        /// <remarks>
        /// 最好实在初始化的时候进行指定，当使用短连接的时候，支持动态更改，切换；当使用长连接后，无法动态更改
        /// </remarks>
        public string IpAddress
        {
            get
            {
                return ipAddress;
            }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    if (!IPAddress.TryParse(value, out _))
                    {
                        throw new Exception("Ip地址输入异常，格式不正确!");
                    }
                    ipAddress = value;
                }
                else
                {
                    ipAddress = "127.0.0.1";
                }
            }
        }
        /// <summary>
        /// 连接超时时间
        /// </summary>
        public int connectTimeOut = 5000;              // 连接超时时间设置
        /// <summary>
        /// 接收数据的超时时间
        /// </summary>
        public int receiveTimeOut = 10000;            // 数据接收的超时时间
        /// <summary>
        /// 发送数据的超时时间
        /// </summary>
        public int sendTimeOut = 10000;            // 数据发送的超时时间
        /// <summary>
        /// 是否是长连接的状态
        /// </summary>
        public bool isPersistentConn = false;         // 是否处于长连接的状态
        /// <summary>
        /// 当前的socket是否发生了错误
        /// </summary>
        public bool IsSocketError = false;            // 指示长连接的套接字是否处于错误的状态
        /// <summary>
        /// 交互的混合锁
        /// </summary>
        private readonly SimpleHybirdLock InteractiveLock;      // 一次正常的交互的互斥锁
        /// <summary>
        /// 获取或设置服务器的端口号
        /// </summary>
        /// <remarks>
        /// 最好实在初始化的时候进行指定，当使用短连接的时候，支持动态更改，切换；当使用长连接后，无法动态更改
        /// </remarks>
        /// <example>
        /// 动态更改请参照IpAddress属性的更改。
        /// </example>
        public int Port
        {
            get
            {
                return port;
            }
            set
            {
                port = value;
            }
        }
        /// <summary>
        /// 网络号，通常为0
        /// </summary>
        /// <remarks>
        /// 依据PLC的配置而配置，如果PLC配置了1，那么此处也填0，如果PLC配置了2，此处就填2，测试不通的话，继续测试0
        /// </remarks>
        public byte NetworkNumber { get; set; } = 0x00;

        /// <summary>
        /// 网络站号，通常为0
        /// </summary>
        /// <remarks>
        /// 依据PLC的配置而配置，如果PLC配置了1，那么此处也填0，如果PLC配置了2，此处就填2，测试不通的话，继续测试0
        /// </remarks>
        public byte NetworkStationNumber { get; set; } = 0x00;
        public Guid Token { get; set; }
        /// <summary>
        /// Socket传输中的缓冲池大小
        /// </summary>
        private readonly int SocketBufferSize = 4096;
        /// <summary>
        /// 获取或设置数据解析的格式，默认DCBA，也即是无修改，可选ABCD,BADC，CDAB，DCBA格式，对于Modbus协议来说，默认ABCD
        /// </summary>
        public DataFormatEnum DataFormat { get; set; }
        /// <summary>
        /// 是否使用同步的网络通讯
        /// </summary>
        public bool UseSynchronousNet { get; set; } = false;
        #endregion Global Member

        #region Constructor

        /// <summary>
        /// 实例化一个三菱的Qna兼容3E帧协议的通讯对象
        /// </summary>
        /// <param name="ipAddress">PLC的Ip地址</param>
        /// <param name="port">PLC的端口</param>
        /// <param name="isPersistentConnected">是否使用Socket长链接。默认值为：true，默认使用长链接</param>
        public MelsecMcNet(string ipAddress, int port, bool isPersistentConnected = true)
        {
            WordLength = 1;
            IpAddress = ipAddress;
            Port = port;
            isPersistentConn = isPersistentConnected;
            InteractiveLock = new SimpleHybirdLock(); // 实例化数据访问锁
            DataFormat = DataFormatEnum.DCBA;
        }
        #endregion

        #region Connect And Close
        /// <summary>
        /// 连接TcpServer端。
        /// </summary>
        /// <returns>返回连接结果，如果失败的话（也即IsSuccess为False），包含失败信息</returns>
        public OperateResult ConnectServer()
        {
            OperateResult result = new OperateResult();

            // 重新连接之前，先将旧的数据进行清空
            tcpClient?.Close();
            tcpClient?.Dispose();

            OperateResult<TcpClient> rSocket = CreateSocketAndInitialication();

            if (!rSocket.IsSuccess)
            {
                IsSocketError = true;
                rSocket.Content = null;
                result.Message = rSocket.Message;
            }
            else
            {
                tcpClient = rSocket.Content;
                result.IsSuccess = true;
                result.Message = rSocket.Message;
            }

            return result;
        }
        /// <summary>
        /// 连接并初始化网络套接字
        /// </summary>
        /// <returns>带有socket的结果对象</returns>
        private OperateResult<TcpClient> CreateSocketAndInitialication()
        {
            OperateResult<TcpClient> result = CreateSocketAndConnect(new IPEndPoint(IPAddress.Parse(ipAddress), port), connectTimeOut);
            if (result.IsSuccess)
            {
                // 初始化
                OperateResult initi = InitializationOnConnect(result.Content);
                if (!initi.IsSuccess)
                {
                    result.Content?.Close();
                    result.IsSuccess = initi.IsSuccess;
                    result.CopyErrorFromOther(initi);
                }
            }
            return result;
        }
        /// <summary>
        /// 连接上服务器后需要进行的初始化操作
        /// </summary>
        /// <param name="socket">网络套接字</param>
        /// <returns>是否初始化成功，依据具体的协议进行重写</returns>
        /// <example>
        /// 有些协议不需要握手信号，比如三菱的MC协议、Modbus协议；西门子和欧姆龙就存在握手信息；
        /// </example>
        private OperateResult InitializationOnConnect(TcpClient socket)
        {
            return OperateResult.CreateSuccessResult();
        }
        /// <summary>
        /// 创建一个新的socket对象并连接到远程的地址
        /// </summary>
        /// <param name="endPoint">连接的目标终结点</param>
        /// <param name="timeOut">连接的超时时间</param>
        /// <returns>返回套接字的封装结果对象</returns>
        private OperateResult<TcpClient> CreateSocketAndConnect(IPEndPoint endPoint, int timeOut)
        {
            tcpClient?.Close();
            tcpClient = null;
            tcpClient = new TcpClient
            {
                ReceiveTimeout = receiveTimeOut,
                SendTimeout = sendTimeOut
            };
            try
            {
                SylTimeOut connectTimeout = new SylTimeOut()
                {
                    WorkSocket = tcpClient,
                    DelayTime = timeOut
                };
                Task.Run(() => ThreadPoolCheckTimeOut(connectTimeout));//超时检查
                tcpClient.Connect(endPoint);
                connectTimeout.IsSuccessful = true;

                return OperateResult.CreateSuccessResult(tcpClient);
            }
            catch (Exception ex)
            {
                tcpClient?.Close();
                return OperateResult.CreateFailedResult<TcpClient>(new OperateResult(ex.HResult, $"【{ex.Message}】-【{ex.StackTrace}】"));
            }
        }
        /// <summary>
        /// 检查网络套接字是否操作超时，需要对套接字进行封装
        /// </summary>
        /// <param name="obj">通常是 <see cref="HslTimeOut"/> 对象 </param>
        private void ThreadPoolCheckTimeOut(SylTimeOut timeout)
        {
            while (!timeout.IsSuccessful)
            {
                Thread.Sleep(100);
                if ((DateTime.Now - timeout.StartTime).TotalMilliseconds > timeout.DelayTime)
                {
                    // 连接超时或是验证超时
                    if (!timeout.IsSuccessful)
                    {
                        timeout.Operator?.Invoke();
                        timeout.WorkSocket?.Close();
                    }
                    break;
                }
            }
        }
        /// <summary>
        /// 断开服务器的连接
        /// </summary>
        /// <returns>关闭连接，不需要查看IsSuccess属性查看</returns>
        public OperateResult ConnectClose()
        {
            InteractiveLock.Enter();
            // 额外操作
            OperateResult result = ExtraOnDisconnect(tcpClient.Client);
            // 关闭信息
            tcpClient?.Close();
            tcpClient?.Dispose();
            InteractiveLock.Leave();

            return result;
        }
        /// <summary>
        /// 在将要和服务器进行断开的情况下额外的操作，需要根据对应协议进行重写
        /// </summary>
        /// <param name="socket">网络套接字</param>
        /// <example>
        /// 目前暂无相关的示例，组件支持的协议都不用实现这个方法。
        /// </example>
        /// <returns>当断开连接时额外的操作结果</returns>
        private OperateResult ExtraOnDisconnect(Socket socket)
        {
            return OperateResult.CreateSuccessResult();
        }
        #endregion Connect And Close

        #region Read Write Support

        #region Read Bool
        /// <summary>
        /// 从三菱PLC中批量读取位软元件，返回读取结果
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <returns>带成功标志的结果数据对象</returns>
        /// <example>参照 <see cref="ReadBool(string, ushort)"/> 方法 </example>
        public OperateResult<bool> ReadBool(string address)
        {
            OperateResult<bool[]> read = ReadBool(address, 1);
            if (!read.IsSuccess) return OperateResult.CreateFailedResult<bool>(read);

            return OperateResult.CreateSuccessResult(read.Content[0]);
        }
        /// <summary>
        /// 从三菱PLC中批量读取位软元件，返回读取结果
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">读取的长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        /// <remarks>
        /// 地址支持的列表参考 <seealso cref="MelsecMcNet"/> 的备注说明
        /// </remarks>
        public OperateResult<bool[]> ReadBool(string address, ushort length)
        {
            // 分析地址
            OperateResult<McAddressData> addressResult = McAnalysisAddress(address, length);
            if (!addressResult.IsSuccess) return OperateResult.CreateFailedResult<bool[]>(addressResult);

            // 获取指令
            byte[] coreResult = MelsecHelper.BuildReadMcCoreCommand(addressResult.Content, true);

            // 核心交互
            var read = ReadFromCoreServer(PackMcCommand(coreResult, NetworkNumber, NetworkStationNumber));
            if (!read.IsSuccess) return OperateResult.CreateFailedResult<bool[]>(read);

            // 错误代码验证
            ushort errorCode = BitConverter.ToUInt16(read.Content, 9);
            if (errorCode != 0) return new OperateResult<bool[]>(errorCode, StringResources.Language.MelsecPleaseReferToManulDocument);

            // 数据解析，需要传入是否使用位的参数
            var extract = ExtractActualData(SoftBasic.BytesArrayRemoveBegin(read.Content, 11), true);
            if (!extract.IsSuccess) return OperateResult.CreateFailedResult<bool[]>(extract);

            // 转化bool数组
            return OperateResult.CreateSuccessResult(extract.Content.Select(m => m == 0x01).Take(length).ToArray());
        }
        #endregion Read Bool

        #region Read short
        /// <summary>
        /// 读取设备的short类型的数据
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<short> ReadInt16(string address)
        {
            return ByteTransformHelper.GetResultFromArray(ReadInt16(address, 1));
        }
        /// <summary>
        /// 读取设备的short类型的数组
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">数组长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<short[]> ReadInt16(string address, ushort length)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, (ushort)(length * WordLength)), m => TransInt16(m, 0, length));
        }
        /// <summary>
        /// 从缓存中提取short结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <returns>short对象</returns>
        private short TransInt16(byte[] buffer, int index)
        {
            return BitConverter.ToInt16(buffer, index);
        }

        /// <summary>
        /// 从缓存中提取short数组结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">读取的数组长度</param>
        /// <returns>short数组对象</returns>
        private short[] TransInt16(byte[] buffer, int index, int length)
        {
            short[] tmp = new short[length];
            for (int i = 0; i < length; i++)
            {
                tmp[i] = TransInt16(buffer, index + 2 * i);
            }
            return tmp;
        }
        #endregion Read short

        #region Read ushort
        /// <summary>
        /// 读取设备的ushort数据类型的数据
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<ushort> ReadUInt16(string address)
        {
            return ByteTransformHelper.GetResultFromArray(ReadUInt16(address, 1));
        }


        /// <summary>
        /// 读取设备的ushort类型的数组
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">数组长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<ushort[]> ReadUInt16(string address, ushort length)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, (ushort)(length * WordLength)), m => TransUInt16(m, 0, length));
        }
        /// <summary>
        /// 从缓存中提取ushort结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <returns>ushort对象</returns>
        private ushort TransUInt16(byte[] buffer, int index)
        {
            return BitConverter.ToUInt16(buffer, index);
        }

        /// <summary>
        /// 从缓存中提取ushort数组结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">读取的数组长度</param>
        /// <returns>ushort数组对象</returns>
        private ushort[] TransUInt16(byte[] buffer, int index, int length)
        {
            ushort[] tmp = new ushort[length];
            for (int i = 0; i < length; i++)
            {
                tmp[i] = TransUInt16(buffer, index + 2 * i);
            }
            return tmp;
        }
        #endregion Read ushort

        #region  Read int
        /// <summary>
        /// 读取设备的int类型的数据
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<int> ReadInt32(string address)
        {
            return ByteTransformHelper.GetResultFromArray(ReadInt32(address, 1));
        }

        /// <summary>
        /// 读取设备的int类型的数组
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">数组长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<int[]> ReadInt32(string address, ushort length)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, (ushort)(length * WordLength * 2)), m => TransInt32(m, 0, length));
        }
        /// <summary>
        /// 从缓存中提取int结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <returns>int对象</returns>
        private int TransInt32(byte[] buffer, int index)
        {
            return BitConverter.ToInt32(ByteTransDataFormat4(buffer, index), 0);
        }

        /// <summary>
        /// 从缓存中提取int数组结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">读取的数组长度</param>
        /// <returns>int数组对象</returns>
        private int[] TransInt32(byte[] buffer, int index, int length)
        {
            int[] tmp = new int[length];
            for (int i = 0; i < length; i++)
            {
                tmp[i] = TransInt32(buffer, index + 4 * i);
            }
            return tmp;
        }
        #endregion Read int

        #region Read uint
        /// <summary>
        /// 读取设备的uint类型的数据
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<uint> ReadUInt32(string address)
        {
            return ByteTransformHelper.GetResultFromArray(ReadUInt32(address, 1));
        }

        /// <summary>
        /// 读取设备的uint类型的数组
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">数组长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        /// <example>
        public OperateResult<uint[]> ReadUInt32(string address, ushort length)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, (ushort)(length * WordLength * 2)), m => TransUInt32(m, 0, length));
        }
        /// <summary>
        /// 从缓存中提取uint结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <returns>uint对象</returns>
        private uint TransUInt32(byte[] buffer, int index)
        {
            return BitConverter.ToUInt32(ByteTransDataFormat4(buffer, index), 0);
        }

        /// <summary>
        /// 从缓存中提取uint数组结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">读取的数组长度</param>
        /// <returns>uint数组对象</returns>
        private uint[] TransUInt32(byte[] buffer, int index, int length)
        {
            uint[] tmp = new uint[length];
            for (int i = 0; i < length; i++)
            {
                tmp[i] = TransUInt32(buffer, index + 4 * i);
            }
            return tmp;
        }
        #endregion Read uint

        #region Read long
        /// <summary>
        /// 读取设备的long类型的数据
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<long> ReadInt64(string address)
        {
            return ByteTransformHelper.GetResultFromArray(ReadInt64(address, 1));
        }

        /// <summary>
        /// 读取设备的long类型的数组
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">数组长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<long[]> ReadInt64(string address, ushort length)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, (ushort)(length * WordLength * 4)), m => TransInt64(m, 0, length));
        }
        /// <summary>
        /// 从缓存中提取long结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <returns>long对象</returns>
        private long TransInt64(byte[] buffer, int index)
        {
            return BitConverter.ToInt64(ByteTransDataFormat8(buffer, index), 0);
        }

        /// <summary>
        /// 从缓存中提取long数组结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">读取的数组长度</param>
        /// <returns>long数组对象</returns>
        private long[] TransInt64(byte[] buffer, int index, int length)
        {
            long[] tmp = new long[length];
            for (int i = 0; i < length; i++)
            {
                tmp[i] = TransInt64(buffer, index + 8 * i);
            }
            return tmp;
        }
        #endregion Read long

        #region Read ulong
        /// <summary>
        /// 读取设备的ulong类型的数据
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<ulong> ReadUInt64(string address)
        {
            return ByteTransformHelper.GetResultFromArray(ReadUInt64(address, 1));
        }

        /// <summary>
        /// 读取设备的ulong类型的数组
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">数组长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<ulong[]> ReadUInt64(string address, ushort length)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, (ushort)(length * WordLength * 4)), m => TransUInt64(m, 0, length));
        }

        /// <summary>
        /// 从缓存中提取ulong结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <returns>ulong对象</returns>
        private ulong TransUInt64(byte[] buffer, int index)
        {
            return BitConverter.ToUInt64(ByteTransDataFormat8(buffer, index), 0);
        }

        /// <summary>
        /// 从缓存中提取ulong数组结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">读取的数组长度</param>
        /// <returns>ulong数组对象</returns>
        private ulong[] TransUInt64(byte[] buffer, int index, int length)
        {
            ulong[] tmp = new ulong[length];
            for (int i = 0; i < length; i++)
            {
                tmp[i] = TransUInt64(buffer, index + 8 * i);
            }
            return tmp;
        }
        #endregion Read ulong

        #region Read float
        /// <summary>
        /// 读取设备的float类型的数据
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<float> ReadFloat(string address)
        {
            return ByteTransformHelper.GetResultFromArray(ReadFloat(address, 1));
        }


        /// <summary>
        /// 读取设备的float类型的数组
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">数组长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<float[]> ReadFloat(string address, ushort length)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, (ushort)(length * WordLength * 2)), m => TransSingle(m, 0, length));
        }
        /// <summary>
        /// 从缓存中提取float结果
        /// </summary>
        /// <param name="buffer">缓存对象</param>
        /// <param name="index">索引位置</param>
        /// <returns>float对象</returns>
        private float TransSingle(byte[] buffer, int index)
        {
            return BitConverter.ToSingle(ByteTransDataFormat4(buffer, index), 0);
        }

        /// <summary>
        /// 从缓存中提取float数组结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">读取的数组长度</param>
        /// <returns>float数组对象</returns>
        private float[] TransSingle(byte[] buffer, int index, int length)
        {
            float[] tmp = new float[length];
            for (int i = 0; i < length; i++)
            {
                tmp[i] = TransSingle(buffer, index + 4 * i);
            }
            return tmp;
        }
        #endregion Read float

        #region Read double
        /// <summary>
        /// 读取设备的double类型的数据
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<double> ReadDouble(string address)
        {
            return ByteTransformHelper.GetResultFromArray(ReadDouble(address, 1));
        }

        /// <summary>
        /// 读取设备的double类型的数组
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">数组长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        public OperateResult<double[]> ReadDouble(string address, ushort length)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, (ushort)(length * WordLength * 4)), m => TransDouble(m, 0, length));
        }
        /// <summary>
        /// 从缓存中提取double结果
        /// </summary>
        /// <param name="buffer">缓存对象</param>
        /// <param name="index">索引位置</param>
        /// <returns>double对象</returns>
        private double TransDouble(byte[] buffer, int index)
        {
            return BitConverter.ToDouble(ByteTransDataFormat8(buffer, index), 0);
        }

        /// <summary>
        /// 从缓存中提取double数组结果
        /// </summary>
        /// <param name="buffer">缓存对象</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">读取的数组长度</param>
        /// <returns>double数组对象</returns>
        private double[] TransDouble(byte[] buffer, int index, int length)
        {
            double[] tmp = new double[length];
            for (int i = 0; i < length; i++)
            {
                tmp[i] = TransDouble(buffer, index + 8 * i);
            }
            return tmp;
        }
        #endregion Read double

        #region Read string
        /// <summary>
        /// 读取设备的字符串数据，编码为ASCII
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">地址长度</param>
        /// <returns>带成功标志的结果数据对象</returns>
        /// <example>
        /// 以下为三菱的连接对象示例，其他的设备读写情况参照下面的代码：
        /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Core\NetworkDeviceBase.cs" region="ReadString" title="String类型示例" />
        /// </example>
        public OperateResult<string> ReadString(string address, ushort length)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, length), m => TransString(m, 0, m.Length, Encoding.ASCII));
        }

        /// <summary>
        /// 读取设备的字符串数据，编码为指定的编码信息
        /// </summary>
        /// <param name="address">起始地址</param>
        /// <param name="length">地址长度</param>
        /// <param name="encoding">编码机制</param>
        /// <returns>带成功标志的结果数据对象</returns>
        /// <example>
        /// 以下为三菱的连接对象示例，其他的设备读写情况参照下面的代码：
        /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Core\NetworkDeviceBase.cs" region="ReadString" title="String类型示例" />
        /// </example>
        public OperateResult<string> ReadString(string address, ushort length, Encoding encoding)
        {
            return ByteTransformHelper.GetResultFromBytes(Read(address, length), m => TransString(m, 0, m.Length, encoding));
        }
        /// <summary>
        /// 从缓存中提取string结果，使用指定的编码
        /// </summary>
        /// <param name="buffer">缓存对象</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">byte数组长度</param>
        /// <param name="encoding">字符串的编码</param>
        /// <returns>string对象</returns>
        private string TransString(byte[] buffer, int index, int length, Encoding encoding)
        {
            byte[] tmp = TransByte(buffer, index, length);
            return encoding.GetString(tmp);
        }
        #endregion Read string

        #region Read byte array 读取PLC数据 核心代码
        public OperateResult<byte> Read(string address)
        {
            OperateResult<byte[]> read = Read(address, 1);
            if (!read.IsSuccess) return OperateResult.CreateFailedResult<byte>(read);

            return OperateResult.CreateSuccessResult(read.Content[0]);
        }
        /// <summary>
        /// 从三菱PLC中读取想要的数据，输入地址，按照字单位读取，返回读取结果
        /// </summary>
        /// <param name="address">读取地址，格式为"M100","D100","W1A0"</param>
        /// <param name="length">读取的数据长度，字最大值960，位最大值7168</param>
        /// <returns>带成功标志的结果数据对象</returns>
        /// <remarks>
        /// 地址支持的列表参考 <seealso cref="MelsecMcNet"/> 的备注说明
        /// </remarks>
        public OperateResult<byte[]> Read(string address, ushort length)
        {
            // 分析地址
            OperateResult<McAddressData> addressResult = McAnalysisAddress(address, length);
            if (!addressResult.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(addressResult);

            List<byte> bytesContent = new List<byte>();
            ushort alreadyFinished = 0;
            while (alreadyFinished < length)
            {
                ushort readLength = (ushort)Math.Min(length - alreadyFinished, 900);
                addressResult.Content.Length = readLength;
                OperateResult<byte[]> read = ReadAddressData(addressResult.Content);
                if (!read.IsSuccess) return read;

                bytesContent.AddRange(read.Content);
                alreadyFinished += readLength;

                // 字的话就是正常的偏移位置，如果是位的话，就转到位的数据
                if (addressResult.Content.McDataType.DataType == 0)
                    addressResult.Content.AddressStart += readLength;
                else
                    addressResult.Content.AddressStart += readLength * 16;
            }
            return OperateResult.CreateSuccessResult(bytesContent.ToArray());
        }
        /// <summary>
        /// 分析地址的方法，允许派生类里进行重写操作
        /// </summary>
        /// <param name="address">地址信息</param>
        /// <param name="length">数据长度</param>
        /// <returns>解析后的数据信息</returns>
        private OperateResult<McAddressData> McAnalysisAddress(string address, ushort length)
        {
            return McAddressData.ParseMelsecFrom(address, length);
        }
        private OperateResult<byte[]> ReadAddressData(McAddressData addressData)
        {
            byte[] coreResult = MelsecHelper.BuildReadMcCoreCommand(addressData, false);

            // 核心交互
            var read = ReadFromCoreServer(PackMcCommand(coreResult, this.NetworkNumber, this.NetworkStationNumber));
            if (!read.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(read);

            // 错误代码验证
            ushort errorCode = BitConverter.ToUInt16(read.Content, 9);
            if (errorCode != 0) return new OperateResult<byte[]>(errorCode, StringResources.Language.MelsecPleaseReferToManulDocument);

            // 数据解析，需要传入是否使用位的参数
            return ExtractActualData(SoftBasic.BytesArrayRemoveBegin(read.Content, 11), false);
        }
        /// <summary>
        /// 使用底层的数据报文来通讯，传入需要发送的消息，返回一条完整的数据指令
        /// </summary>
        /// <param name="send">发送的完整的报文信息</param>
        /// <returns>接收的完整的报文信息</returns>
        /// <remarks>
        public OperateResult<byte[]> ReadFromCoreServer(byte[] send)
        {
            var result = new OperateResult<byte[]>();

            InteractiveLock.Enter();

            // 获取有用的网络通道，如果没有，就建立新的连接
            OperateResult<TcpClient> resultSocket = GetAvailableSocket();
            if (!resultSocket.IsSuccess)
            {
                IsSocketError = true;
                InteractiveLock.Leave();
                result.CopyErrorFromOther(resultSocket);
                return result;
            }

            OperateResult<byte[]> read = ReadFromCoreServer(resultSocket.Content, send);

            if (read.IsSuccess)
            {
                IsSocketError = false;
                result.IsSuccess = read.IsSuccess;
                result.Content = read.Content;
                result.Message = StringResources.Language.SuccessText;
            }
            else
            {
                IsSocketError = true;
                result.CopyErrorFromOther(read);
            }

            ExtraAfterReadFromCoreServer(read);

            InteractiveLock.Leave();
            if (!isPersistentConn) resultSocket.Content?.Close();
            return result;
        }
        /// <summary>
        /// 在其他指定的套接字上，使用报文来通讯，传入需要发送的消息，返回一条完整的数据指令
        /// </summary>
        /// <param name="socket">指定的套接字</param>
        /// <param name="send">发送的完整的报文信息</param>
        /// <remarks>
        /// 无锁的基于套接字直接进行叠加协议的操作。
        /// </remarks>
        /// <returns>接收的完整的报文信息</returns>
        public OperateResult<byte[]> ReadFromCoreServer(TcpClient socket, byte[] send)
        {
            INetMessage netMessage = new MelsecQnA3EBinaryMessage
            {
                SendBytes = send
            };

            // send
            OperateResult sendResult = Send(socket, send);
            if (!sendResult.IsSuccess)
            {
                socket?.Close();
                return OperateResult.CreateFailedResult<byte[]>(sendResult);
            }

            if (receiveTimeOut < 0) return OperateResult.CreateSuccessResult(new byte[0]);

            // receive msg
            OperateResult<byte[]> resultReceive = ReceiveByMessage(socket, receiveTimeOut, netMessage);
            if (!resultReceive.IsSuccess)
            {
                socket?.Close();
                return new OperateResult<byte[]>(StringResources.Language.ReceiveDataTimeout + receiveTimeOut);
            }

            // check
            if (!netMessage.CheckHeadBytesLegal(Token.ToByteArray()))
            {
                socket?.Close();
                return new OperateResult<byte[]>(StringResources.Language.CommandHeadCodeCheckFailed);
            }

            // Success
            return OperateResult.CreateSuccessResult(resultReceive.Content);
        }
        /// <summary>
        /// 发送消息给套接字，直到完成的时候返回
        /// </summary>
        /// <param name="socket">网络套接字</param>
        /// <param name="data">字节数据</param>
        /// <returns>发送是否成功的结果</returns>
        protected OperateResult Send(TcpClient socket, byte[] data)
        {
            if (data == null) return OperateResult.CreateSuccessResult();
            try
            {
                NetworkStream stream = socket.GetStream();
                stream.Write(data, 0, data.Length);
                //socket.Client.Send(data);
                return OperateResult.CreateSuccessResult();
            }
            catch (Exception ex)
            {
                socket?.Close();
                return new OperateResult<byte[]>(ex.Message);
            }
        }
        /// <summary>
        /// 接收一条完整的 <seealso cref="INetMessage"/> 数据内容 ->
        /// Receive a complete <seealso cref="INetMessage"/> data content
        /// </summary>
        /// <param name="socket">网络的套接字</param>
        /// <param name="timeOut">超时时间</param>
        /// <param name="netMessage">消息的格式定义</param>
        /// <returns>带有是否成功的byte数组对象</returns>
        protected OperateResult<byte[]> ReceiveByMessage(TcpClient socket, int timeOut, INetMessage netMessage)
        {
            SylTimeOut receiveTimeout = new SylTimeOut()
            {
                WorkSocket = tcpClient,
                DelayTime = timeOut
            };
            Task.Run(() => ThreadPoolCheckTimeOut(receiveTimeout));//超时检查
            // 接收指令头
            OperateResult<byte[]> headResult = Receive(socket, netMessage.ProtocolHeadBytesLength);
            if (!headResult.IsSuccess)
            {
                receiveTimeout.IsSuccessful = true;
                return headResult;
            }

            netMessage.HeadBytes = headResult.Content;
            int contentLength = netMessage.GetContentLengthByHeadBytes();
            if (contentLength <= 0)
            {
                receiveTimeout.IsSuccessful = true;
                return headResult;
            }

            OperateResult<byte[]> contentResult = Receive(socket, contentLength);
            if (!contentResult.IsSuccess)
            {
                receiveTimeout.IsSuccessful = true;
                return contentResult;
            }

            receiveTimeout.IsSuccessful = true;
            netMessage.ContentBytes = contentResult.Content;
            return OperateResult.CreateSuccessResult(SoftBasic.SpliceTwoByteArray(headResult.Content, contentResult.Content));
        }
        /// <summary>
        /// 接收固定长度的字节数组
        /// </summary>
        /// <remarks>
        /// Receive Special Length Bytes
        /// </remarks>
        /// <param name="socket">网络通讯的套接字</param>
        /// <param name="length">准备接收的数据长度</param>
        /// <returns>包含了字节数据的结果类</returns>
        protected OperateResult<byte[]> Receive(TcpClient socket, int length)
        {
            if (length == 0) return OperateResult.CreateSuccessResult(new byte[0]);

            if (UseSynchronousNet)
            {
                try
                {
                    byte[] data = ReadBytesFromSocket(socket, length);
                    return OperateResult.CreateSuccessResult(data);
                }
                catch (Exception ex)
                {
                    socket?.Close();
                    return new OperateResult<byte[]>($"【{ex.Message}】---【{ex.StackTrace}】");
                }
            }

            NetworkStream stream = socket.GetStream();
            OperateResult<byte[]> result = new OperateResult<byte[]>();
            ManualResetEvent receiveDone = null;
            StateObject state = null;
            try
            {
                receiveDone = new ManualResetEvent(false);
                state = new StateObject(length);
            }
            catch (Exception ex)
            {
                return new OperateResult<byte[]>($"【{ex.Message}】---【{ex.StackTrace}】");
            }


            try
            {
                state.WaitDone = receiveDone;
                state.WorkSocket = socket;

                // Begin receiving the data from the remote device.
                //socket.BeginReceive(state.Buffer, state.AlreadyDealLength,state.DataLength - state.AlreadyDealLength, SocketFlags.None,new AsyncCallback(ReceiveCallback), state);
                stream.BeginRead(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength, new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception ex)
            {
                // 发生了错误，直接返回
                result.Message = $"【{ex.Message}】---【{ex.StackTrace}】";
                receiveDone.Close();
                socket?.Close();
                return result;
            }



            // 等待接收完成，或是发生异常
            receiveDone.WaitOne();
            receiveDone.Close();
            stream.Flush();


            // 接收数据失败
            if (state.IsError)
            {
                socket?.Close();
                result.Message = state.ErrerMsg;
                return result;
            }


            // 远程关闭了连接
            if (state.IsClose)
            {
                // result.IsSuccess = true;
                result.Message = StringResources.Language.RemoteClosedConnection;
                socket?.Close();
                return result;
            }


            // 正常接收到数据
            result.Content = state.Buffer;
            result.IsSuccess = true;
            state.Clear();
            state = null;
            return result;
        }

        #region 异步网络通讯

        private void ReceiveCallback(IAsyncResult ar)
        {
            if (ar.AsyncState is StateObject state)
            {
                try
                {
                    //Socket client = state.WorkSocket;
                    NetworkStream stream = state.WorkSocket.GetStream();
                    int bytesRead = stream.EndRead(ar);

                    if (bytesRead > 0)
                    {
                        // 接收到了数据
                        state.AlreadyDealLength += bytesRead;
                        if (state.AlreadyDealLength < state.DataLength)
                        {
                            // 获取接下来的所有的数据
                            //client.BeginReceive(state.Buffer, state.AlreadyDealLength,state.DataLength - state.AlreadyDealLength, SocketFlags.None,new AsyncCallback(ReceiveCallback), state);
                            stream.BeginRead(state.Buffer, state.AlreadyDealLength, state.DataLength - state.AlreadyDealLength, new AsyncCallback(ReceiveCallback), state);
                        }
                        else
                        {
                            // 接收到了所有的数据，通知接收数据的线程继续
                            state.WaitDone.Set();
                        }
                    }
                    else
                    {
                        // 对方关闭了网络通讯
                        state.IsClose = true;
                        state.WaitDone.Set();
                    }
                }
                catch (Exception ex)
                {
                    state.IsError = true;
                    state.ErrerMsg = $"【{ex.Message}】---【{ex.StackTrace}】";
                    state.WaitDone.Set();
                }
            }
        }

        #endregion 异步网络通讯

        #region 同步网络通讯
        private byte[] ReadBytesFromSocket(TcpClient socket, int receive)
        {
            return ReadBytesFromSocket(socket, receive, null, false, false);
        }
        /// <summary>
        /// 读取socket数据的基础方法，只适合用来接收指令头，或是同步数据
        /// </summary>
        /// <param name="socket">通信对象</param>
        /// <param name="receive">接收的长度</param>
        /// <param name="report">用于报告接收进度的对象</param>
        /// <param name="reportByPercent">是否按照百分比报告进度</param>
        /// <param name="response">是否回发接收数据长度</param>
        /// <returns>接收到的字节数据</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="SocketException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <exception cref="System.Security.SecurityException"></exception>
        /// <example>
        /// 接收数据的举例，输出报告，不根据百分比来产生报告，不回复接收进度。
        /// </example>
        public byte[] ReadBytesFromSocket(TcpClient socket, int receive, Action<long, long> report, bool reportByPercent, bool response)
        {
            byte[] bytes_receive = new byte[receive];
            int count_receive = 0;
            long percent = 0;
            NetworkStream stream = socket.GetStream();
            while (count_receive < receive)
            {
                // 分割成2KB来接收数据
                int receive_length = (receive - count_receive) >= SocketBufferSize ? SocketBufferSize : (receive - count_receive);
                //count_receive += socket.Client.Receive(bytes_receive, count_receive, receive_length, SocketFlags.None);
                count_receive += stream.Read(bytes_receive, count_receive, receive_length);
                if (reportByPercent)
                {
                    long percentCurrent = (long)count_receive * 100 / receive;
                    if (percent != percentCurrent)
                    {
                        percent = percentCurrent;
                        // 报告进度
                        report?.Invoke(count_receive, receive);
                    }
                }
                else
                {
                    // 报告进度
                    report?.Invoke(count_receive, receive);
                }
                // 回发进度
                if (response) socket.Client.Send(BitConverter.GetBytes((long)count_receive));
            }
            stream.Close();
            return bytes_receive;
        }
        #endregion 同步网络通讯

        /// <summary>
        /// 和服务器交互完成的时候调用的方法，无论是成功或是失败，都将会调用，具体的操作需要重写实现
        /// </summary>
        /// <param name="read">读取结果</param>
        private void ExtraAfterReadFromCoreServer(OperateResult read)
        {

        }
        /// <summary>
        /// 获取本次操作的可用的网络套接字
        /// </summary>
        /// <returns>是否成功，如果成功，使用这个套接字</returns>
        protected OperateResult<TcpClient> GetAvailableSocket()
        {
            if (isPersistentConn) // 长连接模式
            {                
                if (IsSocketError || tcpClient == null)
                {
                    OperateResult connect = ConnectServer();
                    if (!connect.IsSuccess)
                    {
                        IsSocketError = true;
                        return OperateResult.CreateFailedResult<TcpClient>(connect);
                    }
                    else
                    {
                        IsSocketError = false;
                        return OperateResult.CreateSuccessResult(tcpClient);
                    }
                }
                else
                {
                    return OperateResult.CreateSuccessResult(tcpClient);
                }
            }
            else // 短连接模式
            {                
                return CreateSocketAndInitialication();
            }
        }
        #endregion Read byte array 读取PLC数据 核心代码

        #region Common method Helper
        /// <summary>
        /// 反转多字节的数据信息
        /// </summary>
        /// <param name="value">数据字节</param>
        /// <param name="index">起始索引，默认值为0</param>
        /// <returns>实际字节信息</returns>
        private byte[] ByteTransDataFormat4(byte[] value, int index = 0)
        {
            byte[] buffer = new byte[4];
            switch (DataFormat)
            {
                case DataFormatEnum.ABCD:
                    {
                        buffer[0] = value[index + 3];
                        buffer[1] = value[index + 2];
                        buffer[2] = value[index + 1];
                        buffer[3] = value[index + 0];
                        break;
                    }
                case DataFormatEnum.BADC:
                    {
                        buffer[0] = value[index + 2];
                        buffer[1] = value[index + 3];
                        buffer[2] = value[index + 0];
                        buffer[3] = value[index + 1];
                        break;
                    }

                case DataFormatEnum.CDAB:
                    {
                        buffer[0] = value[index + 1];
                        buffer[1] = value[index + 0];
                        buffer[2] = value[index + 3];
                        buffer[3] = value[index + 2];
                        break;
                    }
                case DataFormatEnum.DCBA:
                    {
                        buffer[0] = value[index + 0];
                        buffer[1] = value[index + 1];
                        buffer[2] = value[index + 2];
                        buffer[3] = value[index + 3];
                        break;
                    }
            }
            return buffer;
        }
        /// <summary>
        /// 反转多字节的数据信息
        /// </summary>
        /// <param name="value">数据字节</param>
        /// <param name="index">起始索引，默认值为0</param>
        /// <returns>实际字节信息</returns>
        private byte[] ByteTransDataFormat8(byte[] value, int index = 0)
        {
            byte[] buffer = new byte[8];
            switch (DataFormat)
            {
                case DataFormatEnum.ABCD:
                    {
                        buffer[0] = value[index + 7];
                        buffer[1] = value[index + 6];
                        buffer[2] = value[index + 5];
                        buffer[3] = value[index + 4];
                        buffer[4] = value[index + 3];
                        buffer[5] = value[index + 2];
                        buffer[6] = value[index + 1];
                        buffer[7] = value[index + 0];
                        break;
                    }
                case DataFormatEnum.BADC:
                    {
                        buffer[0] = value[index + 6];
                        buffer[1] = value[index + 7];
                        buffer[2] = value[index + 4];
                        buffer[3] = value[index + 5];
                        buffer[4] = value[index + 2];
                        buffer[5] = value[index + 3];
                        buffer[6] = value[index + 0];
                        buffer[7] = value[index + 1];
                        break;
                    }

                case DataFormatEnum.CDAB:
                    {
                        buffer[0] = value[index + 1];
                        buffer[1] = value[index + 0];
                        buffer[2] = value[index + 3];
                        buffer[3] = value[index + 2];
                        buffer[4] = value[index + 5];
                        buffer[5] = value[index + 4];
                        buffer[6] = value[index + 7];
                        buffer[7] = value[index + 6];
                        break;
                    }
                case DataFormatEnum.DCBA:
                    {
                        buffer[0] = value[index + 0];
                        buffer[1] = value[index + 1];
                        buffer[2] = value[index + 2];
                        buffer[3] = value[index + 3];
                        buffer[4] = value[index + 4];
                        buffer[5] = value[index + 5];
                        buffer[6] = value[index + 6];
                        buffer[7] = value[index + 7];
                        break;
                    }
            }
            return buffer;
        }
        /// <summary>
        /// 将MC协议的核心报文打包成一个可以直接对PLC进行发送的原始报文
        /// </summary>
        /// <param name="mcCore">MC协议的核心报文</param>
        /// <param name="networkNumber">网络号</param>
        /// <param name="networkStationNumber">网络站号</param>
        /// <returns>原始报文信息</returns>
        private byte[] PackMcCommand(byte[] mcCore, byte networkNumber = 0, byte networkStationNumber = 0)
        {
            byte[] _PLCCommand = new byte[11 + mcCore.Length];
            _PLCCommand[0] = 0x50;                                               // 副标题
            _PLCCommand[1] = 0x00;
            _PLCCommand[2] = networkNumber;                                      // 网络号
            _PLCCommand[3] = 0xFF;                                               // PLC编号
            _PLCCommand[4] = 0xFF;                                               // 目标模块IO编号
            _PLCCommand[5] = 0x03;
            _PLCCommand[6] = networkStationNumber;                               // 目标模块站号
            _PLCCommand[7] = (byte)((_PLCCommand.Length - 9) % 256);             // 请求数据长度
            _PLCCommand[8] = (byte)((_PLCCommand.Length - 9) / 256);
            _PLCCommand[9] = 0x0A;                                               // CPU监视定时器
            _PLCCommand[10] = 0x00;
            mcCore.CopyTo(_PLCCommand, 11);

            return _PLCCommand;
        }
        /// <summary>
        /// 从PLC反馈的数据中提取出实际的数据内容，需要传入反馈数据，是否位读取
        /// </summary>
        /// <param name="response">反馈的数据内容</param>
        /// <param name="isBit">是否位读取</param>
        /// <returns>解析后的结果对象</returns>
        private OperateResult<byte[]> ExtractActualData(byte[] response, bool isBit)
        {
            if (isBit)
            {
                // 位读取
                byte[] Content = new byte[response.Length * 2];
                for (int i = 0; i < response.Length; i++)
                {
                    if ((response[i] & 0x10) == 0x10)
                    {
                        Content[i * 2 + 0] = 0x01;
                    }

                    if ((response[i] & 0x01) == 0x01)
                    {
                        Content[i * 2 + 1] = 0x01;
                    }
                }

                return OperateResult.CreateSuccessResult(Content);
            }
            else
            {
                // 字读取
                return OperateResult.CreateSuccessResult(response);
            }
        }
        /// <summary>
        /// short数组变量转化缓存数据
        /// </summary>
        /// <param name="values">等待转化的数组</param>
        /// <returns>buffer数据</returns>
        private byte[] TransByte(short[] values)
        {
            if (values == null) return null;
            byte[] buffer = new byte[values.Length * 2];
            for (int i = 0; i < values.Length; i++)
            {
                BitConverter.GetBytes(values[i]).CopyTo(buffer, 2 * i);
            }
            return buffer;
        }
        /// <summary>
        /// 从缓存中提取byte数组结果
        /// </summary>
        /// <param name="buffer">缓存数据</param>
        /// <param name="index">索引位置</param>
        /// <param name="length">读取的数组长度</param>
        /// <returns>byte数组对象</returns>
        private byte[] TransByte(byte[] buffer, int index, int length)
        {
            byte[] tmp = new byte[length];
            Array.Copy(buffer, index, tmp, 0, length);
            return tmp;
        }
        /// <summary>
        /// ushort数组变量转化缓存数据
        /// </summary>
        /// <param name="values">等待转化的数组</param>
        /// <returns>buffer数据</returns>
        private byte[] TransByte(ushort[] values)
        {
            if (values == null) return null;

            byte[] buffer = new byte[values.Length * 2];
            for (int i = 0; i < values.Length; i++)
            {
                BitConverter.GetBytes(values[i]).CopyTo(buffer, 2 * i);
            }

            return buffer;
        }
        /// <summary>
        /// int数组变量转化缓存数据
        /// </summary>
        /// <param name="values">等待转化的数组</param>
        /// <returns>buffer数据</returns>
        private byte[] TransByte(int[] values)
        {
            if (values == null) return null;

            byte[] buffer = new byte[values.Length * 4];
            for (int i = 0; i < values.Length; i++)
            {
                ByteTransDataFormat4(BitConverter.GetBytes(values[i])).CopyTo(buffer, 4 * i);
            }

            return buffer;
        }
        /// <summary>
        /// uint数组变量转化缓存数据
        /// </summary>
        /// <param name="values">等待转化的数组</param>
        /// <returns>buffer数据</returns>
        private byte[] TransByte(uint[] values)
        {
            if (values == null) return null;

            byte[] buffer = new byte[values.Length * 4];
            for (int i = 0; i < values.Length; i++)
            {
                ByteTransDataFormat4(BitConverter.GetBytes(values[i])).CopyTo(buffer, 4 * i);
            }

            return buffer;
        }
        /// <summary>
        /// long数组变量转化缓存数据
        /// </summary>
        /// <param name="values">等待转化的数组</param>
        /// <returns>buffer数据</returns>
        private byte[] TransByte(long[] values)
        {
            if (values == null) return null;

            byte[] buffer = new byte[values.Length * 8];
            for (int i = 0; i < values.Length; i++)
            {
                ByteTransDataFormat8(BitConverter.GetBytes(values[i])).CopyTo(buffer, 8 * i);
            }

            return buffer;
        }
        /// <summary>
        /// ulong数组变量转化缓存数据
        /// </summary>
        /// <param name="values">等待转化的数组</param>
        /// <returns>buffer数据</returns>
        private byte[] TransByte(ulong[] values)
        {
            if (values == null) return null;

            byte[] buffer = new byte[values.Length * 8];
            for (int i = 0; i < values.Length; i++)
            {
                ByteTransDataFormat8(BitConverter.GetBytes(values[i])).CopyTo(buffer, 8 * i);
            }

            return buffer;
        }
        /// <summary>
        /// float数组变量转化缓存数据
        /// </summary>
        /// <param name="values">等待转化的数组</param>
        /// <returns>buffer数据</returns>
        private byte[] TransByte(float[] values)
        {
            if (values == null) return null;

            byte[] buffer = new byte[values.Length * 4];
            for (int i = 0; i < values.Length; i++)
            {
                ByteTransDataFormat4(BitConverter.GetBytes(values[i])).CopyTo(buffer, 4 * i);
            }

            return buffer;
        }
        /// <summary>
        /// double数组变量转化缓存数据
        /// </summary>
        /// <param name="values">等待转化的数组</param>
        /// <returns>buffer数据</returns>
        private byte[] TransByte(double[] values)
        {
            if (values == null) return null;

            byte[] buffer = new byte[values.Length * 8];
            for (int i = 0; i < values.Length; i++)
            {
                ByteTransDataFormat8(BitConverter.GetBytes(values[i])).CopyTo(buffer, 8 * i);
            }

            return buffer;
        }
        /// <summary>
        /// 使用指定的编码字符串转化缓存数据
        /// </summary>
        /// <param name="value">等待转化的数据</param>
        /// <param name="encoding">字符串的编码方式</param>
        /// <returns>buffer数据</returns>
        private byte[] TransByte(string value, Encoding encoding)
        {
            if (value == null) return null;

            return encoding.GetBytes(value);
        }
        #endregion Common method Helper


        #region Write Bool
        /// <summary>
        /// 向PLC中位软元件写入bool数组，返回值说明，比如你写入M100,values[0]对应M100
        /// </summary>
        /// <param name="address">要写入的数据地址</param>
        /// <param name="values">要写入的实际数据，可以指定任意的长度</param>
        /// <returns>返回写入结果</returns>
        public OperateResult Write(string address, bool[] values)
        {
            // 分析地址
            OperateResult<McAddressData> addressResult = McAnalysisAddress(address, 0);
            if (!addressResult.IsSuccess) return addressResult;

            byte[] coreResult = MelsecHelper.BuildWriteBitCoreCommand(addressResult.Content, values);

            // 核心交互
            OperateResult<byte[]> read = ReadFromCoreServer(PackMcCommand(coreResult, NetworkNumber, NetworkStationNumber));
            if (!read.IsSuccess) return read;

            // 错误码校验
            ushort ErrorCode = BitConverter.ToUInt16(read.Content, 9);
            if (ErrorCode != 0) return new OperateResult<byte[]>(ErrorCode, StringResources.Language.MelsecPleaseReferToManulDocument);

            // 成功
            return OperateResult.CreateSuccessResult();
        }
        public OperateResult Write(string address, bool value)
        {
            return Write(address, new bool[1] { value });
        }
        #endregion Write Bool

        #region Write short
        /// <summary>
        /// 向设备中写入short数组，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="values">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, short[] values)
        {
            return Write(address, TransByte(values));
        }

        /// <summary>
        /// 向设备中写入short数据，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, short value)
        {
            return Write(address, new short[1] { value });
        }
        #endregion Write short

        #region Write ushort
        /// <summary>
        /// 向设备中写入ushort数组，返回是否写入成功
        /// </summary>
        /// <param name="address">要写入的数据地址</param>
        /// <param name="values">要写入的实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, ushort[] values)
        {
            return Write(address, TransByte(values));
        }


        /// <summary>
        /// 向设备中写入ushort数据，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, ushort value)
        {
            return Write(address, new ushort[] { value });
        }
        #endregion Write ushort

        #region Write int
        /// <summary>
        /// 向设备中写入int数组，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="values">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, int[] values)
        {
            return Write(address, TransByte(values));
        }

        /// <summary>
        /// 向设备中写入int数据，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, int value)
        {
            return Write(address, new int[] { value });
        }
        #endregion Write int

        #region Write uint
        /// <summary>
        /// 向设备中写入uint数组，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="values">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, uint[] values)
        {
            return Write(address, TransByte(values));
        }

        /// <summary>
        /// 向设备中写入uint数据，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, uint value)
        {
            return Write(address, new uint[] { value });
        }
        #endregion Write uint

        #region Write long
        /// <summary>
        /// 向设备中写入long数组，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="values">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, long[] values)
        {
            return Write(address, TransByte(values));
        }

        /// <summary>
        /// 向设备中写入long数据，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, long value)
        {
            return Write(address, new long[] { value });
        }
        #endregion Write long

        #region Write ulong
        /// <summary>
        /// 向P设备中写入ulong数组，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="values">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, ulong[] values)
        {
            return Write(address, TransByte(values));
        }

        /// <summary>
        /// 向设备中写入ulong数据，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, ulong value)
        {
            return Write(address, new ulong[] { value });
        }
        #endregion Write ulong

        #region Write float
        /// <summary>
        /// 向设备中写入float数组，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="values">实际数据</param>
        /// <returns>返回写入结果</returns>
        public OperateResult Write(string address, float[] values)
        {
            return Write(address, TransByte(values));
        }

        /// <summary>
        /// 向设备中写入float数据，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">实际数据</param>
        /// <returns>返回写入结果</returns>
        public OperateResult Write(string address, float value)
        {
            return Write(address, new float[] { value });
        }
        #endregion Write float

        #region Write double
        /// <summary>
        /// 向设备中写入double数组，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="values">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, double[] values)
        {
            return Write(address, TransByte(values));
        }

        /// <summary>
        /// 向设备中写入double数据，返回是否写入成功
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">实际数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, double value)
        {
            return Write(address, new double[] { value });
        }
        #endregion Write double

        #region Write string
        /// <summary>
        /// 向设备中写入字符串，编码格式为ASCII
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">字符串数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, string value)
        {
            return Write(address, value, Encoding.ASCII);
        }

        /// <summary>
        /// 向设备中写入指定编码的字符串
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">字符串数据</param>
        /// <param name="encoding">字节编码</param>
        /// <returns>是否写入成功的结果对象</returns>
        public OperateResult Write(string address, string value, Encoding encoding)
        {
            byte[] temp = TransByte(value, encoding);
            if (WordLength == 1) temp = SoftBasic.ArrayExpandToLengthEven(temp);
            return Write(address, temp);
        }

        /// <summary>
        /// 向设备中写入指定长度的字符串,超出截断，不够补0，编码格式为ASCII
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">字符串数据</param>
        /// <param name="length">指定的字符串长度，必须大于0</param>
        /// <returns>是否写入成功的结果对象 -> Whether to write a successful result object</returns>
        public OperateResult Write(string address, string value, int length)
        {
            return Write(address, value, length, Encoding.ASCII);
        }

        /// <summary>
        /// 向设备中写入指定长度并且指定编码的字符串,超出截断，不够补0
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">字符串数据</param>
        /// <param name="length">指定的长度，按照转换后的字节计算</param>
        /// <param name="encoding">字符编码</param>
        /// <returns>是否写入成功的结果对象 -> Whether to write a successful result object</returns>
        public OperateResult Write(string address, string value, int length, Encoding encoding)
        {
            byte[] temp = TransByte(value, encoding);
            if (WordLength == 1) temp = SoftBasic.ArrayExpandToLengthEven(temp);
            temp = SoftBasic.ArrayExpandToLength(temp, length);
            return Write(address, temp);
        }

        /// <summary>
        /// 向设备中写入字符串，编码格式为Unicode
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">字符串数据</param>
        /// <returns>是否写入成功的结果对象</returns>
        private OperateResult WriteUnicodeString(string address, string value)
        {
            byte[] temp = TransByte(value, Encoding.Unicode);
            return Write(address, temp);
        }

        /// <summary>
        /// 向设备中写入指定长度的字符串,超出截断，不够补0，编码格式为Unicode
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="value">字符串数据</param>
        /// <param name="length">指定的字符串长度，必须大于0</param>
        /// <returns>是否写入成功的结果对象 -> Whether to write a successful result object</returns>
        private OperateResult WriteUnicodeString(string address, string value, int length)
        {
            byte[] temp = TransByte(value, Encoding.Unicode);
            temp = SoftBasic.ArrayExpandToLength(temp, length * 2);
            return Write(address, temp);
        }
        #endregion Write string

        #region Write byte array 向PLC写入数据 核心代码
        /// <summary>
        /// 向PLC写入数据，数据格式为原始的字节类型
        /// </summary>
        /// <param name="address">初始地址</param>
        /// <param name="value">原始的字节数据</param>
        /// <returns>结果</returns>
        public OperateResult Write(string address, byte[] value)
        {
            // 分析地址
            OperateResult<McAddressData> addressResult = McAnalysisAddress(address, 0);
            if (!addressResult.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(addressResult);

            return WriteAddressData(addressResult.Content, value);
        }
        public OperateResult Write(string address, byte value)
        {
            return Write(address, new byte[] { value });
        }

        private OperateResult WriteAddressData(McAddressData addressData, byte[] value)
        {
            // 创建核心报文
            byte[] coreResult = MelsecHelper.BuildWriteWordCoreCommand(addressData, value);

            // 核心交互
            OperateResult<byte[]> read = ReadFromCoreServer(PackMcCommand(coreResult, NetworkNumber, NetworkStationNumber));
            if (!read.IsSuccess) return read;

            // 错误码校验
            ushort ErrorCode = BitConverter.ToUInt16(read.Content, 9);
            if (ErrorCode != 0) return new OperateResult<byte[]>(ErrorCode, StringResources.Language.MelsecPleaseReferToManulDocument);

            // 成功
            return OperateResult.CreateSuccessResult();
        }
        #endregion Write byte array 向PLC写入数据 核心代码

        #endregion Read Write Support
    }

    /// <summary>
    /// 应用于多字节数据的解析或是生成格式
    /// </summary>
    public enum DataFormatEnum
    {
        /// <summary>
        /// 按照顺序排序
        /// </summary>
        ABCD = 0,
        /// <summary>
        /// 按照单字反转
        /// </summary>
        BADC = 1,
        /// <summary>
        /// 按照双字反转
        /// </summary>
        CDAB = 2,
        /// <summary>
        /// 按照倒序排序
        /// </summary>
        DCBA = 3,
    }
}
