SiemensS7Communication.cs
15.2 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
using DataAcquisition.Common.Enums;
using DataAcquisition.Common.Utils;
using DataAcquisition.Models;
using HslCommunication;
using HslCommunication.Core;
using HslCommunication.Profinet.Siemens;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
namespace DataAcquisition.Common.Communications
{
/// <summary>
/// 西门子通信
/// </summary>
public class SiemensS7Communication : ICommunication
{
public readonly SiemensS7Net Siemens = null!;
private readonly SystemLog systemLog = SystemLog.Instance;
private readonly ReverseBytesTransform reverseBytesTransform = new();
public string IpAddress => Siemens.IpAddress;
public int CommunicationId { get; set; }
private SiemensS7Communication() { }
public SiemensS7Communication(int communicationId, SiemensPLCS siemens, string ipAddress) : this()
{
CommunicationId = communicationId;
Siemens = new SiemensS7Net(siemens, ipAddress);
Siemens.SetPersistentConnection();
}
public OperateResult ConnectServer() => Siemens.ConnectServer();
public OperateResult ConnectClose() => Siemens.ConnectClose();
public void Read(IEnumerable<EquipmentProperty> equipmentProperties)
{
try
{
var stopwatch = Stopwatch.StartNew();
//DB地址批量读取
if (equipmentProperties.All(x => x.DataAddress.StartsWith("DB", StringComparison.OrdinalIgnoreCase)))
{
var regex = new Regex("[0-9]+");
foreach (var item in equipmentProperties.GroupBy(x => x.DataAddress.Split('.').First()))
{
var amountItems = item.Select(x => Convert.ToInt32(regex.Match(x.DataAddress.Split('.')[1]).Value));
var amountStart = amountItems.Min();
var amountEnd = amountItems.Max();
var lastItemDataType = item.MaxBy(x => Convert.ToInt32(regex.Match(x.DataAddress.Split('.')[1]).Value))!.DataType;
//最后一个地址占用的Byte数量,Word类型需要加2,Real需要加4
var lastByteAmount = lastItemDataType switch
{
DataTypeConst.Bool => 1,
DataTypeConst.UInt32 => 4,
DataTypeConst.UInt16 => 2,
DataTypeConst.Int16 => 2,
DataTypeConst.Int32 => 4,
//DataTypeConst.String => throw new NotImplementedException(),
DataTypeConst.Real => 4,
_ => 1
};
var amount = (ushort)(amountEnd - amountStart + lastByteAmount);
var multiReadResult = Siemens.Read($"{item.Key}.{amountStart}", amount);
if (!multiReadResult.IsSuccess)
{
throw new Exception(multiReadResult.Message);
}
//根据数据类型按byte转换,不同数据类型字节数不同
foreach (var prop in item)
{
_ = int.TryParse(regex.Match(prop.DataAddress.Split('.')[1]).Value, out int currentAmountEnd);
_ = int.TryParse(regex.Match(prop.DataAddress.Split('.').Skip(2).FirstOrDefault() ?? "0").Value, out int bitIndex);
var index = currentAmountEnd - amountStart;
prop.Value = prop.DataType switch
{
DataTypeConst.Byte => reverseBytesTransform.TransInt32(multiReadResult.Content, index).ToString(),
DataTypeConst.Bool => Convert.ToBoolean(multiReadResult.Content[index] & (1 << bitIndex)).ToString(),
DataTypeConst.UInt32 => reverseBytesTransform.TransUInt32(multiReadResult.Content, index).ToString(),
DataTypeConst.UInt16 => reverseBytesTransform.TransUInt16(multiReadResult.Content, index).ToString(),
DataTypeConst.Int16 => reverseBytesTransform.TransInt16(multiReadResult.Content, index).ToString(),
DataTypeConst.Int32 => reverseBytesTransform.TransInt32(multiReadResult.Content, index).ToString(),
//DataTypeConst.String => reverseBytesTransform.TransString(multiReadResult.Content, index, prop.Length, Encoding.ASCII).Replace("\u0003", "").Trim(),
DataTypeConst.Real => reverseBytesTransform.TransSingle(multiReadResult.Content, index).ToString(),
_ => string.Empty
};
prop.UpdateTime = DateTime.Now;
}
}
}
else
{
foreach (var item in equipmentProperties)
{
switch (item.DataType)
{
case DataTypeConst.Bool:
var boolDataResult = Siemens.ReadBool(item.DataAddress);
if (!boolDataResult.IsSuccess)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{boolDataResult.Message}");
item.Value = string.Empty;
return;
}
item.Value = boolDataResult.Content.ToString();
break;
case DataTypeConst.Byte:
var byteDataResult = Siemens.ReadByte(item.DataAddress);
if (!byteDataResult.IsSuccess)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{byteDataResult.Message}");
item.Value = string.Empty;
return;
}
item.Value = byteDataResult.Content.ToString();
break;
case DataTypeConst.Int16:
var shortDataResult = Siemens.ReadInt16(item.DataAddress);
if (!shortDataResult.IsSuccess)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{shortDataResult.Message}");
item.Value = string.Empty;
return;
}
item.Value = shortDataResult.Content.ToString();
break;
case DataTypeConst.UInt16:
var ushortDataResult = Siemens.ReadUInt16(item.DataAddress);
if (!ushortDataResult.IsSuccess)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{ushortDataResult.Message}");
item.Value = string.Empty;
return;
}
item.Value = ushortDataResult.Content.ToString();
break;
case DataTypeConst.Int32:
var intDataResult = Siemens.ReadInt32(item.DataAddress);
if (!intDataResult.IsSuccess)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{intDataResult.Message}");
item.Value = string.Empty;
return;
}
item.Value = intDataResult.Content.ToString();
break;
case DataTypeConst.UInt32:
var uintDataResult = Siemens.ReadUInt32(item.DataAddress);
if (!uintDataResult.IsSuccess)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{uintDataResult.Message}");
item.Value = string.Empty;
return;
}
item.Value = uintDataResult.Content.ToString();
break;
case DataTypeConst.Int64:
var longDataResult = Siemens.ReadInt64(item.DataAddress);
if (!longDataResult.IsSuccess)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{longDataResult.Message}");
item.Value = string.Empty;
return;
}
item.Value = longDataResult.Content.ToString();
break;
case DataTypeConst.UInt64:
var ulongDataResult = Siemens.ReadUInt64(item.DataAddress);
if (!ulongDataResult.IsSuccess)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{ulongDataResult.Message}");
item.Value = string.Empty;
return;
}
item.Value = string.Empty;
break;
case DataTypeConst.Real:
var floatDataResult = Siemens.ReadFloat(item.DataAddress);
if (!floatDataResult.IsSuccess)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{floatDataResult.Message}");
item.Value = string.Empty;
return;
}
item.Value = floatDataResult.Content.ToString();
break;
//case "double":
// var doubleDataResult = Siemens.ReadDouble(item.DataAddress);
// if (!doubleDataResult.IsSuccess)
// {
// item.Value = string.Empty;
// systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{doubleDataResult.Message}");
// return;
// }
// item.Value = doubleDataResult.Content.ToString();
// break;
case DataTypeConst.String:
var stringDataResult = Siemens.ReadString(item.DataAddress);
if (!stringDataResult.IsSuccess)
{
item.Value = string.Empty;
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}出现异常:{stringDataResult.Message}");
return;
}
item.Value = stringDataResult.Content.ToString();
break;
default:
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]地址{item.DataAddress}失败:不支持“{item.DataType}”数据类型");
return;
}
item.UpdateTime = DateTime.Now;
}
}
stopwatch.Stop();
systemLog.LogInfo($"读取PLC[{equipmentProperties.FirstOrDefault()?.Equipment.CommunicationConfig?.IpAddress}]地址数量:{equipmentProperties.Count()},耗时:{stopwatch.Elapsed}");
}
catch (Exception ex)
{
systemLog.LogError($"读取PLC[{Siemens.IpAddress}]数据出现异常:{ex.Message}");
}
}
public void Read(EquipmentProperty equipmentProperty)
{
Read([equipmentProperty]);
}
public void Write(IEnumerable<EquipmentProperty> equipmentProperties)
{
try
{
var result = new OperateResult();
var stopwatch = Stopwatch.StartNew();
foreach (var item in equipmentProperties)
{
if (item.DataType == DataTypeConst.Bool)
{
_ = bool.TryParse(item.Value, out bool val);
result = Siemens.Write(item.DataAddress, val);
}
else if (item.DataType == DataTypeConst.Int16)
{
_ = ushort.TryParse(item.Value, out ushort val);
result = Siemens.Write(item.DataAddress, val);
}
else if (item.DataType == DataTypeConst.Real)
{
_ = float.TryParse(item.Value, out var val);
result = Siemens.Write(item.DataAddress, val);
}
else
{
var bytes = Encoding.Default.GetBytes(item.Value ?? string.Empty);
result = Siemens.Write(item.DataAddress, bytes);
}
if (!result.IsSuccess)
{
systemLog.LogError($"写入PLC[{Siemens.IpAddress}]_{item.DataAddress}地址数据失败:{result.Message}");
return;
}
}
stopwatch.Stop();
systemLog.LogSuccess($"写入PLC[{Siemens.IpAddress}]地址数据成功,数量{equipmentProperties.Count()},耗时:{stopwatch.Elapsed}");
}
catch (Exception ex)
{
systemLog.LogError($"写入PLC[{Siemens.IpAddress}]数据出现异常:{ex.Message}");
}
}
public void Write(EquipmentProperty equipmentProperty)
{
Write([equipmentProperty]);
}
}
}