ABB.cs
23.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
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
using System.Net;
using System.Net.Sockets;
using System;
using System.Threading;
using System.Collections.Generic;
using AssemblyLine;
using System.Text;
using ABB.Robotics.Controllers.Discovery;
using ABB.Robotics.Controllers;
using ABB.Robotics.Controllers.IOSystemDomain;
using System.Diagnostics;
namespace BLL
{
public class ABB
{
private bool loop;
private string[] cmd;
private int start;
private int end;
private Socket server;
private Thread tListenClient; //监听客户端连接
private Thread tStatus;
private Client[] _client; //所有客户端
private Asa.File.Log log;
private Thread tMultitask;
private System.Collections.Concurrent.ConcurrentQueue<string> _receive1;
private System.Collections.Concurrent.ConcurrentQueue<string> _receive2;
private System.Collections.Concurrent.ConcurrentQueue<string> _receive3;
private NetworkScanner scanner = null;
private NetworkWatcher networkwatcher = null;
public delegate void StatusEvent(int idx, string sta);
public event StatusEvent StatusChanged;
public event StatusEvent ServerChanged;
public ABB()
{
_receive1 = new System.Collections.Concurrent.ConcurrentQueue<string>();
_receive2 = new System.Collections.Concurrent.ConcurrentQueue<string>();
_receive3 = new System.Collections.Concurrent.ConcurrentQueue<string>();
PutStart = new bool[3] { false, false, false };
PutIn = new bool[3] { false, false, false };
PutEnd = new bool[3] { true, true, true };
GetStart = new bool[3] { false, false, false };
GetEnd = new bool[3] { true, true, true };
log = new Asa.File.Log(Common.LOG_PATH, "ABB");
log.OutString("=====程序启动=====");
cmd = new string[Common.ABB_Dev.Length];
_client = new Client[Common.ABB_Dev.Length];
for (int i = 0; i < _client.Length; i++)
_client[i] = new Client(Common.ABB_Dev[i].IP);
}
/// <summary>
/// 停止多个任务
/// </summary>
public bool StopMultitask { set; get; } = false;
/// <summary>
/// Put指令开始
/// </summary>
public bool[] PutStart { private set; get; }
/// <summary>
/// Put指令已放入,但未结束
/// </summary>
public bool[] PutIn { private set; get; }
/// <summary>
/// 整个Put指令已完成
/// </summary>
public bool[] PutEnd { private set; get; }
/// <summary>
/// Get指令开始
/// </summary>
public bool[] GetStart { private set; get; }
/// <summary>
/// 整个Get指令已完成
/// </summary>
public bool[] GetEnd { private set; get; }
public void Start()
{
LoadController();
OpenServer();
}
public void Exit()
{
loop = false;
if (_client != null)
{
for (int i = 0; i < _client.Length; i++)
{
_client[i].Loop = false;
_client[i].IsConn = false;
//if (_client[i].Receive != null)
// _client[i].Receive.Abort();
if (_client[i].Socket != null)
_client[i].Socket.Close();
}
}
if (server != null)
{
server.Close();
}
log.OutString("=====程序关闭=====\r\n");
log.Dispose();
}
//public bool MovePut(int idx, string point)
//{
// string RFID;
// if (idx == 2)
// RFID = Common.line_Double.Place2RFID.ToLower();
// else
// RFID = Common.line_Double.Place1RFID.ToLower();
// point = RFID[0] + point;
// string s = string.Format("{0},{1},{2},{3}", Common.ABB_MOVEPUT, point, "L", Common.config["ABB" + (idx + 1) + "_Speed"]);
// if (s.Equals(cmd[idx]))
// {
// bool rtn = false;
// string result = "";
// if (idx == 0)
// rtn = _receive1.TryDequeue(out result);
// else if (idx == 1)
// rtn = _receive2.TryDequeue(out result);
// else if (idx == 2)
// rtn = _receive3.TryDequeue(out result);
// if (rtn)
// {
// if (result.Contains(point))
// {
// cmd[idx] = "";
// log.OutInfo(Common.ABB_Dev[idx].ToString("MovePut Receive"));
// return true;
// }
// else
// return false;
// }
// else
// return false;
// }
// else
// {
// cmd[idx] = s;
// SendCommand(idx, s);
// log.OutInfo(Common.ABB_Dev[idx].ToString("MovePut Send"));
// return false;
// }
//}
//public bool MoveGet(int idx, string point)
//{
// string s = string.Format("{0},{1},{2},{3}", Common.ABB_MOVEGET, point, "L", Common.config["ABB" + (idx + 1) + "_Speed"]);
// if (s.Equals(cmd[idx]))
// {
// bool rtn = false;
// string result = "";
// if (idx == 0)
// rtn = _receive1.TryDequeue(out result);
// else if (idx == 1)
// rtn = _receive2.TryDequeue(out result);
// else if (idx == 2)
// rtn = _receive3.TryDequeue(out result);
// if (rtn)
// {
// if (result.Contains(point))
// {
// cmd[idx] = "";
// log.OutInfo(Common.ABB_Dev[idx].ToString("MoveGet Receive"));
// return true;
// }
// else
// return false;
// }
// else
// return false;
// }
// else
// {
// cmd[idx] = s;
// SendCommand(idx, s);
// log.OutInfo(Common.ABB_Dev[idx].ToString("MoveGet Send"));
// return false;
// }
//}
public void SendCommand(int idx, string s)
{
if (!_client[idx].IsConn) return;
try
{
byte[] buff = Encoding.ASCII.GetBytes(s);
_client[idx].Socket.Send(buff);
log.OutInfo(Common.ABB_Dev[idx].Name + " Send " + s);
}
catch (Exception ex)
{
log.OutError(ex);
}
}
public void Multitask(int idx, string s, int p1, int p2)
{
cmd[idx] = s;
start = p1;
end = p2;
StopMultitask = false;
tMultitask = new Thread(new ParameterizedThreadStart(Multitask));
tMultitask.Start(idx);
}
/// <summary>
/// Get指令
/// </summary>
/// <param name="idx">机器人索引号</param>
/// <param name="point">架位,带p</param>
/// <param name="speed">速度</param>
public void MoveGet(int idx, string point, string speed)
{
point = point.ToLower();
string s = string.Format("{0},{1},{2},{3}", Common.ABB_MOVEGET, point, "L", speed);
GetStart[idx] = true;
GetEnd[idx] = false;
SendCommand(idx, s);
log.OutInfo(Common.ABB_Dev[idx].Name + " MoveGet Start");
}
/// <summary>
/// Put指令
/// </summary>
/// <param name="idx">机器人索引号</param>
/// <param name="point">架位,带c/d</param>
/// <param name="speed">速度</param>
public void MovePut(int idx, string point, string speed)
{
string s = string.Format("{0},{1},{2},{3}", Common.ABB_MOVEPUT, point, "L", speed);
PutStart[idx] = true;
PutIn[idx] = false;
PutEnd[idx] = false;
SendCommand(idx, s);
log.OutInfo(Common.ABB_Dev[idx].Name + " MovePut Start");
}
private void StartDevice(int idx)
{
try
{
if (idx < 0 && idx >= _client.Length)
{
log.OutInfo("Start _client[" + idx + "] 超出范围");
}
else if (_client[idx].Ctl == null)
{
log.OutInfo(Common.ABB_Dev[idx].ToString(" 没有连接"));
}
else
{
if (_client[idx].IsConn)
{
log.OutInfo(Common.ABB_Dev[idx].ToString(" 已经打开"));
}
else
{
Signal signal = _client[idx].Ctl.IOSystem.GetSignal("di_start");
((DigitalSignal)signal).Set();
Thread.Sleep(100);
((DigitalSignal)signal).Reset();
Common.ABB_Dev[idx].IsOpen = true;
log.OutInfo(Common.ABB_Dev[idx].ToString(" 打开设备"));
}
}
}
catch (Exception ex)
{
log.OutError(ex);
}
}
private void StopDevice(int idx)
{
try
{
if (idx < 0 && idx >= _client.Length)
{
log.OutInfo("Stop _client[" + idx + "] 超出范围");
}
else if (_client[idx].Ctl == null)
{
log.OutInfo(Common.ABB_Dev[idx].ToString(" 没有连接"));
}
else
{
Signal signal = _client[idx].Ctl.IOSystem.GetSignal("di_stop");
((DigitalSignal)signal).Set();
Thread.Sleep(100);
((DigitalSignal)signal).Reset();
Thread.Sleep(100);
Common.ABB_Dev[idx].IsOpen = false;
if (tMultitask != null) tMultitask.Abort();
_client[idx].IsConn = false;
_client[idx].Loop = false;
_client[idx].Socket.Close();
ServerChanged?.Invoke(idx, "关闭");
log.OutInfo(Common.ABB_Dev[idx].ToString(" 关闭"));
}
}
catch (Exception ex)
{
log.OutError(ex);
}
}
private void Multitask(object obj)
{
int idx = (int)obj;
if (!_client[idx].IsConn) return;
string s;
if (start < end)
{
for (int i = start; i <= end; i++)
{
try
{
s = string.Format(cmd[idx], i);
byte[] buff = Encoding.ASCII.GetBytes(s);
_client[idx].Socket.Send(buff);
log.OutInfo(Common.ABB_Dev[idx].ToString("Send ") + s);
}
catch (Exception ex)
{
log.OutError(ex);
break;
}
while (true)
{
bool rtn = false;
string result = "";
if (idx == 0)
rtn = _receive1.TryDequeue(out result);
else if (idx == 1)
rtn = _receive2.TryDequeue(out result);
else if (idx == 2)
rtn = _receive3.TryDequeue(out result);
if (rtn)
{
log.OutInfo(Common.ABB_Dev[idx].ToString("Receive Multitask ") + s);
if (result.Contains("p" + i))
break;
}
Thread.Sleep(1000);
}
if (StopMultitask)
{
StopMultitask = false;
break;
}
}
}
else
{
for (int i = start; i >= end; i--)
{
try
{
s = string.Format(cmd[idx], i);
byte[] buff = Encoding.ASCII.GetBytes(s);
_client[idx].Socket.Send(buff);
log.OutInfo(Common.ABB_Dev[idx].ToString("Send ") + s);
}
catch (Exception ex)
{
log.OutError(ex);
break;
}
while (true)
{
bool rtn = false;
string result = "";
if (idx == 0)
rtn = _receive1.TryDequeue(out result);
else if (idx == 1)
rtn = _receive2.TryDequeue(out result);
else if (idx == 2)
rtn = _receive3.TryDequeue(out result);
if (rtn)
{
log.OutInfo(Common.ABB_Dev[idx].ToString("Receive Multitask ") + s);
if (result.Contains("p" + i))
break;
}
Thread.Sleep(1000);
}
if (StopMultitask)
{
StopMultitask = false;
break;
}
}
}
}
private void ListenClient()
{
while (loop)
{
try
{
Socket socket = server.Accept(); //这边会暂停,不需要sleep
IPEndPoint ep = (IPEndPoint)socket.RemoteEndPoint;
Thread thread = new Thread(new ParameterizedThreadStart(Received));
string ip = ep.Address.ToString();
int idx = Array.FindIndex(Common.ABB_Dev, s => s.IP == ip);
if (idx == -1) continue;
_client[idx].Socket = socket;
_client[idx].Receive = thread;
_client[idx].IsConn = true;
ServerChanged?.Invoke(idx, "打开");
_client[idx].Loop = true;
thread.Start(idx);
log.OutInfo(Common.ABB_Dev[idx].ToString(" 连接到服务器"));
}
catch (Exception ex)
{
log.OutError(ex);
}
}
}
private void ListenStatus()
{
int sum;
while (loop)
{
sum = 0;
try
{
for (int i = 0; i < _client.Length; i++)
{
if (_client[i].Ctl == null)
{
log.OutInfo("ListenStatus " + Common.ABB_Dev[i].ToString(" 不存在"));
}
else
{
if (_client[i].Ctl.State == ControllerState.MotorsOn)
{
if (!_client[i].IsConn) StartDevice(i);
}
else
{
if (_client[i].IsConn)
StopDevice(i);
}
if (_client[i].IsConn) sum++;
}
}
}
catch (Exception ex)
{
log.OutError(ex);
}
Thread.Sleep(1000);
}
}
private void Received(object obj)
{
int idx = (int)obj;
Socket client = _client[idx].Socket;
while (_client[idx].Loop)
{
if (!_client[idx].IsConn) break;
if (client.Available > 0)
{
byte[] buffer = new byte[1024];
int count = client.Receive(buffer);
//返回的命令用逗号(,)分隔,最后有分号(;)
string ss = Encoding.ASCII.GetString(buffer, 0, count);
log.OutInfo(Common.ABB_Dev[idx].ToString("Receive ") + ss);
string[] arr = ss.Split(',');
if (arr[0] == Common.ABB_MOVEGET)
{
GetStart[idx] = false;
GetEnd[idx] = true;
}
else if (arr[0] == Common.ABB_MOVEPUT)
{
PutStart[idx] = false;
if (arr[4].StartsWith("OK"))
{
PutEnd[idx] = true;
PutIn[idx] = false;
}
else if (arr[4].StartsWith("FINISHED"))
{
PutEnd[idx] = false;
PutIn[idx] = true;
}
}
//if (idx == 0)
// _receive1.Enqueue(ss);
//else if (idx == 1)
// _receive2.Enqueue(ss);
//else if (idx == 2)
// _receive3.Enqueue(ss);
}
Thread.Sleep(100);
}
}
private bool OpenServer()
{
try
{
IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(Common.config["Local_IP"]), 21);
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(localEP);
server.Listen(10);
tListenClient = new Thread(new ThreadStart(ListenClient));
tStatus = new Thread(new ThreadStart(ListenStatus));
loop = true;
tListenClient.Start();
tStatus.Start();
log.OutInfo("ABB Server Open");
return true;
}
catch (Exception ex)
{
log.OutError(ex);
return false;
}
}
public void LoadController()
{
try
{
scanner = new NetworkScanner();
scanner.Scan();
log.OutInfo("LoadController Count=" + scanner.Controllers.Count);
foreach (ControllerInfo controllerInfo in scanner.Controllers)
{
string ip = controllerInfo.IPAddress.ToString();
int idx = Array.FindIndex(Common.ABB_Dev, s => s.IP == ip);
if (idx == -1) continue;
_client[idx].Ctl = ControllerFactory.CreateFrom(controllerInfo);
_client[idx].Ctl.Logon(UserInfo.DefaultUser);
_client[idx].Ctl.StateChanged += Controller_StateChanged;
Common.ABB_Dev[idx].State = _client[idx].Ctl.State.ToString();
log.OutInfo(Common.ABB_Dev[idx].Name + " State=" + _client[idx].Ctl.State.ToString());
}
networkwatcher = new NetworkWatcher(scanner.Controllers);
networkwatcher.Found += new EventHandler<NetworkWatcherEventArgs>(FoundEvent);
networkwatcher.Lost += new EventHandler<NetworkWatcherEventArgs>(LostEvent);
networkwatcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
log.OutError(ex);
}
}
private void Controller_StateChanged(object sender, StateChangedEventArgs e)
{
try
{
Controller ctl = (sender as Controller);
int idx = Array.FindIndex(_client, cc => cc.IP == ctl.IPAddress.ToString());
if (idx == -1) return;
StatusChanged?.Invoke(idx, ctl.State.ToString());
//从自动切换到手动,关闭客户端
if (_client[idx].IsConn && ctl.State == ControllerState.MotorsOff)
StopDevice(idx);
}
catch (Exception ex)
{
log.OutError(ex);
}
}
private void FoundEvent(object sender, NetworkWatcherEventArgs e)
{
try
{
string ip = e.Controller.IPAddress.ToString();
log.OutInfo("Find IP=" + ip);
int idx = Array.FindIndex(Common.ABB_Dev, s => s.IP == ip);
if (idx == -1) return;
GetStart[idx] = false;
GetEnd[idx] = true;
PutStart[idx] = false;
PutIn[idx] = false;
PutEnd[idx] = true;
_client[idx].Ctl = ControllerFactory.CreateFrom(e.Controller);
_client[idx].Ctl.Logon(UserInfo.DefaultUser);
Common.ABB_Dev[idx].State = _client[idx].Ctl.State.ToString();
log.OutInfo(Common.ABB_Dev[idx].Name + " State=" + _client[idx].Ctl.State.ToString());
}
catch (Exception ex)
{
log.OutError(ex);
}
}
private void LostEvent(object sender, NetworkWatcherEventArgs e)
{
//string ip = e.Controller.IPAddress.ToString();
//int idx = Array.FindIndex(AssemblyLine.Common.ABB_NAME, s => s[0] == ip);
//if (idx == -1) return;
//_client[idx].IP = "";
//_client[idx].Socket.Close();
//_client[idx].Socket = null;
//_client[idx].Receive.Abort();
//_client[idx].Receive = null;
//_client[idx].Buffer = null;
//_client[idx].Ctl = null;
//_dgv.Rows[idx].Cells[2].Value = "NULL";
}
private class Client
{
/// <summary>
/// 客户端IP地址
/// </summary>
public string IP = "";
/// <summary>
/// Socket TCP
/// </summary>
public Socket Socket;
/// <summary>
/// 接收事件
/// </summary>
public Thread Receive;
/// <summary>
/// 缓存
/// </summary>
//public byte[] Buffer;
/// <summary>
/// 控制器
/// </summary>
public Controller Ctl;
public bool Loop;
/// <summary>
/// 是否连接服务器
/// </summary>
public bool IsConn { set; get; } = false;
public Client(string ip)
{
IP = ip;
Loop = false;
}
}
}
}