HoldingRegister.cs
3.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DL.Com.Protocol.Modbus
{
/// <summary>
/// 保持寄存器
/// 0x03
/// </summary>
public class HoldingRegister : Register
{
public HoldingRegister() : base()
{
FunctionCodes.Add(RegisterFunction.Read, 0x03);
FunctionCodes.Add(RegisterFunction.WriteSingle, 0x06);
FunctionCodes.Add(RegisterFunction.WriteMultiple, 0x10);
}
/// <summary>
/// PLC地址
/// </summary>
public new string PLCAddress
{
get { return $"4{FrameStruct.PDU.Data.Addr.GetIntValue()}"; }
}
public override byte[] GetRequestBytes(RegisterFunction func, ushort startAddr, ushort countOrValue,byte equipAddr=1, ushort[] ValuesOfMultiple = null)
{
CmdByte cmdByte = new CmdByte();
cmdByte.StartAddr = Byte2.GetStru2Byte(startAddr);
cmdByte.Function = func;
cmdByte.Count = Byte2.GetStru2Byte(countOrValue);
if (func.Equals(RegisterFunction.WriteMultiple))
{
if (ValuesOfMultiple == null)
return null;
List<byte> values = new List<byte>();
foreach (var item in ValuesOfMultiple)
{
values.AddRange(Byte2.GetStru2Byte(item).ToBytes());
}
cmdByte.ByteLength = (byte)(countOrValue * 2);
cmdByte.ValuesOfMultiple = values.ToArray();
}
SetMBAP(_serialnum, equipAddr);
SetParamPDU(cmdByte);
return DataFrame;
}
protected override void SetParamPDU(CmdByte cmdByte)
{
if (cmdByte.Function.Equals(RegisterFunction.WriteSingle))
{
SetPDU(cmdByte.Function, cmdByte.StartAddr, cmdByte.Count, cmdByte.ByteLength, cmdByte.ValuesOfMultiple);
}
else if (cmdByte.Function.Equals(RegisterFunction.WriteMultiple))
{
SetPDU(cmdByte.Function, cmdByte.StartAddr, cmdByte.Count, cmdByte.ByteLength, cmdByte.ValuesOfMultiple);
}
else
SetPDU(RegisterFunction.Read, cmdByte.StartAddr, cmdByte.Count);
}
protected override bool ParseWriteSingle(byte[] response)
{
if (GetResponseResult(response, 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;
}
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;
}
}
}