AIOBOX.cs
26.6 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
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Asa.IOModule
{
/// <summary>
/// 零点IO模块操作类
/// </summary>
public class AIOBOX
{
private string LogName {
get { return "AIOBOX [" + IP + "]"; }
}
/// <summary>
/// 自动读取DI委托
/// </summary>
/// <param name="box">AIOBOX</param>
/// <param name="sta">所有DI状态</param>
public delegate void DIO_Changed(AIOBOX box, Box_Sta[] sta);
/// <summary>
/// 自动读取DI事件触发
/// </summary>
public event DIO_Changed DI_Changed_Event;
/// <summary>
/// 自动读取DO事件触发
/// </summary>
public event DIO_Changed DO_Changed_Event;
private Socket _client; //客户端
private bool _loop;
private ushort _uid;
private Box_Sta[] _stateDI; //DI状态
private Box_Sta[] _stateDO; //DO状态
private int[] _valueAI; //AI模拟量
private int[] _valueAO; //AO模拟量
private List<byte> _receive;
private System.Collections.Concurrent.ConcurrentQueue<byte[]> _writeDO;
private log4net.ILog log;
private readonly Box_Type _typeInput; //输入类型
private readonly Box_Type _typeOutput; //输出类型
private readonly byte[] _addressInput; //输入地址
private readonly byte[] _addressOutput; //输出地址
private const int SEND_SLEEP = 60; //每条命令发送的间隔,不能小于15,会出现IO接收不到的情况,小于30时,会出现接收数据连包的情况
private const int PORT = 502; //端口
private const int UPLOAD_TIME = 3000; //8秒
private Thread tRecon; //重连线程
private Thread tSend; //发送命令处理
private Thread tListen; //监听网络
private UdpClient broadcastClient; //广播客户端
private IPEndPoint broadcastEndPoint; //广播远程节点
private byte[] broadcastBuffer; //远程返回数据
/// <summary>
/// 零点IO模块操作类
/// </summary>
/// <param name="input">输入类型</param>
/// <param name="inputCount">输入数量</param>
/// <param name="output">输出类型</param>
/// <param name="outputCount">输出数量</param>
public AIOBOX(Box_Type input, int inputCount, Box_Type output, int outputCount)
{
_typeInput = input;
_typeOutput = output;
log = log4net.LogManager.GetLogger("AIOBOX");
byte n = 0;
_addressInput = new byte[inputCount];
for (int i = 0; i < inputCount; i++)
_addressInput[i] = n++;
_addressOutput = new byte[outputCount];
for (int i = 0; i < outputCount; i++)
_addressOutput[i] = n++;
_stateDI = new Box_Sta[inputCount];
_stateDO = new Box_Sta[outputCount];
_valueAI = new int[inputCount];
_valueAO = new int[outputCount];
}
/// <summary>
/// IP地址
/// </summary>
public string IP { set; get; } = "192.168.1.100";
/// <summary>
/// 输入主动上传
/// </summary>
public bool Upload { set; get; } = false;
/// <summary>
/// 是否连接
/// </summary>
public bool IsConn { get; private set; } = false;
/// <summary>
/// 错误信息
/// </summary>
public string ErrInfo { get; private set; } = "";
/// <summary>
/// 监控DI输入,索引数组
/// </summary>
public int[] MonitorDI { get; set; }
/// <summary>
/// 监控DO输出,索引数组
/// </summary>
public int[] MonitorDO { get; set; }
/// <summary>
/// 连接
/// </summary>
public void Connect()
{
_loop = true;
_uid = 0;
IsConn = false;
_receive = new List<byte>();
_writeDO = new System.Collections.Concurrent.ConcurrentQueue<byte[]>();
tRecon = new Thread(new ThreadStart(Reconn));
tSend = new Thread(new ThreadStart(Send));
tListen = new Thread(new ThreadStart(Listen));
tRecon.Start();
tSend.Start();
tListen.Start();
log.Info(LogName+ "Connect");
}
/// <summary>
/// 关闭连接
/// </summary>
public void Close()
{
_loop = false;
IsConn = false;
try
{
if (_client != null)
{
_client.Shutdown(SocketShutdown.Both);
_client.Close();
}
log.Info(LogName+ "Close");
}
catch (Exception ex)
{
log.Error(LogName+ "Close", ex);
}
finally
{
_client = null;
}
}
/// <summary>
/// 相反状态(ON/OFF)
/// </summary>
/// <param name="sta"></param>
/// <returns></returns>
public Box_Sta ReverseStatus(Box_Sta sta)
{
return sta == Box_Sta.On ? Box_Sta.Off : Box_Sta.On;
}
/// <summary>
/// 相反状态(ON/OFF)
/// </summary>
/// <param name="sta"></param>
public void ReverseStatus(ref Box_Sta sta)
{
if (sta == Box_Sta.On)
sta = Box_Sta.Off;
else
sta = Box_Sta.On;
}
/// <summary>
/// 读取单个DI输入状态(ON/OFF)
/// </summary>
/// <param name="add">输入地址,从0开始</param>
/// <returns></returns>
public Box_Sta ReadDI(int add)
{
return _stateDI[add];
}
/// <summary>
/// 读取多个DI输入状态(ON/OFF)
/// </summary>
/// <param name="add">起始地址,从0开始</param>
/// <param name="count">数量</param>
/// <returns></returns>
public Box_Sta[] ReadDI(int add, int count)
{
Box_Sta[] sta = new Box_Sta[count];
Array.Copy(_stateDI, add, sta, 0, count);
return sta;
}
/// <summary>
/// 读取单个AI模拟量的值
/// </summary>
/// <param name="add">模拟量地址,从0开始</param>
/// <returns></returns>
public int ReadAI(int add)
{
return _valueAI[add];
}
/// <summary>
/// 读取多个AI模拟量的值
/// </summary>
/// <param name="add">起始地址,从0开始</param>
/// <param name="count">数量</param>
/// <returns></returns>
public int[] ReadAI(int add, int count)
{
int[] sta = new int[count];
Array.Copy(_valueAI, add, sta, 0, count);
return sta;
}
/// <summary>
/// 读取单个DO输出状态(ON/OFF)
/// </summary>
/// <param name="add">输出地址,从0开始</param>
/// <returns></returns>
public Box_Sta ReadDO(int add)
{
return _stateDO[add];
}
/// <summary>
/// 读取多个DO输出状态(ON/OFF)
/// </summary>
/// <param name="add">起始地址,从0开始</param>
/// <param name="count">数量</param>
/// <returns></returns>
public Box_Sta[] ReadDO(int add, int count)
{
Box_Sta[] sta = new Box_Sta[count];
Array.Copy(_stateDO, add, sta, 0, count);
return sta;
}
/// <summary>
/// 读取单个AO模拟量的值
/// </summary>
/// <param name="add">输出地址,从0开始</param>
/// <returns></returns>
public int ReadAO(int add)
{
return _valueAO[add];
}
/// <summary>
/// 读取多个AO模拟量的值
/// </summary>
/// <param name="add">起始地址,从0开始</param>
/// <param name="count">数量</param>
/// <returns></returns>
public int[] ReadAO(int add, int count)
{
int[] sta = new int[count];
Array.Copy(_valueAO, add, sta, 0, count);
return sta;
}
/// <summary>
/// 写入单个DO输出状态(ON/OFF)
/// </summary>
/// <param name="add">输出地址,从0开始</param>
/// <param name="sta"></param>
/// <returns></returns>
public bool WriteDO(int add, Box_Sta sta)
{
try
{
if (!IsConn)
{
LogUtil.error(LogName + "WriteDO Fail : IsConn= "+ IsConn);
log.Error(LogName + "WriteDO Fail : IsConn= " + IsConn);
return false;
}
log.Info(LogName+ "call WriteDO");
byte[] data = Command();
byte[] buff = new byte[12];
Array.Copy(data, 0, buff, 0, data.Length);
buff[5] = 6; //后面字节数
buff[7] = 5; //功能码
buff[9] = _addressOutput[add]; //地址
buff[10] = (byte)sta; //写入值
//_writeDO.Enqueue(buff);
return SendToDevice(buff);
}
catch (Exception ex)
{
LogUtil.error(LogName + "WriteDO ", ex);
log.Error(LogName+ "WriteDO ", ex);
return false;
}
}
/// <summary>
/// 发送命令线程
/// </summary>
private void Send()
{
bool shift = true; //切换
int time = 0; //上传时间
int writeTimer = 0; //写入DO次数
bool writeStop = false; //写入命令停止
while (_loop)
{
Thread.Sleep(SEND_SLEEP);
if (!IsConn) continue;
byte[] buff = null;
if (Upload) //主动上传
{
if (time >= UPLOAD_TIME)
{
buff = GetReadDI_Command();
time = 0;
}
//else
//{
// if (writeTimer >= 3) //连续发送WriteDO3次,强制发送DO
// {
// buff = GetReadDO_Command();
// writeTimer = 0;
// }
// else
// {
// if (_writeDO.TryDequeue(out buff))
// {
// writeTimer++;
// }
// else
// {
// buff = GetReadDO_Command();
// writeTimer = 0;
// }
// }
//}
time += SEND_SLEEP;
}
else
{
if (writeTimer >= 3) //连续发送WriteDO3次,强制发送DI和DO
{
if (shift)
buff = GetReadDI_Command();
else
buff = GetReadDO_Command();
shift = !shift;
if (writeStop)
writeTimer = 0;
else
writeStop = true;
}
else
{
if (_writeDO.TryDequeue(out buff))
{
writeTimer++;
writeStop = false;
}
else
{
//if (shift)
// buff = GetReadDI_Command();
//else
// buff = GetReadDO_Command();
shift = !shift;
writeTimer = 0;
}
}
}
if (buff != null)
{
SendToDevice(buff);
}
}
}
private bool SendToDevice(byte[] buff)
{
try
{
_client.Send(buff);
log.Debug(LogName+ "Send: " + HexBuff(buff));
return true;
}
catch (Exception ex)
{
LogUtil.error(LogName + "Send Error Socket Close", ex);
log.Error(LogName+ "Send Error,Socket Close ", ex);
IsConn = false;
}
return false;
}
/// <summary>
/// 获取ReadDI的命令
/// </summary>
/// <returns></returns>
private byte[] GetReadDI_Command()
{
byte[] data = Command();
byte[] buff = new byte[12];
Array.Copy(data, 0, buff, 0, data.Length);
buff[5] = 6; //后面字节数
//功能码
if (_typeInput == Box_Type.DI)
buff[7] = 2;
else if (_typeInput == Box_Type.AI)
buff[7] = 4;
buff[9] = _addressInput[0]; //地址
buff[11] = (byte)_addressInput.Length; //个数
return buff;
}
/// <summary>
/// 获取ReadDO的命令
/// </summary>
/// <returns></returns>
private byte[] GetReadDO_Command()
{
byte[] data = Command();
byte[] buff = new byte[12];
Array.Copy(data, 0, buff, 0, data.Length);
buff[5] = 6; //后面字节数
buff[7] = 1; //功能码
buff[9] = _addressOutput[0]; //地址
buff[11] = (byte)_addressOutput.Length; //个数
return buff;
}
/// <summary>
/// 监听网络线程
/// </summary>
private void Listen()
{
int index = 0;
while (_loop)
{
Thread.Sleep(10);
if (!IsConn) continue;
if (_client == null) continue;
try
{
if (_client.Available > 0)
{
byte[] buff = new byte[_client.ReceiveBufferSize];
int count = _client.Receive(buff);
byte[] temp = new byte[count];
Array.Copy(buff, 0, temp, 0, count);
// lock (_receive)
{
_receive.AddRange(temp);
while (_receive.Count > 6) //分解连包
{
int len = _receive[5] + 6;
if (len > _receive.Count) break;
byte[] cmd = new byte[len];
_receive.CopyTo(0, cmd, 0, len);
_receive.RemoveRange(0, len);
index++;
log.Debug(LogName+ "Receive: " + HexBuff(cmd));
if (IP.Equals("192.168.101.22") && cmd.Length>7&& (cmd[7] == 2))
{
LogUtil.LOGGER.Debug(LogName + " Listen 收到数据 ["+index+"] " + HexBuff(cmd));
}
CommandProcess(cmd, index);
// System.Threading.Tasks.Task.Run(() => CommandProcess(cmd, index));
}
}
}
}
catch (Exception ex)
{
LogUtil.error(LogName + "Listen ",ex);
log.Error(LogName+ "Listen ", ex);
IsConn = false;
}
}
}
/// <summary>
/// 接收到的命令处理方法,(task多线程)
/// </summary>
/// <param name="cmd"></param>
private void CommandProcess(byte[] cmd,int index)
{
string str;
int idx = 0;
int count = cmd[8];
try
{
if (cmd[7] == 1) //ReadDO
{
Box_Sta[] staDO = new Box_Sta[_stateDO.Length];
// lock (_stateDO)
{
for (int i = 1; i <= count; i++)
{
int move = 0;
byte val = cmd[8 + i];
for (int j = 0; j < 8; j++) //字节的0-7位
{
int n = (val & Convert.ToInt32(Math.Pow(2, move))) >> move;
staDO[idx++] = n == 1 ? Box_Sta.On : Box_Sta.Off;
move++;
}
}
Array.Copy(staDO, 0, _stateDO, 0, staDO.Length);
if (MonitorDO != null)
{
str = "MonitorDO ";
for (int i = 0; i < MonitorDO.Length; i++)
str += string.Format("[{0}]{1} ", MonitorDO[i], _stateDO[MonitorDO[i]].ToString());
log.Info(LogName+ str);
}
}
DO_Changed_Event?.Invoke(this, staDO);
}
else if (cmd[7] == 2) //ReadDI
{
Box_Sta[] staDI = new Box_Sta[_stateDI.Length];
// lock (_stateDI)
{
for (int i = 1; i <= count; i++)
{
int move = 0;
byte val = cmd[8 + i];
for (int j = 0; j < 8; j++) //字节的0-7位
{
int n = (val & Convert.ToInt32(Math.Pow(2, move))) >> move;
staDI[idx++] = n == 1 ? Box_Sta.On : Box_Sta.Off;
move++;
}
}
Array.Copy(staDI, 0, _stateDI, 0, staDI.Length);
if (MonitorDI != null)
{
str = "MonitorDI ";
for (int i = 0; i < MonitorDI.Length; i++)
str += string.Format("[{0}]{1} ", MonitorDI[i], _stateDI[MonitorDI[i]].ToString());
log.Info(LogName+ str);
}
}
if (IP.Equals("192.168.101.22"))
{
string msg = "";
foreach (Box_Sta s in staDI)
{
msg += " " + (int)s;
}
LogUtil.LOGGER.Debug(LogName + " DI_Changed_Event ["+index+"] " + msg);
}
DI_Changed_Event?.Invoke(this, staDI);
}
else if (cmd[7] == 5)
{
idx = Array.FindIndex(_addressOutput, s => s == cmd[9]);
if (idx != -1)
{
Box_Sta[] staDO = new Box_Sta[_stateDO.Length];
_stateDO[idx] = cmd[10] == 0xFF ? Box_Sta.On : Box_Sta.Off;
Array.Copy(_stateDO, staDO, staDO.Length);
DO_Changed_Event?.Invoke(this, staDO);
//System.Threading.Tasks.Task.Run(() => DO_Changed_Event?.Invoke(this, staDO));
}
}
}
catch (Exception ex)
{
LogUtil.error(LogName + "CommandProcess ", ex);
ErrInfo = ex.Message;
}
}
/// <summary>
/// 重连线程
/// </summary>
private void Reconn()
{
while (_loop)
{
if (IsConn)
{
Thread.Sleep(1000);
}
else
{
Thread.Sleep(100);
if (_loop) Open();
}
}
}
/// <summary>
/// 打开socket建立连接
/// </summary>
private void Open()
{
try
{
IsConn = false;
bool rtn = CheckIP(IP);
if (!rtn) return;
//建立连接
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
_client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
_client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
_client.Connect(IPAddress.Parse(IP), PORT);
Thread.Sleep(100); //需要等待一会才能获取连接状态
IsConn = true;
byte[] buff = GetReadDI_Command();
SendToDevice(buff);
buff = GetReadDO_Command();
SendToDevice(buff);
LogUtil.error(LogName+ "Socket Connect OK");
log.Info(LogName + "Socket Connect OK");
}
catch (Exception ex)
{
IsConn = false;
log.Error(LogName + "Open ", ex);
LogUtil.error(LogName + "Open ", ex);
}
}
/// <summary>
/// 检查IP地址
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
private bool CheckIP(string ip)
{
//IP合法
string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
bool rtn = System.Text.RegularExpressions.Regex.IsMatch(ip, pattern);
if (!rtn)
{
ErrInfo = "非法的IP地址";
return false;
}
//Ping服务端
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply result = ping.Send(ip, 1000);
ping.Dispose();
if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
{
ErrInfo = "Ping " + ip + " 请求没有响应";
return false;
}
return true;
}
/// <summary>
/// 自动获取IP地址,未连接前使用,必须在同一网段
/// </summary>
/// <param name="localIP">本地IP地址</param>
/// <returns></returns>
private bool AutoIP(string localIP)
{
try
{
IPEndPoint local = new IPEndPoint(IPAddress.Parse(localIP), 55654);
broadcastClient = new UdpClient(local);
broadcastBuffer = null;
Thread tTemp = new Thread(new ThreadStart(GetIP));
tTemp.Start();
broadcastEndPoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1024);
byte[] dgram = new byte[] { 0x05, 0x00, 0x07, 0x00, 0x00, 0xC1, 0x59 };
broadcastClient.Send(dgram, dgram.Length, broadcastEndPoint);
Thread.Sleep(1000);
tTemp.Abort();
broadcastClient.Close();
ErrInfo = "无法访问";
if (broadcastBuffer == null) return false;
if (broadcastBuffer[0] != 0x3B) return false;
byte[] buff = new byte[broadcastBuffer[7]];
Array.Copy(broadcastBuffer, 9, buff, 0, buff.Length);
IP = buff[buff.Length - 12] + "." + buff[buff.Length - 11] + "." + buff[buff.Length - 10] + "." + buff[buff.Length - 9];
ErrInfo = "OK";
return true;
}
catch (Exception ex)
{
ErrInfo = ex.Message;
LogUtil.error(LogName + "AutoIP ", ex);
return false;
}
}
/// <summary>
/// 获取IO模块IP地址
/// </summary>
private void GetIP()
{
broadcastBuffer = broadcastClient.Receive(ref broadcastEndPoint);
}
/// <summary>
/// 命令,前7个字节
/// </summary>
/// <returns></returns>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
private byte[] Command()
{
byte[] flag = BitConverter.GetBytes(++_uid);
if (_uid == ushort.MaxValue) _uid = 0;
byte[] data = new byte[7];
data[0] = flag[1];
data[1] = flag[0];
data[2] = 0;
data[3] = 0;
data[4] = 0;
data[5] = 0;
data[6] = 255;
return data;
}
private string HexBuff(byte[] buff)
{
string s = "";
if (buff == null) return s;
for (int i = 0; i < buff.Length; i++)
s += buff[i].ToString("X2") + " ";
return s;
}
}
/// <summary>
/// IO模块类型
/// </summary>
public enum Box_Type : int
{
/// <summary>
/// 数字信号输入
/// </summary>
DI,
/// <summary>
/// 数字信号输出
/// </summary>
DO,
/// <summary>
/// 模拟量输入
/// </summary>
AI,
/// <summary>
/// 模拟量输出
/// </summary>
AO
}
/// <summary>
/// IO模块寄存器状态
/// </summary>
public enum Box_Sta : int
{
/// <summary>
/// 断开,关闭,低电平
/// </summary>
Off = 0,
/// <summary>
/// 闭合,打开,高电平
/// </summary>
On = 255
}
}