OPCHelp.cs
11.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
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
using HHECS.Bll;
using HHECS.Model;
using OPCAutomation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HHECS.OPC
{
public class OPCHelp
{
string PCIP;
public OPCServer s7 = new OPCServer();
public OPCGroup s7Group;
/// <summary>
/// PC站IP地址
/// </summary>
/// <param name="OPCIP"></param>
public OPCHelp(string OPCIP)
{
PCIP = OPCIP;
}
/// <summary>
/// 打开OPC连接
/// </summary>
/// <returns></returns>
public bool OpenConn()
{
try
{
s7.Connect("OPC.SimaticNET", PCIP);
if (s7.ServerState == (int)OPCServerState.OPCRunning)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 关闭连接
/// </summary>
/// <returns></returns>
public bool CloseConn()
{
try
{
s7.Disconnect();
if (s7.ServerState == (int)OPCServerState.OPCDisconnected)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 获取OPCserver当前状态,TRUE:正在运行,false:连接关闭
/// </summary>
/// <returns></returns>
public bool GetConnStatus()
{
return s7.ServerState == (int)OPCServerState.OPCRunning ? true : false;
}
/// <summary>
/// 创建组
/// </summary>
public bool CreateGroup(string name)
{
try
{
s7Group = s7.OPCGroups.Add(name);
SetGroupProperty();
}
catch (Exception)
{
//MessageBox.Show("创建组出现错误:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
return true;
}
/// <summary>
/// 设置组属性
/// </summary>
private void SetGroupProperty()
{
s7.OPCGroups.DefaultGroupIsActive = Convert.ToBoolean(true);
s7.OPCGroups.DefaultGroupDeadband = Convert.ToInt32(0);
s7Group.UpdateRate = Convert.ToInt32(250);// 刷新率 ms
s7Group.IsActive = Convert.ToBoolean(true); //设置该组为激活状态
s7Group.IsSubscribed = Convert.ToBoolean(false);//设置该组数据为后台刷新
}
/// <summary>
/// 添加项目地址
/// </summary>
public int AddAddr(string Addr, int ClientHandle)
{
int returnvalue = 0;
if (!string.IsNullOrEmpty(Addr))
{
try
{
OPCItem tempItem = s7Group.OPCItems.AddItem(Addr, ClientHandle);
//ServerHandle,这是一个重要的东西,个人理解为组中的项的索引,读取程序根据这个索引找到db块并进行读写操作。
//程序中应对ServerHandle与实际的变量地址已经这个变量地址所代表的意义进行一个映射。
returnvalue = tempItem.ServerHandle;
}
catch (Exception err)
{
}
}
return returnvalue;
}
/// <summary>
/// 读取数据,成功返回值,失败返回null
/// 按照 OPC 规范,数组始终以索引 1 开始。
/// </summary>
public Array ReadData(int[] handle)
{
try
{
int count = handle.Length;
int[] temp = new int[count + 1];
temp[0] = 0;
for (int i = 1; i < temp.Length; i++)
{
temp[i] = handle[i - 1];
}
Array serverHandles = (Array)temp;
Array values;
Array Errors;
object Qualities;
object TimeStamps;
//OPCAutomation.OPCDataSource.OPCCache;
s7Group.SyncRead(1, count, ref serverHandles, out values, out Errors, out Qualities, out TimeStamps);
return values;
}
catch (Exception err)
{
return null;
}
}
/// <summary>
/// 写入数据,handle,索引值数组,value对应值数组
/// 按照 OPC 规范,数组始终以索引 1 开始。
/// </summary>
public bool WriteData(int[] handle, object[] value)
{
try
{
int[] temp = new int[handle.Length + 1];
temp[0] = 0;
object[] temp1 = new object[handle.Length + 1];
temp1[0] = "";
for (int i = 1; i < temp.Length; i++)
{
temp[i] = handle[i - 1];
temp1[i] = value[i - 1];
}
Array serverHandles = (Array)temp;
Array values = (Array)temp1;
Array Errors;
//OPCAutomation.OPCDataSource.OPCCache;
s7Group.SyncWrite(handle.Length, ref serverHandles, ref values, out Errors);
return true;
}
catch (Exception)
{
return false;
}
}
#region 数据互转
/// <summary>
/// 数据类型转换WCS-->PLC
/// </summary>
/// <param name="type"></param>
/// <param name="v"></param>
/// <returns></returns>
private BllResult TansforWCSDataToAddressData(string type, string data)
{
try
{
object obj = null;
switch (type)
{
case "BYTE": obj = Convert.ToUInt16(data); break;
case "DWORD": obj = Convert.ToUInt32(data); break;
case "BOOL": obj = Convert.ToBoolean(data); break;
case "WORD": obj = Convert.ToUInt16(data); break;
case "INT": obj = Convert.ToInt16(data); break;
case "DINT": obj = Convert.ToInt32(data); break;
case "CHAR": obj = ConverHelper.StringToASCII(data); break;
default:
obj = data;
break;
}
return BllResultFactory.Sucess(obj, "成功");
}
catch (Exception ex)
{
return BllResultFactory.Error(null, "WCS到PLC数据转换出现异常,值:" + data + " 目标类型:" + type + " 异常:" + ex.ToString());
}
}
/// <summary>
/// 数据类型转换PLC-->WCS
/// </summary>
/// <param name="type"></param>
/// <param name="data"></param>
/// <returns></returns>
private BllResult<String> TransforAddressDataToWCSData(string type, object data)
{
string str;
try
{
switch (type)
{
case "BYTE":
case "DWORD":
case "INT":
case "DINT":
case "BOOL":
case "WORD": str = data.ToString(); break;
case "CHAR": str = ConverHelper.ASCIIToString((short[])data).Trim().Replace("$03", "").Replace("\u0003", "").Replace("\0", ""); break;
default:
str = data.ToString();
break;
}
return BllResultFactory.Sucess<string>(str, "成功");
}
catch (Exception ex)
{
return BllResultFactory.Error<string>(null, "PLC到WCS数据转换出现异常,值:" + data + " 目标类型:" + type + " 异常:" + ex.ToString());
}
}
#endregion
/// <summary>
/// 添加地址
/// </summary>
/// <param name="props"></param>
public void AddOPCItems(List<EquipmentProp> props)
{
for (int i = 0; i < props.Count; i++)
{
var temp = props[i];
temp.ServerHandle = this.AddAddr(temp.Address, i);
}
}
/// <summary>
/// 读取特定地址
/// </summary>
/// <param name="deviceAddressEntities"></param>
public BllResult ReadAddress(List<EquipmentProp> props)
{
int j = 0;
try
{
if (this == null || this.GetConnStatus() == false || props == null || props.Count == 0)
{
//AddLogToUI("地址读取失败,请检查通讯连接", 2);
return BllResultFactory.Error(null, "地址读取失败,请检查通讯连接");
}
int[] handles = props.Select(t => t.ServerHandle).ToArray();
var array = this.ReadData(handles);
for (int i = 0; i < props.Count; i++)
{
j = i;
var result = TransforAddressDataToWCSData(props[i].EquipmentTypePropTemplate.DataType, array.GetValue(i + 1));
if (!result.Success)
{
return BllResultFactory.Error(null, "转换PLC数据到WCS类型错误,值:" + array.GetValue(i + 1) + " 类型:" + props[i].EquipmentTypePropTemplate.DataType);
}
props[i].Value = result.Data;
}
}
catch (Exception ex)
{
}
return BllResultFactory.Sucess(null, "成功");
}
/// <summary>
/// 写入PLC数据
/// </summary>
/// <param name="deviceAddressEntities"></param>
/// <returns></returns>
public BllResult WriteAddress(List<EquipmentProp> props)
{
if (this == null || this.GetConnStatus() == false || props == null || props.Count == 0)
{
return BllResultFactory.Error(null, "地址读取失败,请检查通讯连接");
}
var serverHandel = props.Select(t => t.ServerHandle).ToArray();
object[] values = new object[serverHandel.Count<int>()];
for (int i = 0; i < props.Count; i++)
{
var result = TansforWCSDataToAddressData(props[i].EquipmentTypePropTemplate.DataType, props[i].Value);
if (!result.Success)
{
return BllResultFactory.Error(null, $"转换WCS数据到PLC类型错误,属性名:{props[i].EquipmentTypePropTemplateCode},设备编码:{props[i].Equipment.Code},值:" + props[i].Value + " 类型:" + props[i].EquipmentTypePropTemplate.DataType);
}
values[i] = result.Data;
}
if (this.WriteData(serverHandel, values))
{
return BllResultFactory.Sucess(null, "成功");
}
else
{
return BllResultFactory.Error(null, "写入失败!");
}
}
}
}