MasterTcpClient.cs
26.3 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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
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;
using OnlineStore.LoadCSVLibrary;
namespace OnlineStore.DeviceLibrary
{
public class MasterTcpClient
{
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 MasterTcpClient()
{
}
private string IP = "";
public int TimeOutTime = 0;
public MasterTcpClient(string ip, ushort port)
{
this.IP = ip;
TimeOutTime = 2000;
connect(ip, port);
}
private System.Timers.Timer reviceTimer = new System.Timers.Timer();
public void connect(string ip, ushort port)
{
try
{
// 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;
}
}
//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 (System.IO.IOException error)
{
LogUtil.info(LOGGER, "Connect to " + ip + ":" + port + " fail!");
_connected = false;
throw (error);
}
}
void reviceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
//socketClient.BeginReceive(tcpSocketReviceBuffer, 0, tcpSocketReviceBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), socketClient);
ReviceDataProcess();
Thread.Sleep(10);
}
catch (Exception ex)
{
LOGGER.Error("IO模块["+IP+"]出错:" + ex.ToString());
}
}
private void ReviceDataProcess()
{
int lengthIndex = 5;
byte[] rdata = Receive();
if (rdata != null)
{
string str = "";
foreach (byte by in rdata)
{
str = str + " " + by;
if (str.Length > 200)
{
break;
}
}
//这里rdata就是接收到的数据,
IPEndPoint clientipe = (IPEndPoint)socketClient.RemoteEndPoint;
//ushort id = BitConverter.ToUInt16(rdata, 0);
//byte function = rdata[7];
byte dataLength = rdata[lengthIndex];
int allLength = lengthIndex + 1 + dataLength;
if (rdata.Length > allLength)
{
//LogUtil.info(clientipe.ToString() + "收到数据(需要分包):" + str);
int currStartIndex = 0;
for (int i = 0; i < 100; i++)
{
try
{
if (rdata.Length < currStartIndex + lengthIndex)
{
LogUtil.error(clientipe.ToString() + "收到数据:" + str + "分包出错 [" + currStartIndex + "]");
}
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());
}
}
}
else
{
LogUtil.debug(LOGGER, clientipe.ToString() + "收到数据(无需分包):" + str);
ushort id = BitConverter.ToUInt16(rdata, 0);
byte function = rdata[7];
DataProcess(clientipe.ToString(),id,function,rdata);
}
}
}
private void DataProcess(string clientIp, ushort id, byte function, byte[] rdata)
{
byte[] data;
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)
{
LogUtil.error(LOGGER, "IO模块[" + IP + "]接收数据出现错误:" + e.ToString());
if (socketClient != null)
{
socketClient.Close();
socketClient = null;
}
return null;
}
}
// ------------------------------------------------------------------------
/// <summary>Stop connection to slave.</summary>
public void disconnect()
{
Dispose();
}
// ------------------------------------------------------------------------
/// <summary>Destroy master instance.</summary>
~MasterTcpClient()
{
Dispose();
}
// ------------------------------------------------------------------------
/// <summary>Destroy master instance</summary>
public void Dispose()
{
reviceTimer.Enabled = false;
if (socketClient != null)
{
if (socketClient.Connected)
{
try
{
socketClient.Shutdown(SocketShutdown.Both);
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "IO模块[" + IP + "]dispose出错:" + ex.ToString());
}
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 ReadCoils(ushort id, ushort startAddress, ushort numInputs, byte SlaveID)
{
WriteAsyncData(CreateReadHeader(id, startAddress, numInputs, fctReadCoil, SlaveID), id);
}
public void ReadDiscreteInputs(ushort id, ushort startAddress, ushort numInputs, byte SlaveID)
{
WriteAsyncData(CreateReadHeader(id, startAddress, numInputs, fctReadDiscreteInputs, SlaveID), id);
}
public void ReadHoldingRegister(ushort id, ushort startAddress, ushort numInputs, byte SlaveID)
{
WriteAsyncData(CreateReadHeader(id, startAddress, numInputs, fctReadHoldingRegister, SlaveID), id);
}
public void ReadInputRegister(ushort id, ushort startAddress, ushort numInputs, byte SlaveID)
{
WriteAsyncData(CreateReadHeader(id, startAddress, numInputs, fctReadInputRegister, SlaveID), id);
}
public bool WriteSingleCoils(ushort id, ushort startAddress, IO_VALUE ioValue, byte SlaveID)
{
byte[] data;
bool OnOff = ioValue.Equals(IO_VALUE.HIGH);
data = CreateWriteHeader(id, startAddress, 1, 1, fctWriteSingleCoil, SlaveID);
if (OnOff == true) data[10] = 255;
else data[10] = 0;
return WriteAsyncData(data, id);
}
public void WriteMultipleCoils(ushort id, ushort startAddress, ushort numBits, byte[] values, byte SlaveID)
{
byte numBytes = Convert.ToByte(values.Length);
byte[] data;
data = CreateWriteHeader(id, startAddress, numBits, (byte)(numBytes + 2), fctWriteMultipleCoils, SlaveID);
Array.Copy(values, 0, data, 13, numBytes);
WriteAsyncData(data, id);
}
public void WriteSingleRegister(ushort id, ushort startAddress, byte[] values, byte SlaveID)
{
byte[] data;
data = CreateWriteHeader(id, startAddress, 1, 1, fctWriteSingleRegister, SlaveID);
data[10] = values[0];
data[11] = values[1];
WriteAsyncData(data, id);
}
public void WriteMultipleRegister(ushort id, ushort startAddress, byte[] values, byte SlaveID)
{
ushort numBytes = Convert.ToUInt16(values.Length);
if (numBytes % 2 > 0) numBytes++;
byte[] data;
data = CreateWriteHeader(id, startAddress, Convert.ToUInt16(numBytes / 2), Convert.ToUInt16(numBytes + 2), fctWriteMultipleRegister, SlaveID);
Array.Copy(values, 0, data, 13, values.Length);
WriteAsyncData(data, id);
}
public void ReadWriteMultipleRegister(ushort id, ushort startReadAddress, ushort numInputs, ushort startWriteAddress, byte SlaveID, byte[] values)
{
ushort numBytes = Convert.ToUInt16(values.Length);
if (numBytes % 2 > 0) numBytes++;
byte[] data;
data = CreateReadWriteHeader(id, startReadAddress, numInputs, startWriteAddress, Convert.ToUInt16(numBytes / 2), SlaveID);
Array.Copy(values, 0, data, 17, values.Length);
WriteAsyncData(data, id);
}
// ------------------------------------------------------------------------
// Create modbus header for read action
private byte[] CreateReadHeader(ushort id, ushort 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 = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)startAddress));
data[8] = _adr[0]; // Start address
data[9] = _adr[1]; // Start address
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;
}
// ------------------------------------------------------------------------
// Create modbus header for write action
private byte[] CreateWriteHeader(ushort id, ushort startAddress, ushort numData, ushort numBytes, byte function, byte SlaveID)
{
byte[] data = new byte[numBytes + 11];
byte[] _id = BitConverter.GetBytes((short)id);
data[0] = _id[0]; // Slave id high byte
data[1] = _id[1]; // Slave id low byte+
byte[] _size = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)(5 + numBytes)));
data[4] = _size[0]; // Complete message size in bytes
data[5] = _size[1]; // Complete message size in bytes
data[6] = SlaveID; // Slave address //必须设置为"1": 2012.04-24 覃发光;
data[7] = function; // Function code
byte[] _adr = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)startAddress));
data[8] = _adr[0]; // Start address
data[9] = _adr[1]; // Start address
if (function >= fctWriteMultipleCoils)
{
byte[] _cnt = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)numData));
data[10] = _cnt[0]; // Number of bytes
data[11] = _cnt[1]; // Number of bytes
data[12] = (byte)(numBytes - 2);
}
return data;
}
// ------------------------------------------------------------------------
// Create modbus header for write action
private byte[] CreateReadWriteHeader(ushort id, ushort startReadAddress, ushort numRead, ushort startWriteAddress, ushort numWrite, byte SlaveID)
{
byte[] data = new byte[numWrite * 2 + 17];
byte[] _id = BitConverter.GetBytes((short)id);
data[0] = _id[0]; // Slave id high byte
data[1] = _id[1]; // Slave id low byte+
byte[] _size = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)(11 + numWrite * 2)));
data[4] = _size[0]; // Complete message size in bytes
data[5] = _size[1]; // Complete message size in bytes
data[6] = SlaveID; // Slave address //必须设置为"1": 2012.04-24 覃发光;
data[7] = fctReadWriteMultipleRegister; // Function code
byte[] _adr_read = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)startReadAddress));
data[8] = _adr_read[0]; // Start read address
data[9] = _adr_read[1]; // Start read address
byte[] _cnt_read = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)numRead));
data[10] = _cnt_read[0]; // Number of bytes to read
data[11] = _cnt_read[1]; // Number of bytes to read
byte[] _adr_write = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)startWriteAddress));
data[12] = _adr_write[0]; // Start write address
data[13] = _adr_write[1]; // Start write address
byte[] _cnt_write = BitConverter.GetBytes((short)IPAddress.HostToNetworkOrder((short)numWrite));
data[14] = _cnt_write[0]; // Number of bytes to write
data[15] = _cnt_write[1]; // Number of bytes to write
data[16] = (byte)(numWrite * 2);
return data;
}
// ------------------------------------------------------------------------
// Write asynchronous data
private bool WriteAsyncData(byte[] write_data, ushort id)
{
if (socketClient == null)
{
LOGGER.Error("MasterTcpClient发送数据时发现socketClient=null");
return false ;
}
IPEndPoint clientipe = (IPEndPoint)socketClient.RemoteEndPoint;
if ((socketClient != null) && (socketClient.Connected))
{
try
{
//发送的数据打印出来
string str = "";
foreach (byte by in write_data)
{
str = str +" "+ by;
}
//LogUtil.info( clientipe.ToString()+"发送数据:" + str);
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();
return true;
}
catch (SystemException error)
{
LogUtil.error(LOGGER, "IO模块 WriteAsyncData出错:" + error.ToString());
CallException(id, write_data[7], excExceptionConnectionLost, tcpSocketReviceBuffer);
}
}
else CallException(id, write_data[7], excExceptionConnectionLost, tcpSocketReviceBuffer);
return false;
}
// ------------------------------------------------------------------------
// Write asynchronous data acknowledge
private void OnSend(System.IAsyncResult result)
{
if (result.IsCompleted == false) CallException(0xFFFF, 0xFF, excSendFailt, tcpSocketReviceBuffer);
}
// ------------------------------------------------------------------------
// Write asynchronous data response
private void OnReceive(System.IAsyncResult result)
{
if (socketClient == null)
{
return;
}
IPEndPoint clientipe = (IPEndPoint)socketClient.RemoteEndPoint;
if (result.IsCompleted == false) {
CallException(0xFF, 0xFF, excExceptionConnectionLost, tcpSocketReviceBuffer);
}
ushort id = BitConverter.ToUInt16(tcpSocketReviceBuffer, 0); ;
byte function = tcpSocketReviceBuffer[7];
byte[] data;
// ------------------------------------------------------------
// Write response data
if ((function >= fctWriteSingleCoil) && (function != fctReadWriteMultipleRegister))
{
data = new byte[2];
Array.Copy(tcpSocketReviceBuffer, 10, data, 0, 2);
}
// ------------------------------------------------------------
// Read response data
else
{
data = new byte[tcpSocketReviceBuffer[8]];
Array.Copy(tcpSocketReviceBuffer, 9, data, 0, tcpSocketReviceBuffer[8]);
}
// ------------------------------------------------------------
// Response data is slave exception
if (function > excExceptionOffset)
{
function -= excExceptionOffset;
CallException(id, function, tcpSocketReviceBuffer[8],tcpSocketReviceBuffer);
}
// ------------------------------------------------------------
// Response data is regular data
else if (OnResponseData != null)
{ //收到的数据打印出来
string str = "";
foreach (byte by in tcpSocketReviceBuffer)
{
str = str + " " + by;
if (str.Length > 50)
{
break;
}
}
// LogUtil.info( clientipe.ToString()+"收到数据:" + str);
OnResponseData(clientipe.ToString(), id, function, data, tcpSocketReviceBuffer);
}
}
internal bool ISConnection()
{
if (socketClient == null)
{
return false;
}
if (socketClient.Connected == false)
{
return false;
}
return true;
}
}
}