CoilRegister.cs 3.0 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DL.Com.Protocol.Modbus
{
    /// <summary>
    /// 线圈寄存器:可读可写。
    /// 支持的功能码:
    /// 0x01:读线圈
    /// 0x05:写线圈
    /// 0x0F:写多个线圈
    /// </summary>
    public class CoilRegister : Register
    {
        public CoilRegister() : base()
        {
            FunctionCodes.Add(RegisterFunction.Read, 0x01);
            FunctionCodes.Add(RegisterFunction.WriteSingle, 0x05);
            FunctionCodes.Add(RegisterFunction.WriteMultiple, 0x0F);
        }
        /// <summary>
        /// PLC地址
        /// </summary>
        public new string PLCAddress
        {
            get { return $"0{FrameStruct.PDU.Data.Addr.GetIntValue()}"; }
        }
        /// <summary>
        /// 解析写单个线圈
        /// </summary>
        /// <returns>写入成功</returns>
        protected override bool ParseWriteSingle(byte[] respoonse)
        {
            if (GetResponseResult(respoonse, out byte[] data))
            {
                //数据部分,发送与接收一致
                byte[] senddata = FrameStruct.PDU.Data.ToBytes();
                if (data != null && data.Length != senddata.Length)
                    return false;
                for (int i = 0; i < senddata.Length; i++)
                {
                    if (senddata[i] != data[i])
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
        /// <summary>
        /// 解析写多个线圈
        /// </summary>
        /// <returns>写入成功/returns>
        protected override bool ParseWriteMultiple(byte[] response)
        {
            if (GetResponseResult(response, out byte[] data))
            {
                byte[] senddata = FrameStruct.PDU.Data.AddrValueToBytes();
                if (data != null && data.Length != senddata.Length)
                    return false;
                for (int i = 0; i < senddata.Length; i++)
                {
                    if (senddata[i] != data[i])
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }

        protected override void SetParamPDU(CmdByte cmd)
        {
            if (cmd.Function.Equals(RegisterFunction.WriteSingle))
            {
                SetPDU(cmd.Function, cmd.StartAddr, cmd.Count.Equals(new Byte2 { ByteH = 0x00, ByteL = 0x00 }) ? cmd.Count : new Byte2 { ByteH = 0xFF, ByteL = 0x00 }, cmd.ByteLength, cmd.ValuesOfMultiple);
            }
            else if (cmd.Function.Equals(RegisterFunction.WriteMultiple))
            {
                SetPDU(cmd.Function, cmd.StartAddr, cmd.Count, cmd.ByteLength, cmd.ValuesOfMultiple);
            }
            else
            {
                SetPDU(RegisterFunction.Read, cmd.StartAddr, cmd.Count);
            }
        }

    }

}