AITcpClient.cs
17.5 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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
using log4net;
using System.Reflection;
using OnlineStore.Common;
namespace OnlineStore.DeviceLibrary
{
public class AITcpClient
{
public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// ------------------------------------------------------------------------
// Constants for access
private const byte fctReadCoil = 1;
private const byte fctReadDiscreteInputs = 2;
private const byte fctReadHoldingRegister = 3;
private const byte fctReadInputRegister = 4;
private const byte fctWriteSingleCoil = 5;
private const byte fctWriteSingleRegister = 6;
private const byte fctWriteMultipleCoils = 15;
private const byte fctWriteMultipleRegister = 16;
private const byte fctReadWriteMultipleRegister = 23;
/// <summary>Constant for exception illegal function.</summary>
public const byte excIllegalFunction = 1;
/// <summary>Constant for exception illegal data address.</summary>
public const byte excIllegalDataAdr = 2;
/// <summary>Constant for exception illegal data value.</summary>
public const byte excIllegalDataVal = 3;
/// <summary>Constant for exception slave device failure.</summary>
public const byte excSlaveDeviceFailure = 4;
/// <summary>Constant for exception acknowledge.</summary>
public const byte excAck = 5;
/// <summary>Constant for exception slave is busy/booting up.</summary>
public const byte excSlaveIsBusy = 6;
/// <summary>Constant for exception gate path unavailable.</summary>
public const byte excGatePathUnavailable = 10;
/// <summary>Constant for exception not connected.</summary>
public const byte excExceptionNotConnected = 253;
/// <summary>Constant for exception connection lost.</summary>
public const byte excExceptionConnectionLost = 254;
/// <summary>Constant for exception response timeout.</summary>
public const byte excExceptionTimeout = 255;
/// <summary>Constant for exception wrong offset.</summary>
private const byte excExceptionOffset = 128;
/// <summary>Constant for exception send failt.</summary>
private const byte excSendFailt = 100;
// ------------------------------------------------------------------------
// Private declarations
private static ushort _timeout = 500;
private static ushort _refresh = 10;
private static bool _connected = false;
private static bool _autoConnectOfBreak = false;
private Socket socketClient;
private int M281_A_Len = 0;
private byte[] tcpSocketReviceBuffer = new byte[2048];
//private Socket tcpSynCl;
//private byte[] tcpSynClBuffer = new byte[2048];
// ------------------------------------------------------------------------
/// <summary>Response data event. This event is called when new data arrives</summary>
public delegate void ResponseData(string ip, ushort id, byte function, byte[] data, byte[] reviceData);
/// <summary>Response data event. This event is called when new data arrives</summary>
public event ResponseData OnResponseData;
/// <summary>Exception data event. This event is called when the data is incorrect</summary>
public delegate void ExceptionData(string ip, ushort id, byte function, byte exception, byte[] reviceData);
/// <summary>Exception data event. This event is called when the data is incorrect</summary>
public event ExceptionData OnException;
/// <summary>
/// autoConnectOfBreak
/// </summary>
public bool autoConnectOfBreak
{
get { return _autoConnectOfBreak; }
set { _autoConnectOfBreak = value; }
}
public static ushort timeout
{
get { return _timeout; }
set { _timeout = value; }
}
public ushort refresh
{
get { return _refresh; }
set { _refresh = value; }
}
public bool connected
{
get { return _connected; }
}
public AITcpClient()
{
}
public string IP = "";
public int Port = 0;
public int TimeOutTime = 0;
public AITcpClient(string ip, ushort port)
{
TimeOutTime = 2000;
connect(ip, port);
}
private System.Timers.Timer reviceTimer = new System.Timers.Timer();
public void connect(string ip, ushort port)
{
try
{
this.IP = ip;
this.Port = port;
OnResponseData = null;
// Connect asynchronous client
socketClient = new Socket(IPAddress.Parse(ip).AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (TimeOutTime <= 0)
{
socketClient.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, _timeout);
socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _timeout);
socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
}
else
{
socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, _timeout);
socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _timeout);
socketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
IAsyncResult connResult = socketClient.BeginConnect(ip, port, null, null);
connResult.AsyncWaitHandle.WaitOne(this.TimeOutTime, true); //等待2秒
if (!connResult.IsCompleted)
{
LogUtil.info(LOGGER, "Connect to " + ip + ":" + port + " fail!");
return;
}
else
{
_connected = true;
LogUtil.info(LOGGER, "Connect to " + ip + ":" + port + " success!");
}
}
//Thread threadReceive = new Thread(new ThreadStart(ReceiveHandle));
//threadReceive.Start();
reviceTimer.AutoReset = true;
reviceTimer.Elapsed += reviceTimer_Elapsed;
reviceTimer.Interval = 130;
reviceTimer.Enabled = true;
_connected = true;
}
catch (Exception error)
{
LogUtil.info(LOGGER, "Connect to " + ip + ":" + port + " fail!");
_connected = false;
}
}
public void WriteAIScope(ushort id, byte slaveId, string address, int value)
{
//0x000100000006FF0603EA0001
byte function = 0x06;
byte[] data = new byte[12];
byte[] _id = BitConverter.GetBytes((short)id);
data[0] = _id[0]; // Slave id high byte
data[1] = _id[1]; // Slave id low byte
data[2] = 0x00;
data[3] = 0x00;
data[4] = 0x00;
data[5] = 6; // Message size
data[6] = slaveId; // Slave address //必须设置为"1": 2012.04-24 覃发光;
data[7] = function; ; // Function code
byte[] _adr = AcSerialBean.StringToByte(address);
data[8] = _adr[0]; // Start address
data[9] = _adr[1]; // Start address
byte[] _length = BitConverter.GetBytes((short)1);
data[10] = _length[0]; // Number of data to read
data[11] = _length[1]; // Number of data to read
WriteAsyncData(data, id);
}
public void ReadAllAI(ushort id, string startAddress, int length, byte slaveId)
{
//0x 000100000006FF0302580010
byte function = 0x03;
byte[] data = CreateData(id, startAddress, (ushort)length, function, slaveId);
WriteAsyncData(data, id);
}
private byte[] CreateData(ushort id, string startAddress, ushort length, byte function, byte SlaveID)
{
byte[] data = new byte[12];
byte[] _id = BitConverter.GetBytes((short)id);
data[0] = _id[0]; // Slave id high byte
data[1] = _id[1]; // Slave id low byte
data[5] = 6; // Message size
data[6] = SlaveID; // Slave address //必须设置为"1": 2012.04-24 覃发光;
data[7] = function; // Function code
byte[] _adr = AcSerialBean.StringToByte(startAddress);
if (_adr.Length.Equals(2))
{
data[8] = _adr[0]; // Start address
data[9] = _adr[1]; // Start address
}
else if (_adr.Length.Equals(1))
{
data[8] = 0x00;
data[9] = _adr[0]; // Start address
}
else
{
data[8] = 0x00;
data[9] = 0x00;
}
byte[] _length = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)length));
data[10] = _length[0]; // Number of data to read
data[11] = _length[1]; // Number of data to read
return data;
}
void reviceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
ReviceDataProcess();
Thread.Sleep(10);
}
catch (Exception ex)
{
LOGGER.Error("出错:" + ex.ToString());
}
}
private void ReviceDataProcess()
{
byte[] rdata = Receive();
if (rdata == null)
{
return;
}
string str = "";
foreach (byte by in rdata)
{
str = str + " " + by;
}
int lengthIndex = 5;
//这里rdata就是接收到的数据,
IPEndPoint clientipe = (IPEndPoint)socketClient.RemoteEndPoint;
byte dataLength = rdata[lengthIndex];
int allLength = lengthIndex + 1 + dataLength;
if (rdata.Length <= allLength)
{
LogUtil.debug(LOGGER, clientipe.ToString() + "收到数据(无需分包):" + str);
ushort id = BitConverter.ToUInt16(rdata, 0);
byte function = rdata[7];
DataProcess(clientipe.ToString(), id, function, rdata);
return;
}
int currStartIndex = 0;
try
{
for (int i = 0; i < 100; i++)
{
if (rdata.Length < currStartIndex + lengthIndex)
{
LogUtil.error(clientipe.ToString() + "收到数据:" + str + "分包出错 [" + currStartIndex + "]");
break;
}
else
{
dataLength = rdata[currStartIndex + lengthIndex];
allLength = lengthIndex + 1 + dataLength;
byte[] thisData = new byte[allLength];
Array.Copy(rdata, currStartIndex, thisData, 0, allLength);
ushort id = BitConverter.ToUInt16(thisData, 0);
byte function = thisData[7];
DataProcess(clientipe.ToString(), id, function, thisData);
//剩余的数据处理
if (rdata.Length <= currStartIndex + allLength)
{
break;
}
currStartIndex = currStartIndex + allLength;
}
}
}
catch (Exception ex)
{
LogUtil.error(clientipe.ToString() + "收到数据:" + str + "分包出错 [" + currStartIndex + "]:" + ex.ToString());
}
}
private void DataProcess(string clientIp, ushort id, byte function, byte[] rdata)
{
byte[] data;
if (rdata.Length <= 9)
{
return;
}
if ((function >= fctWriteSingleCoil) && (function != fctReadWriteMultipleRegister))
{
data = new byte[2];
Array.Copy(rdata, 10, data, 0, 2);
}
// ------------------------------------------------------------
// Read response data
else
{
data = new byte[rdata[8]];
Array.Copy(rdata, 9, data, 0, rdata[8]);
}
// ------------------------------------------------------------
// Response data is slave exception
if (function > excExceptionOffset)
{
function -= excExceptionOffset;
CallException(id, function, rdata[8], rdata);
}
// ------------------------------------------------------------
// Response data is regular data
else if (OnResponseData != null)
{ //收到的数据打印出来
OnResponseData(clientIp, id, function, data, rdata);
}
}
private byte[] Receive()
{
try
{
if (socketClient == null || !socketClient.Connected || socketClient.Available < 1)
{
return null;
}
int size = socketClient.Available;
byte[] rData = new byte[size];
socketClient.Receive(rData, size, SocketFlags.None);
return rData;
}
catch (SocketException e)
{
if (socketClient != null)
{
socketClient.Close();
socketClient = null;
}
return null;
}
}
public void disconnect()
{
Dispose();
}
~AITcpClient()
{
Dispose();
}
public void Dispose()
{
reviceTimer.Enabled = false;
if (socketClient != null)
{
if (socketClient.Connected)
{
try { socketClient.Shutdown(SocketShutdown.Both); }
catch { }
socketClient.Close();
}
socketClient = null;
}
}
internal void CallException(ushort id, byte function, byte exception, byte[] rdata)
{
reviceTimer.Enabled = false;
if ((socketClient == null))
{
return;
}
if (exception == excExceptionConnectionLost)
{
//tcpSynCl = null;
socketClient = null;
return;
}
if (OnException != null)
{
OnException(socketClient.RemoteEndPoint.AddressFamily.ToString(), id, function, exception, rdata);
}
}
public void WriteAsyncData(byte[] write_data, ushort id)
{
try
{
if (socketClient == null)
{
LOGGER.Error("AITcpClient发送数据时发现socketClient=null");
return;
}
IPEndPoint clientipe = (IPEndPoint)socketClient.RemoteEndPoint;
if ((socketClient != null) && (socketClient.Connected))
{
try
{
//LogUtil.info( clientipe.ToString()+"发送数据:" + AcSerialBean.byteToHexStr(write_data));
socketClient.BeginSend(write_data, 0, write_data.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
//socketClient.BeginReceive(tcpSocketReviceBuffer, 0, tcpSocketReviceBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), socketClient);
ReviceDataProcess();
}
catch (SystemException error)
{
CallException(id, write_data[7], excExceptionConnectionLost, tcpSocketReviceBuffer);
}
}
else CallException(id, write_data[7], excExceptionConnectionLost, tcpSocketReviceBuffer);
}
catch (Exception ex)
{
LOGGER.Error("出错:" + ex.ToString());
}
}
// ------------------------------------------------------------------------
// Write asynchronous data acknowledge
private void OnSend(System.IAsyncResult result)
{
if (result.IsCompleted == false) CallException(0xFFFF, 0xFF, excSendFailt, tcpSocketReviceBuffer);
}
internal bool ISConnection()
{
if (socketClient == null)
{
return false;
}
if (socketClient.Connected == false)
{
return false;
}
return true;
}
}
}