forked from GavinYellow/SharpSCADA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModbusTCPDriver.cs
646 lines (595 loc) · 25.6 KB
/
ModbusTCPDriver.cs
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Timers;
using DataService;
namespace ModbusDriver
{
[Description("Modbus TCP协议")]
public sealed class ModbusTCPReader : IPLCDriver, IMultiReadWrite
{
private int _timeout;
private Socket tcpSynCl;
private byte[] tcpSynClBuffer = new byte[0xFF];
short _id;
public short ID
{
get
{
return _id;
}
}
string _name;
public string Name
{
get
{
return _name;
}
}
string _ip;
public string ServerName
{
get { return _ip; }
set { _ip = value; }
}
public bool IsClosed
{
get
{
return tcpSynCl == null || tcpSynCl.Connected == false;
}
}
byte _devId;//设备ID 单元号 字节号
/// <summary>
/// 设备ID 单元号 字节号
/// </summary>
public byte DevId
{
get { return _devId; }
set { _devId = value; }
}
public int TimeOut
{
get { return _timeout; }
set { _timeout = value; }
}
List<IGroup> _grps = new List<IGroup>(20);
public IEnumerable<IGroup> Groups
{
get { return _grps; }
}
IDataServer _server;
public IDataServer Parent
{
get { return _server; }
}
public ModbusTCPReader(IDataServer server, short id, string name, string ip, int timeOut = 500, string spare1 = null, string spare2 = null)
{
_id = id;
_name = name;
_server = server;
_ip = ip;
_timeout = timeOut;
_devId = byte.Parse(spare2);
}
public bool Connect()
{
int port = 502;
try
{
if (tcpSynCl != null)
tcpSynCl.Close();
//IPAddress ip = IPAddress.Parse(_ip);
// ----------------------------------------------------------------
// Connect synchronous client
tcpSynCl = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
tcpSynCl.SendTimeout = _timeout;
tcpSynCl.ReceiveTimeout = _timeout;
tcpSynCl.NoDelay = true;
tcpSynCl.Connect(_ip, port);
return true;
}
catch (SocketException error)
{
if (OnClose != null)
OnClose(this, new ShutdownRequestEventArgs(error.Message));
return false;
}
}
//创建读取命令
private byte[] CreateReadCmd(int id, int startAddress, ushort length, byte function)
{
byte[] data = new byte[12];
data[0] = 0; //事务处理标识 可以写死成0 后面考虑自加
data[1] = 0; //事务处理标识 可以写死成0 后面考虑自加
data[2] = 0; // 协议标识符
data[3] = 0; // 协议标识符
byte[] _size = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)(6)));//读命令帧字节总数永远是6位
data[4] = _size[0]; // Complete message size in bytes
data[5] = _size[1]; // Complete message size in bytes
data[6] = (byte)_devId; // 单元标识符 或者叫Slave address
data[7] = function; // 功能码
byte[] _adr = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)startAddress));
data[8] = _adr[0]; // Start address
data[9] = _adr[1]; // Start address
byte[] _Length = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)length));//读取的字节总数
data[10] = _Length[0];
data[11] = _Length[1];
return data;
}
//创建写入的帧头 数据后面添加
private byte[] CreateWriteHeader(int id, int startAddress, ushort numData, ushort numBytes, byte function)
{
byte[] data = new byte[numBytes + 11];
byte[] _id = BitConverter.GetBytes(id);
data[0] = 0; //事务处理标识 可以写死成0 后面考虑自加
data[1] = 0; //事务处理标识 可以写死成0 后面考虑自加
data[2] = 0; // 协议标识符
data[3] = 0; // 协议标识符
byte[] _size = BitConverter.GetBytes(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] = (byte)_devId; // Slave address
data[7] = function; // Function code
byte[] _adr = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)startAddress));
data[8] = _adr[0]; // Start address
data[9] = _adr[1]; // Start address
if (function >= Modbus.fctWriteMultipleCoils)
{
byte[] _cnt = BitConverter.GetBytes(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;
}
private byte[] WriteSyncData(byte[] write_data)
{
short id = BitConverter.ToInt16(write_data, 0);
if (IsClosed) CallException(id, write_data[7], Modbus.excExceptionConnectionLost);
else
{
try
{
tcpSynCl.Send(write_data, 0, write_data.Length, SocketFlags.None);//是否存在lock的问题?
int result = tcpSynCl.Receive(tcpSynClBuffer, 0, 0xFF, SocketFlags.None);
byte function = tcpSynClBuffer[7];
byte[] data;
if (result == 0) CallException(id, write_data[7], Modbus.excExceptionConnectionLost);
// ------------------------------------------------------------
// Response data is slave ModbusModbus.exception
if (function > Modbus.excExceptionOffset)
{
function -= Modbus.excExceptionOffset;
CallException(id, function, tcpSynClBuffer[8]);
return null;
}
// ------------------------------------------------------------
// Write response data
else if ((function >= Modbus.fctWriteSingleCoil) && (function != Modbus.fctReadWriteMultipleRegister))
{
data = new byte[2];
Array.Copy(tcpSynClBuffer, 10, data, 0, 2);
}
// ------------------------------------------------------------
// Read response data
else
{
data = new byte[tcpSynClBuffer[8]];
Array.Copy(tcpSynClBuffer, 9, data, 0, tcpSynClBuffer[8]);
}
return data;
}
catch (SocketException e)
{
CallException(id, write_data[7], Modbus.excExceptionConnectionLost);
}
}
return null;
}
public byte[] WriteSingleCoils(int id, int startAddress, bool OnOff)
{
byte[] data;
data = CreateWriteHeader(id, startAddress, 1, 1, Modbus.fctWriteSingleCoil);
if (OnOff == true) data[10] = 255;
else data[10] = 0;
return WriteSyncData(data);
}
public byte[] WriteMultipleCoils(int id, int startAddress, ushort numBits, byte[] values)
{
byte numBytes = Convert.ToByte(values.Length);
byte[] data;
data = CreateWriteHeader(id, startAddress, numBits, (byte)(numBytes + 2), Modbus.fctWriteMultipleCoils);
Array.Copy(values, 0, data, 13, numBytes);
return WriteSyncData(data);
}
public byte[] WriteSingleRegister(int id, int startAddress, byte[] values)
{
byte[] data;
data = CreateWriteHeader(id, startAddress, 1, 1, Modbus.fctWriteSingleRegister);
data[10] = values[1];//这里需要倒一下
data[11] = values[0];
return WriteSyncData(data);
}
public byte[] WriteMultipleRegister(int id, int startAddress, byte[] values)
{
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), Modbus.fctWriteMultipleRegister);
Array.Copy(values, 0, data, 13, values.Length);
return WriteSyncData(data);
}
public int PDU
{
get { return 252; }
}
public DeviceAddress GetDeviceAddress(string address)
{
DeviceAddress dv = DeviceAddress.Empty;
if (string.IsNullOrEmpty(address))
return dv;
switch (address[0])
{
case '0':
{
dv.Area = Modbus.fctReadCoil;
int st;
int.TryParse(address, out st);
//dv.Start = (st / 16) * 16;//???????????????????
dv.Bit = (byte)(st % 16);
st /= 16;
dv.Start = st;
}
break;
case '1':
{
dv.Area = Modbus.fctReadDiscreteInputs;
int st;
int.TryParse(address.Substring(1), out st);
//dv.Start = (st / 16) * 16;//???????????????????
dv.Bit = (byte)(st % 16);
st /= 16;
dv.Start = st;
}
break;
case '4':
{
int index = address.IndexOf('.');
dv.Area = Modbus.fctReadHoldingRegister;
if (index > 0)
{
dv.Start = int.Parse(address.Substring(1, index - 1));
dv.Bit = byte.Parse(address.Substring(index + 1));
}
else
dv.Start = int.Parse(address.Substring(1));
}
break;
case '3':
{
int index = address.IndexOf('.');
dv.Area = Modbus.fctReadInputRegister;
if (index > 0)
{
dv.Start = int.Parse(address.Substring(1, index - 1));
dv.Bit = byte.Parse(address.Substring(index + 1));
}
else
dv.Start = int.Parse(address.Substring(1));
}
break;
}
return dv;
}
public string GetAddress(DeviceAddress address)
{
return string.Empty;
}
public IGroup AddGroup(string name, short id, int updateRate, float deadBand = 0f, bool active = false)
{
ModbusTcpGroup grp = new ModbusTcpGroup(id, name, updateRate, active, this);
_grps.Add(grp);
return grp;
}
public bool RemoveGroup(IGroup grp)
{
grp.IsActive = false;
return _grps.Remove(grp);
}
public void Dispose()
{
if (tcpSynCl != null)
{
if (tcpSynCl.Connected)
{
try { tcpSynCl.Shutdown(SocketShutdown.Both); }
catch { }
tcpSynCl.Close();
}
tcpSynCl = null;
}
foreach (IGroup grp in _grps)
{
grp.Dispose();
}
_grps.Clear();
}
internal string GetErrorString(byte exception)
{
switch (exception)
{
case Modbus.excIllegalFunction:
return "Constant for ModbusModbus.exception illegal function.";
case Modbus.excIllegalDataAdr:
return "Constant for ModbusModbus.exception illegal data address.";
case Modbus.excIllegalDataVal:
return "Constant for ModbusModbus.exception illegal data value.";
case Modbus.excSlaveDeviceFailure:
return "Constant for ModbusModbus.exception slave device failure.";
case Modbus.excAck:
return "Constant for ModbusModbus.exception acknowledge.";
case Modbus.excSlaveIsBusy:
return "Constant for ModbusModbus.exception slave is busy/booting up.";
case Modbus.excGatePathUnavailable:
return "Constant for ModbusModbus.exception gate path unavailable.";
case Modbus.excExceptionNotConnected:
return "Constant for ModbusModbus.exception not connected.";
case Modbus.excExceptionConnectionLost:
return "Constant for ModbusModbus.exception connection lost.";
case Modbus.excExceptionTimeout:
return "Constant for ModbusModbus.exception response timeout.";
case Modbus.excExceptionOffset:
return "Constant for ModbusModbus.exception wrong offset.";
case Modbus.excSendFailt:
return "Constant for ModbusModbus.exception send failt.";
}
return string.Empty;
}
internal void CallException(int id, byte function, byte exception)
{
if (tcpSynCl == null) return;
if (exception == Modbus.excExceptionConnectionLost && IsClosed == false)
{
if (OnClose != null)
OnClose(this, new ShutdownRequestEventArgs(GetErrorString(exception)));
}
}
public byte[] ReadBytes(DeviceAddress address, ushort size)
{
int area = address.Area;
// 如果读取区域是线圈或者Input类型的话,就读取size*16 个
if (area<2)
{
return WriteSyncData(CreateReadCmd(_id, address.Start, (ushort)(size * 16), (byte)area));
}
else
{
return WriteSyncData(CreateReadCmd(_id, address.Start, size, (byte)area));
}
}
public ItemData<int> ReadInt32(DeviceAddress address)
{
byte[] data = WriteSyncData(CreateReadCmd(_id, address.Start, 2, (byte)address.Area));
if (data == null)
return new ItemData<int>(0, 0, QUALITIES.QUALITY_BAD);
else
return new ItemData<int>(IPAddress.HostToNetworkOrder(BitConverter.ToInt32(data, 0)), 0, QUALITIES.QUALITY_GOOD);
}
public ItemData<short> ReadInt16(DeviceAddress address)
{
byte[] data = WriteSyncData(CreateReadCmd(_id, address.Start, 1, (byte)address.Area));
if (data == null)
return new ItemData<short>(0, 0, QUALITIES.QUALITY_BAD);
else
return new ItemData<short>(IPAddress.HostToNetworkOrder(BitConverter.ToInt16(data, 0)), 0, QUALITIES.QUALITY_GOOD);
}
public ItemData<byte> ReadByte(DeviceAddress address)
{
byte[] data = WriteSyncData(CreateReadCmd(_id, address.Start, 1, (byte)address.Area));
if (data == null)
return new ItemData<byte>(0, 0, QUALITIES.QUALITY_BAD);
else
return new ItemData<byte>(data[0], 0, QUALITIES.QUALITY_GOOD);
}
public ItemData<string> ReadString(DeviceAddress address, ushort size)
{
byte[] data = WriteSyncData(CreateReadCmd(_id, address.Start, size, (byte)address.Area));
if (data == null)
return new ItemData<string>(string.Empty, 0, QUALITIES.QUALITY_BAD);
else
return new ItemData<string>(Encoding.ASCII.GetString(data, 0, data.Length), 0, QUALITIES.QUALITY_GOOD);//是否考虑字节序问题?
}
public unsafe ItemData<float> ReadFloat(DeviceAddress address)
{
byte[] data = WriteSyncData(CreateReadCmd(_id, address.Start, 2, (byte)address.Area));
if (data == null)
return new ItemData<float>(0.0f, 0, QUALITIES.QUALITY_BAD);
else
{
int value = IPAddress.HostToNetworkOrder(BitConverter.ToInt32(data, 0));
return new ItemData<float>(*(((float*)&value)), 0, QUALITIES.QUALITY_GOOD);
}
}
public ItemData<bool> ReadBit(DeviceAddress address)
{
byte[] data = address.Area > 2 ? WriteSyncData(CreateReadCmd(_id, address.Start, 1, (byte)address.Area)) :
WriteSyncData(CreateReadCmd(_id, address.Start + address.Bit, 1, (byte)address.Area));
if (data == null)
return new ItemData<bool>(false, 0, QUALITIES.QUALITY_BAD);
unsafe
{
fixed (byte* p = data)
{
short* p1 = (short*)p;
return new ItemData<bool>((*p1 & (1 << address.Bit.BitSwap()))
!= 0, 0, QUALITIES.QUALITY_GOOD);
}
}
}
public ItemData<object> ReadValue(DeviceAddress address)
{
return this.ReadValueEx(address);
}
public int WriteBytes(DeviceAddress address, byte[] bit)
{
var data = address.Area > 2 ? WriteMultipleRegister(_id, address.Start, bit)
: WriteMultipleCoils(address.Area, address.Start, (ushort)(8 * bit.Length), bit);//应考虑到
return data == null ? -1 : 0;
}
public int WriteBit(DeviceAddress address, bool bit)
{
if (address.Area < 3)
{
var data = WriteSingleCoils(_id, address.Start + address.Bit, bit);
return data == null ? -1 : 0;
}
return -1;
}
public int WriteBits(DeviceAddress address, byte bits)
{
var data = WriteSingleRegister(_id, address.Start, new byte[] { bits });
return data == null ? -1 : 0;
}
public int WriteInt16(DeviceAddress address, short value)
{
var data = WriteSingleRegister(_id, address.Start, BitConverter.GetBytes(value));
return data == null ? -1 : 0;
}
public int WriteInt32(DeviceAddress address, int value)
{
var data = WriteMultipleRegister(_id, address.Start, BitConverter.GetBytes(value));
return data == null ? -1 : 0;
}
public int WriteFloat(DeviceAddress address, float value)
{
var data = WriteMultipleRegister(_id, address.Start, BitConverter.GetBytes(value));
return data == null ? -1 : 0;
}
public int WriteString(DeviceAddress address, string str)
{
var data = WriteMultipleRegister(_id, address.Start, Encoding.ASCII.GetBytes(str));
return data == null ? -1 : 0;
}
public int WriteValue(DeviceAddress address, object value)
{
return this.WriteValueEx(address, value);
}
public event ShutdownRequestEventHandler OnClose;
public int Limit
{
get { return 60; }
}
public ItemData<Storage>[] ReadMultiple(DeviceAddress[] addrsArr)
{
return this.PLCReadMultiple(new NetShortCacheReader(), addrsArr);
}
public int WriteMultiple(DeviceAddress[] addrArr, object[] buffer)
{
return this.PLCWriteMultiple(new NetShortCacheReader(), addrArr, buffer, Limit);
}
}
public sealed class ModbusTcpGroup : PLCGroup
{
public ModbusTcpGroup(short id, string name, int updateRate, bool active, IPLCDriver plcReader)
{
this._id = id;
this._name = name;
this._updateRate = updateRate;
this._isActive = active;
this._plcReader = plcReader;
this._server = _plcReader.Parent;
this._timer = new Timer();
this._changedList = new List<int>();
this._cacheReader = new NetShortCacheReader();
}
protected override unsafe int Poll()
{
short[] cache = (short[])_cacheReader.Cache;
int offset = 0;
foreach (PDUArea area in _rangeList)
{
byte[] rcvBytes = _plcReader.ReadBytes(area.Start, (ushort)area.Len);//从PLC读取数据
if (rcvBytes == null || rcvBytes.Length == 0)
{
//_plcReader.Connect();
return -1;
}
else
{
int len = rcvBytes.Length / 2;
fixed (byte* p1 = rcvBytes)
{
short* prcv = (short*)p1;
int index = area.StartIndex;//index指向_items中的Tag元数据
int count = index + area.Count;
while (index < count)
{
DeviceAddress addr = _items[index].Address;
int iShort = addr.CacheIndex;
int iShort1 = iShort - offset;
if (addr.VarType == DataType.BOOL)
{
short tt = prcv[iShort1];
int tmp = tt ^ cache[iShort];
DeviceAddress next = addr;
if (tmp != 0)
{
while (addr.Start == next.Start)
{
//这里有更改 不知道为什么要转换一下
//NetShortCacheReader 里面的ReadBit 我把BitSwap()也给删了
//int ne = 1 << next.Bit.BitSwap();
int ne = 1 << next.Bit;
if ((tmp & (ne)) > 0) _changedList.Add(index);
if (++index < count)
next = _items[index].Address;
else
break;
}
}
else
{
while (addr.Start == next.Start && ++index < count)
{
next = _items[index].Address;
}
}
}
else
{
if (addr.DataSize <= 2)
{
if (prcv[iShort1] != cache[iShort]) _changedList.Add(index);
}
else
{
int size = addr.DataSize / 2;
for (int i = 0; i < size; i++)
{
if (prcv[iShort1 + i] != cache[iShort + i])
{
_changedList.Add(index);
break;
}
}
}
index++;
}
}
for (int j = 0; j < len; j++)
{
cache[j + offset] = prcv[j];
}//将PLC读取的数据写入到CacheReader中
}
offset += len;
}
}
return 1;
}
}
}