CoilRegister.cs
3.0 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
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);
}
}
}
}