나만의 Siemens PLC Class 작성
Siemens PLC Class
바로 실무에 적용 가능한 Simens PLC Class
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
using S7.Net;
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
namespace PNEProxy.PLC
{
public enum CpuType { S7200, Logo0BA8, S7200Smart, S7300 = 10, S7400 = 20, S71200 = 30, S71500 = 40 }
public enum DataType { Counter = 28, Timer = 29, Input = 129, Output = 130, Memory = 131, DataBlock = 132 }
public enum VarType { Bit, Byte, Word, DWord, Int, DInt, Real, LReal, String, S7String, S7WString, Timer, Counter, DateTime, DateTimeLong }
public enum ErrorCode { NoError, WrongCPU_Type, ConnectionError, IPAddressNotAvailable, WrongVarFormat = 10, WrongNumberReceivedBytes = 11, SendDataError = 20, ReadDataError = 30, WriteDataError = 50 }
public class SiemensPLC
{
public ErrorCode LastErrorCode { get; set; }
public string LastErrorString { get; set; }
private Plc mPlc;
private S7.Net.CpuType mCpuType;
private string mIP;
private short mRack;
private short mSlot;
public SiemensPLC() { }
/// <summary>
/// PLC 연결을 초기화합니다.
/// </summary>
public bool Initialize(CpuType cpuType, string ip, short rack, short slot, int port = 102)
{
try
{
mCpuType = (S7.Net.CpuType)Enum.Parse(typeof(S7.Net.CpuType), cpuType.ToString());
mIP = ip;
mRack = rack;
mSlot = slot;
mPlc = new Plc(mCpuType, mIP, port, mRack, mSlot)
{
ReadTimeout = 1000,
WriteTimeout = 1000
};
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
}
return false;
}
/// <summary>
/// PLC에 비동기 연결을 시도합니다.
/// </summary>
public async Task<ErrorCode> Open()
{
try
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
await Task.WhenAny(mPlc?.OpenAsync(cts.Token), Task.Delay(TimeSpan.FromSeconds(1)));
return mPlc?.IsConnected == true ? ErrorCode.NoError : ErrorCode.ConnectionError;
}
catch (Exception e)
{
Console.WriteLine(e);
return ErrorCode.ConnectionError;
}
}
/// <summary>
/// PLC 연결을 종료합니다.
/// </summary>
public bool Close()
{
mPlc?.Close();
return true;
}
/// <summary>
/// 현재 PLC와의 연결 상태를 반환합니다.
/// </summary>
public bool? IsConnected() => mPlc?.IsConnected;
/// <summary>
/// PLC IP로 Ping을 보내 연결 가능 여부를 확인합니다.
/// </summary>
public bool IsPingSuccessful()
{
try
{
Ping ping = new Ping();
var reply = ping.Send(mIP, 500);
if (reply?.Status == IPStatus.Success)
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
}
if (IsConnected() == true) Close();
return false;
}
/// <summary>
/// PLC에서 변수를 읽습니다. (제네릭 지원)
/// </summary>
public T Read<T>(string variable)
{
try
{
var result = mPlc?.Read(variable);
return (T)Convert.ChangeType(result, typeof(T));
}
catch (Exception e)
{
Console.WriteLine(e);
return default;
}
}
/// <summary>
/// PLC에서 여러 바이트를 읽습니다.
/// </summary>
public byte[] ReadBytes(DataType dataType, int db, int startByteAdr, int count)
{
try
{
return mPlc?.ReadBytes((S7.Net.DataType)Enum.Parse(typeof(S7.Net.DataType), dataType.ToString()), db, startByteAdr, count);
}
catch (Exception e)
{
Console.WriteLine(e);
return Array.Empty<byte>();
}
}
/// <summary>
/// PLC 데이터 블록을 클래스 객체로 읽습니다.
/// </summary>
public T ReadClass<T>(int db, int startByteAdr = 0) where T : class
{
try
{
return mPlc?.ReadClass<T>(db, startByteAdr);
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
/// <summary>
/// PLC에 데이터를 씁니다.
/// </summary>
public ErrorCode Write(string variable, object value, VarType varType = VarType.String)
{
try
{
var typedValue = ConvertToTargetType((S7.Net.VarType)Enum.Parse(typeof(S7.Net.VarType), varType.ToString()), value);
mPlc?.Write(variable, typedValue);
return ErrorCode.NoError;
}
catch (Exception e)
{
Console.WriteLine(e);
return ErrorCode.WriteDataError;
}
}
/// <summary>
/// PLC에 바이트 배열을 씁니다.
/// </summary>
public ErrorCode WriteBytes(DataType dataType, int db, int startByteAdr, byte[] value)
{
try
{
mPlc?.WriteBytes((S7.Net.DataType)Enum.Parse(typeof(S7.Net.DataType), dataType.ToString()), db, startByteAdr, value);
return ErrorCode.NoError;
}
catch (Exception e)
{
Console.WriteLine(e);
return ErrorCode.WriteDataError;
}
}
/// <summary>
/// 여러 변수(데이터아이템)를 동시에 읽습니다.
/// </summary>
public List<byte[]> ReadMultipleVars(List<DataItem> dataItems)
{
var result = new List<byte[]>();
try
{
List<S7.Net.Types.DataItem> _dataItems = new List<S7.Net.Types.DataItem>();
foreach (var item in dataItems)
{
_dataItems.Add(new S7.Net.Types.DataItem
{
DataType = (S7.Net.DataType)Enum.Parse(typeof(S7.Net.DataType), item.DataType.ToString()),
DB = item.DB,
StartByteAdr = item.StartByteAdr,
Count = item.Count,
VarType = (S7.Net.VarType)Enum.Parse(typeof(S7.Net.VarType), item.VarType.ToString()),
BitAdr = item.BitAdr
});
}
mPlc.ReadMultipleVars(_dataItems);
foreach (var item in _dataItems)
{
result.Add(item.Value as byte[]);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return result;
}
/// <summary>
/// 여러 변수(데이터아이템)를 동시에 씁니다.
/// </summary>
public ErrorCode WriteMultipleVars(List<DataItem> dataItems)
{
try
{
List<S7.Net.Types.DataItem> _dataItems = new List<S7.Net.Types.DataItem>();
foreach (var item in dataItems)
{
object converted = ConvertToTargetType((S7.Net.VarType)Enum.Parse(typeof(S7.Net.VarType), item.VarType.ToString()), item.Value);
_dataItems.Add(new S7.Net.Types.DataItem
{
DataType = (S7.Net.DataType)Enum.Parse(typeof(S7.Net.DataType), item.DataType.ToString()),
DB = item.DB,
StartByteAdr = item.StartByteAdr,
Count = item.Count,
VarType = (S7.Net.VarType)Enum.Parse(typeof(S7.Net.VarType), item.VarType.ToString()),
BitAdr = item.BitAdr,
Value = converted
});
}
mPlc.Write(_dataItems.ToArray());
return ErrorCode.NoError;
}
catch (Exception e)
{
Console.WriteLine(e);
return ErrorCode.WriteDataError;
}
}
/// <summary>
/// 내부에서 데이터 타입에 따라 값을 변환합니다.
/// </summary>
private object ConvertToTargetType(S7.Net.VarType varType, object value)
{
switch (varType)
{
case S7.Net.VarType.Bit:
return value.ToString() == "1" ? true : value.ToString() == "0" ? false : bool.Parse(value.ToString());
case S7.Net.VarType.Byte:
return byte.Parse(value.ToString());
case S7.Net.VarType.Word:
case S7.Net.VarType.Int:
return short.Parse(value.ToString());
case S7.Net.VarType.DWord:
case S7.Net.VarType.DInt:
return int.Parse(value.ToString());
case S7.Net.VarType.Real:
return float.Parse(value.ToString());
case S7.Net.VarType.LReal:
return double.Parse(value.ToString());
default:
return value;
}
}
}
public class DataItem
{
public DataType DataType { get; set; }
public VarType VarType { get; set; }
public int DB { get; set; }
public int StartByteAdr { get; set; }
public int Count { get; set; }
public byte BitAdr { get; set; }
public object Value { get; set; }
public DataItem() { }
}
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.