forked from GavinYellow/SharpSCADA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClientDriver.cs
More file actions
1298 lines (1235 loc) · 53.2 KB
/
Copy pathClientDriver.cs
File metadata and controls
1298 lines (1235 loc) · 53.2 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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using DataService;
namespace ClientDriver
{
[Description("客户端驱动")]
public class ClientReader : IDriver//客户端存在对TLV数据的字节序转换问题,需测试
{
short _id;
public short ID
{
get
{
return _id;
}
}
private int _timeout = 0;
public int TimeOut
{
get { return _timeout; }
set { _timeout = value; }
}
string _name;
public string Name
{
get
{
return _name;
}
}
string _ip;
public string ServerName
{
get { return _ip; }
set { _ip = value; }
}
internal Socket tcpSend;
internal Socket tcpRecive;
public bool IsClosed
{
get
{
//return tcpASynCl.Poll(-1, SelectMode.SelectRead);
return tcpSend == null || tcpRecive == null || !tcpSend.Connected || !tcpRecive.Connected;
}
}
List<IGroup> _grps = new List<IGroup>(1);
public IEnumerable<IGroup> Groups
{
get { return _grps; }
}
IDataServer _server;
public IDataServer Parent
{
get { return _server; }
}
public ClientReader(IDataServer server, short id, string name)
{
_id = id;
_server = server;
_name = name;
}
public bool Connect()
{
int port = 6543;
lock (this)
{
try
{
if (tcpRecive != null)
{
tcpRecive.Dispose();
}
if (tcpSend != null)
{
tcpSend.Dispose();
}
tcpRecive = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
tcpRecive.Connect(_ip, port);
tcpRecive.SendTimeout = _timeout;
tcpRecive.ReceiveTimeout = -1;
tcpSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
tcpSend.Connect(_ip, port);
tcpSend.SendTimeout = _timeout;
tcpSend.ReceiveTimeout = _timeout;
return true;
}
catch (SocketException error)
{
if (OnError != null)
OnError(this, new IOErrorEventArgs(error.Message));
return false;
}
}
}
public IGroup AddGroup(string name, short id, int updateRate, float deadBand = 0f, bool active = false)
{
ClientGroup grp = new ClientGroup(id, name, updateRate, active, this);
_grps.Add(grp);
return grp;
}
public bool RemoveGroup(IGroup grp)
{
grp.IsActive = false;
return _grps.Remove(grp);
}
public event IOErrorEventHandler OnError;
public void Dispose()
{
foreach (IGroup grp in _grps)
{
grp.Dispose();
}
_grps.Clear();
try
{
if (tcpRecive != null)
{
if (tcpRecive.Connected)
tcpRecive.Shutdown(SocketShutdown.Both);
tcpRecive.Dispose();
}
if (tcpSend != null)
{
if (tcpSend.Connected)
tcpSend.Shutdown(SocketShutdown.Both);
tcpSend.Dispose();
}
}
catch (SocketException err)
{
if (OnError != null)
OnError(this, new IOErrorEventArgs(err.Message));
}
}
}
public class ClientGroup : IGroup
{
bool _active = false;
public bool IsActive
{
get
{
return _active;
}
set
{
_active = value;
if (value)
{
if (_plcReader != null && _plcReader.tcpSend != null)
{
this._tcpRecive = _plcReader.tcpRecive;
this._tcpSend = _plcReader.tcpSend;
try
{
_addr = (_tcpSend.RemoteEndPoint as IPEndPoint).Address;
}
catch { }
Thread workItem = new Thread(new ThreadStart(ReciveData));
workItem.Priority = ThreadPriority.Highest;
workItem.Start();
if (_updateRate > 0)
ThreadPool.QueueUserWorkItem(new WaitCallback(this.OnUpdate));
else
Init();
}
}
}
}
protected short _id;
public short ID
{
get
{
return _id;
}
}
protected int _updateRate;
public int UpdateRate
{
get
{
return _updateRate;
}
set
{
_updateRate = value;
}
}
protected DeviceAddress _start;
public DeviceAddress Start
{
get
{
return _start;
}
}
protected string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
protected float _deadband;
public float DeadBand
{
get
{
return _deadband;
}
set
{
_deadband = value;
}
}
protected ClientReader _plcReader;
public IDriver Parent
{
get
{
return _plcReader;
}
}
protected Dictionary<short, ITag> _items;
public IEnumerable<ITag> Items
{
get { return _items.Values; }
}
IDataServer _server;
public IDataServer Server
{
get
{
return _server;
}
}
Socket _tcpSend, _tcpRecive;
byte[] tcpBuffer;
IPAddress _addr;
public IPAddress RemoteAddress
{
get { return _addr; }
}
public ClientGroup(short id, string name, int updateRate, bool active, ClientReader plcReader)
{
this._id = id;
this._name = name;
this._updateRate = updateRate;
this._active = active;
this._plcReader = plcReader;
this._server = plcReader.Parent;
tcpBuffer = new byte[8192];
}
object sendasync = new object();
private byte[] ReadSingleData(DeviceAddress address, DataSource source = DataSource.Cache)
{
if (_tcpSend == null) return null;
short ID = (short)address.Start;
byte type = (byte)address.VarType;
byte len = (byte)(address.DataSize);
byte[] idbits = BitConverter.GetBytes(ID);
byte[] write_data = new byte[6] { FCTCOMMAND.fctHead, FCTCOMMAND.fctReadSingle,
source == DataSource.Cache?(byte)0:(byte)1, idbits[0], idbits[1] ,len};
byte[] data = new byte[len];
SocketError error;
lock (sendasync)
{
_tcpSend.Send(write_data, 0, 6, SocketFlags.None, out error);
int result = _tcpSend.Receive(tcpBuffer, 0, data.Length + 5, SocketFlags.None, out error);
}
Array.Copy(tcpBuffer, 5, data, 0, data.Length);
if (error == SocketError.Success)
return data;
else
{
return null;
}
}
private int WriteSingleData(DeviceAddress address, byte[] value)
{
if (_tcpSend == null) return -1;
short ID = (short)address.Start;
byte type = (byte)address.VarType;
byte[] idbits = BitConverter.GetBytes(ID);
byte[] write_data = new byte[6] { FCTCOMMAND.fctHead, FCTCOMMAND.fctWriteSingle, 1, idbits[0], idbits[1], (byte)(value.Length) };
byte[] data = new byte[6 + value.Length];
write_data.CopyTo(data, 0);
value.CopyTo(data, 6);
SocketError error;
lock (sendasync)
{
_tcpSend.Send(data, 0, data.Length, SocketFlags.None, out error);
_tcpSend.Receive(tcpBuffer, 0, 2, SocketFlags.None, out error);
}
if (error == SocketError.Success)
return tcpBuffer[1];//可在此处返回一个错误号
else
{
return (int)error;
}
}
public void Init()
{
if (_items != null && _tcpSend != null)
{
int len = 0;
List<ITag> tags = new List<ITag>();
foreach (var tag in _items.Values)
{
len += (3 + tag.Address.DataSize);
if (len >= tcpBuffer.Length - 10)
{
len = 0;
BatchRead(DataSource.Cache, true, tags.ToArray());
tags.Clear();
}
tags.Add(tag);
}
BatchRead(DataSource.Cache, true, tags.ToArray());
}
}
private void ReciveData()
{
if (!_active || _plcReader.tcpRecive == null) return;
byte[] bytes = new byte[ushort.MaxValue];
byte[] temp = new byte[ushort.MaxValue];
Storage value = Storage.Empty;
int start = 0;
SocketError error;
int result = 0;
do
{
if (!_tcpRecive.Connected || !_active) return;
try
{
result = _tcpRecive.Receive(bytes, 0, bytes.Length, SocketFlags.None, out error);
if (error == SocketError.Success)
{
List<HistoryData> historys = new List<HistoryData>(); ;
if (start != 0 && temp[0] == FCTCOMMAND.fctHead)
{
int j = 3;
if (start < 0)
{
Array.Copy(bytes, 0, temp, -start, 5 + start);
}
short tc = BitConverter.ToInt16(temp, j);//总字节数
if (start < 0)
start += tc;
Array.Copy(bytes, 0, temp, tc - start, start);
j += 2;
while (j < tc)
{
short id = BitConverter.ToInt16(temp, j);//标签ID、数据长度、数据值(T,L,V)
j += 2;
byte length = temp[j++];
ITag tag;
if (_items.TryGetValue(id, out tag))
{
//数据类型
switch (tag.Address.VarType)
{
case DataType.BOOL:
value.Boolean = BitConverter.ToBoolean(temp, j);
break;
case DataType.BYTE:
value.Byte = temp[j];
break;
case DataType.WORD:
value.Word = BitConverter.ToUInt16(temp, j);//需测试
break;
case DataType.SHORT:
value.Int16 = BitConverter.ToInt16(temp, j);//需测试
break;
case DataType.DWORD:
value.DWord = BitConverter.ToUInt32(temp, j);//需测试
break;
case DataType.INT:
value.Int32 = BitConverter.ToInt32(temp, j);//需测试
break;
case DataType.FLOAT:
value.Single = BitConverter.ToSingle(temp, j);
break;
case DataType.STR:
StringTag strTag = tag as StringTag;
if (strTag != null)
{
strTag.String = Encoding.ASCII.GetString(temp, j, length).Trim((char)0);
}
break;
default:
break;
}
j += length;
try
{
DateTime time = DateTime.FromFileTime(BitConverter.ToInt64(temp, j));
//tag.Update(value, time, QUALITIES.QUALITY_GOOD);
//if (historys != null)
historys.Add(new HistoryData(id, QUALITIES.QUALITY_GOOD, value, time));
}
catch (Exception exp)
{
}
j += 8;
}
else
j += length + 8;
}
}
byte head = bytes[start];
int count = start;
while (head == FCTCOMMAND.fctHead && result > count)
{
if (count + 5 > bytes.Length)
{
start = count - bytes.Length;
Array.Copy(bytes, count, temp, 0, -start);
break;
}
int j = count + 3;
short tc = BitConverter.ToInt16(bytes, j);//总标签数
count += tc;
if (count >= bytes.Length)
{
start = count - bytes.Length;
Array.Copy(bytes, count - tc, temp, 0, tc - start);
break;
}
else start = 0;
j += 2;
while (j < count)
{
short id = BitConverter.ToInt16(bytes, j);//标签ID、数据长度、数据值(T,L,V)
j += 2;
byte length = bytes[j++];
ITag tag;
if (_items.TryGetValue(id, out tag))
{
//数据类型
switch (tag.Address.VarType)
{
case DataType.BOOL:
value.Boolean = BitConverter.ToBoolean(bytes, j);
break;
case DataType.BYTE:
value.Byte = bytes[j];
break;
case DataType.WORD:
value.Word = BitConverter.ToUInt16(bytes, j);//需测试
break;
case DataType.SHORT:
value.Int16 = BitConverter.ToInt16(bytes, j);//需测试
break;
case DataType.DWORD:
value.DWord = BitConverter.ToUInt32(bytes, j);//需测试
break;
case DataType.INT:
value.Int32 = BitConverter.ToInt32(bytes, j);//需测试
break;
case DataType.FLOAT:
value.Single = BitConverter.ToSingle(bytes, j);
break;
case DataType.STR:
StringTag strTag = tag as StringTag;
if (strTag != null)
{
strTag.String = Encoding.ASCII.GetString(bytes, j, length).Trim((char)0);
}
break;
default:
break;
}
j += length;
try
{
DateTime time = DateTime.FromFileTime(BitConverter.ToInt64(bytes, j));
//tag.Update(value, time, QUALITIES.QUALITY_GOOD);
//if (historys != null)
historys.Add(new HistoryData(id, QUALITIES.QUALITY_GOOD, value, time));
}
catch (Exception exp)
{
}
j += 8;
}
else
j += length + 8;
}
head = bytes[count];
}
ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(this.OnRecieve), historys);
//if (DataChange != null && historys.Count > 0)
// DataChange(this, new DataChangeEventArgs(1, historys));
}
else if (error == SocketError.ConnectionReset || error == SocketError.Interrupted
|| error == SocketError.HostDown || error == SocketError.NetworkDown || error == SocketError.Shutdown)
{
_tcpRecive.Dispose();
return;
}
}
catch (Exception)
{
_tcpRecive.Dispose();
return;
}
}
while (result > 0);
try
{
_tcpRecive.Dispose();
}
catch (Exception)
{
}
}
private void OnRecieve(object stateInfo)
{
var historys = stateInfo as List<HistoryData>;
if (historys == null) return;
if (DataChange != null && historys.Count > 0)
DataChange(this, new DataChangeEventArgs(1, historys));
for (int i = 0; i < historys.Count; i++)
{
var data = historys[i];
ITag tag;
if (_items.TryGetValue(data.ID, out tag))
{
tag.Update(data.Value, data.TimeStamp, data.Quality);
}
}
}
public void OnUpdate(object stateInfo)
{
while (true)
{
Thread.Sleep(_updateRate);
lock (this)
{
if (!_active)
{
return;
}
Init();
}
}
}
public bool AddItems(IList<TagMetaData> items)
{
int count = items.Count;
if (_items == null) _items = new Dictionary<short, ITag>(count);
lock (_server.SyncRoot)
{
for (int i = 0; i < count; i++)
{
ITag dataItem = null;
TagMetaData meta = items[i];
DeviceAddress addr = new DeviceAddress(0, 0, 0, meta.ID, meta.Size, 0, meta.DataType);
switch (meta.DataType)
{
case DataType.BOOL:
dataItem = new BoolTag(meta.ID, addr, this);
break;
case DataType.BYTE:
dataItem = new ByteTag(meta.ID, addr, this);
break;
case DataType.WORD:
dataItem = new UShortTag(meta.ID, addr, this);
break;
case DataType.SHORT:
dataItem = new ShortTag(meta.ID, addr, this);
break;
case DataType.INT:
dataItem = new IntTag(meta.ID, addr, this);
break;
case DataType.DWORD:
dataItem = new UIntTag(meta.ID, addr, this);
break;
case DataType.FLOAT:
dataItem = new FloatTag(meta.ID, addr, this);
break;
case DataType.STR:
dataItem = new StringTag(meta.ID, addr, this);
break;
default:
dataItem = new BoolTag(meta.ID, addr, this);
break;
}
_items.Add(meta.ID, dataItem);
_server.AddItemIndex(meta.Name, dataItem);
}
}
//Init();
return true;
}
public bool AddTags(IEnumerable<ITag> tags)
{
if (_items == null)
{
_items = new Dictionary<short, ITag>();
}
foreach (ITag tag in tags)
{
if (tag != null)
{
_items.Add(tag.ID, tag);
}
}
//Init();
return true;
}
public bool RemoveItems(params ITag[] items)
{
foreach (var item in items)
{
_server.RemoveItemIndex(item.GetTagName());
_items.Remove(item.ID);
}
return true;
}
public bool SetActiveState(bool active, params short[] items)
{
return true;
}
public ITag FindItemByAddress(DeviceAddress addr)
{
ITag tag;
if (_items.TryGetValue((short)addr.Start, out tag))
return tag;
return _server[(short)addr.Start];
}
public HistoryData[] BatchRead(DataSource source, bool isSync, params ITag[] itemArray)
{
if (itemArray.Length == 0 || _tcpSend == null || !_tcpSend.Connected) return null;
short len = (short)itemArray.Length;
byte[] bt = new byte[2];
byte[] data = new byte[5 + len * 2];
int j = 0;
data[j++] = FCTCOMMAND.fctHead;
data[j++] = FCTCOMMAND.fctReadMultiple;
data[j++] = source == DataSource.Cache ? (byte)0 : (byte)1;
bt = BitConverter.GetBytes(len);
data[j++] = bt[0];
data[j++] = bt[1];
for (int i = 0; i < len; i++)
{
bt = BitConverter.GetBytes(itemArray[i].ID);
data[j++] = bt[0];
data[j++] = bt[1];
}
SocketError error;
lock (sendasync)
{
_tcpSend.Send(data, 0, data.Length, SocketFlags.None, out error);
int result = _tcpSend.Receive(tcpBuffer, 0, tcpBuffer.Length, SocketFlags.None, out error);
}
//!!!!此处的协议应注意,如批量读入的数据量超过缓存,必须分批合并;在协议头应加入总字节数,以和result比较是否需要循环读入。
j = 5;
if (error == SocketError.Success)
{
DateTime time = DateTime.Now;
HistoryData[] values = new HistoryData[len];
for (int i = 0; i < len; i++)
{
short id = BitConverter.ToInt16(tcpBuffer, j);
j += 2;
ITag tag = _server[id];
byte length = tcpBuffer[j++];
if (tag != null && length > 0)
{
switch (tag.Address.VarType)
{
case DataType.BOOL:
values[i].Value.Boolean = BitConverter.ToBoolean(tcpBuffer, j);
break;
case DataType.BYTE:
values[i].Value.Byte = tcpBuffer[j];
break;
case DataType.WORD:
values[i].Value.Word = BitConverter.ToUInt16(tcpBuffer, j);
break;
case DataType.SHORT:
values[i].Value.Int16 = BitConverter.ToInt16(tcpBuffer, j);
break;
case DataType.DWORD:
values[i].Value.DWord = BitConverter.ToUInt32(tcpBuffer, j);
break;
case DataType.INT:
values[i].Value.Int32 = BitConverter.ToInt32(tcpBuffer, j);
break;
case DataType.FLOAT:
values[i].Value.Single = BitConverter.ToSingle(tcpBuffer, j);
break;
case DataType.STR:
StringTag strTag = tag as StringTag;
if (strTag != null)
{
strTag.String = Encoding.ASCII.GetString(tcpBuffer, j, length).Trim();
}
break;
}
if (values[i].Value != tag.Value)
tag.Update(values[i].Value, time, QUALITIES.QUALITY_GOOD);
}
j += length;
}
return values;
}
else
return null;
}
public int BatchWrite(SortedDictionary<ITag, object> items, bool isSync = true)
{
if (_tcpSend == null || !_tcpSend.Connected) return -1;
List<byte> list = new List<byte>(new byte[] { FCTCOMMAND.fctHead, FCTCOMMAND.fctWriteMultiple });
list.AddRange(BitConverter.GetBytes((short)items.Count));
foreach (var item in items)
{
ITag tag = item.Key;
list.AddRange(BitConverter.GetBytes(tag.ID));
var addr = tag.Address;
if (addr.VarType != DataType.STR)
list.Add((byte)(addr.DataSize));//此处存疑
switch (addr.VarType)
{
case DataType.BOOL:
list.Add(Convert.ToBoolean(item.Value) ? (byte)1 : (byte)0);
break;
case DataType.BYTE:
list.Add(Convert.ToByte(item.Value));
break;
case DataType.WORD:
list.AddRange(BitConverter.GetBytes(Convert.ToUInt16(item.Value)));
break;
case DataType.SHORT:
list.AddRange(BitConverter.GetBytes(Convert.ToInt16(item.Value)));
break;
case DataType.DWORD:
list.AddRange(BitConverter.GetBytes(Convert.ToUInt32(item.Value)));
break;
case DataType.INT:
list.AddRange(BitConverter.GetBytes(Convert.ToInt32(item.Value)));
break;
case DataType.FLOAT:
list.AddRange(BitConverter.GetBytes(Convert.ToSingle(item.Value)));
break;
case DataType.STR:
var bts = Encoding.ASCII.GetBytes(Convert.ToString(item.Value));
list.Add((byte)bts.Length);
list.AddRange(bts);
break;
}
}
SocketError error;
lock (sendasync)
{
_tcpSend.Send(list.ToArray(), 0, list.Count, SocketFlags.None, out error);
_tcpSend.Receive(tcpBuffer, 0, 2, SocketFlags.None, out error);
}
if (error == SocketError.Success)
return tcpBuffer[1];
else
{
return (int)error;
}
}
public IEnumerable<HistoryData> SendHdaRequest(DateTime start, DateTime end)
{
if (_tcpSend == null || !_tcpSend.Connected) yield break;
byte[] hdaReq = new byte[18];
hdaReq[0] = FCTCOMMAND.fctHead;
hdaReq[1] = FCTCOMMAND.fctHdaRequest;
byte[] startbuffer = BitConverter.GetBytes(start.ToFileTime());
startbuffer.CopyTo(hdaReq, 2);
byte[] endbuffer = BitConverter.GetBytes(end.ToFileTime());
endbuffer.CopyTo(hdaReq, 10);
SocketError error;
HistoryData data = HistoryData.Empty;
short tempid = short.MinValue;
byte[] temp = new byte[14];
ITag tag = null;
int index = 0;
int size = 0;
int result = 0;
short id = 0;
lock (sendasync)
{
_tcpSend.Send(hdaReq);
do
{
result = _tcpSend.Receive(tcpBuffer, 0, tcpBuffer.Length, SocketFlags.None, out error);
if (error == SocketError.ConnectionReset || error == SocketError.Interrupted || error == SocketError.HostDown || error == SocketError.NetworkDown || error == SocketError.Shutdown)
{
_tcpSend.Dispose();
yield break;
}
if (index != 0)
{
Array.Copy(tcpBuffer, 0, temp, 14 - index, index);
id = BitConverter.ToInt16(temp, 0);
tempid = id;
tag = _server[id];
if (tag == null) yield break;
data.ID = id;
size = tag.Address.DataSize;
index -= (4 - size);
switch (tag.Address.VarType)
{
case DataType.BOOL:
data.Value.Boolean = BitConverter.ToBoolean(temp, 2);
break;
case DataType.BYTE:
data.Value.Byte = tcpBuffer[index];
break;
case DataType.WORD:
data.Value.Word = BitConverter.ToUInt16(temp, 2);
break;
case DataType.SHORT:
data.Value.Int16 = BitConverter.ToInt16(temp, 2);
break;
case DataType.DWORD:
data.Value.DWord = BitConverter.ToUInt32(temp, 2);
break;
case DataType.INT:
data.Value.Int32 = BitConverter.ToInt32(temp, 2);
break;
case DataType.FLOAT:
data.Value.Single = BitConverter.ToSingle(temp, 2);
break;
}
long fileTime = BitConverter.ToInt64(temp, 2 + size);
if (fileTime == -1) yield break;
data.TimeStamp = DateTime.FromFileTime(fileTime);
yield return data;
}
while (result >= index + 2)
{
id = BitConverter.ToInt16(tcpBuffer, index);
if (tempid != id)
{
tempid = id;
tag = _server[id];
if (tag == null) yield break;
size = tag.Address.DataSize;
}
if (index + 10 + size > result)
break;
data.ID = id;
index += 2;
switch (tag.Address.VarType)
{
case DataType.BOOL:
data.Value.Boolean = BitConverter.ToBoolean(tcpBuffer, index);
break;
case DataType.BYTE:
data.Value.Byte = tcpBuffer[index];
break;
case DataType.WORD:
data.Value.Word = BitConverter.ToUInt16(tcpBuffer, index);
break;
case DataType.SHORT:
data.Value.Int16 = BitConverter.ToInt16(tcpBuffer, index);
break;
case DataType.DWORD:
data.Value.DWord = BitConverter.ToUInt32(tcpBuffer, index);
break;
case DataType.INT:
data.Value.Int32 = BitConverter.ToInt32(tcpBuffer, index);
break;
case DataType.FLOAT:
data.Value.Single = BitConverter.ToSingle(tcpBuffer, index);
break;
}
index += size;
long fileTime = BitConverter.ToInt64(tcpBuffer, index);
if (fileTime == -1) yield break;
data.TimeStamp = DateTime.FromFileTime(fileTime);
index += 8;
yield return data;
}
if (index == result)
index = 0;
else
{
Array.Copy(tcpBuffer, index, temp, 0, result - index);
index += 14 - result;
}
} while (result > 0);
}
yield break;
}
public IEnumerable<HistoryData> SendHdaRequest(DateTime start, DateTime end, short id)
{
if (_tcpSend == null || !_tcpSend.Connected) yield break;
ITag tag = _server[id];
if (tag == null) yield break;
byte[] hdaReq = new byte[20];
hdaReq[0] = FCTCOMMAND.fctHead;
hdaReq[1] = FCTCOMMAND.fctHdaIdRequest;
byte[] startbuffer = BitConverter.GetBytes(start.ToFileTime());
startbuffer.CopyTo(hdaReq, 2);
byte[] endbuffer = BitConverter.GetBytes(end.ToFileTime());
endbuffer.CopyTo(hdaReq, 10);
byte[] idbuffer = BitConverter.GetBytes(id);
idbuffer.CopyTo(hdaReq, 18);
SocketError error;
int index = 0;
HistoryData data = HistoryData.Empty;
data.ID = id;
int result = 0;
lock (sendasync)
{
_tcpSend.Send(hdaReq);
switch (tag.Address.VarType)
{
case DataType.FLOAT:
do
{
result = _tcpSend.Receive(tcpBuffer, 0, tcpBuffer.Length, SocketFlags.None, out error);
if (error == SocketError.ConnectionReset || error == SocketError.Interrupted || error == SocketError.HostDown || error == SocketError.NetworkDown || error == SocketError.Shutdown)
{
_tcpSend.Dispose();
yield break;
}
while (index + 12 <= result)
{
data.Value.Single = BitConverter.ToSingle(tcpBuffer, index);//未来可考虑量程转换和其他数据类型
index += 4;
long fileTime = BitConverter.ToInt64(tcpBuffer, index);
if (fileTime == -1) yield break;
data.TimeStamp = DateTime.FromFileTime(fileTime);
index += 8;
yield return data;
}
if (index == result)
index = 0;
else
index += 12 - result;//丢弃一个值
} while (result > 0);
break;
case DataType.SHORT:
do
{
result = _tcpSend.Receive(tcpBuffer, 0, tcpBuffer.Length, SocketFlags.None, out error);