patrick
2019-12-10 1c4426810c71eead57084be8a18ade8d314dd8c4
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
using Autofac;
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using Bro.Common.Model;
using Bro.Device.AuboRobot;
using Bro.Device.SeerAGV;
using HalconDotNet;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
 
namespace A032.Process
{
    public class TrayTask : IComplexDisplay
    {
        [Browsable(false)]
        public string TaskId { get; set; } = Guid.NewGuid().ToString();
 
        /// <summary>
        /// 优先级越高,越快执行
        /// </summary>
        [Category("任务配置")]
        [Description("优先级。优先级越高,越快执行")]
        public int Priority { get; set; }
 
        private string locationCode = "";
 
        [Category("任务配置")]
        [Description("任务执行地址代码")]
        [TypeConverter(typeof(PositionCodeConverter))]
        public string LocationCode
        {
            get => locationCode;
            set
            {
                if (locationCode != value)
                {
                    locationCode = value;
 
                    using (var scope = GlobalVar.Container.BeginLifetimeScope())
                    {
                        ProcessConfig config = scope.Resolve<ProcessConfig>();
 
                        Location = config.PositionCollection.FirstOrDefault(u => u.PositionCode == locationCode);
                    }
                }
            }
        }
 
        [Browsable(false)]
        public PathPosition Location { get; set; } = new PathPosition();
 
        private TaskType taskType = TaskType.LoadEmptyTrayToAGV;
        [Category("任务配置")]
        [Description("任务类型")]
        public TaskType TaskType
        {
            get => taskType;
            set
            {
                taskType = value;
 
                var attr = taskType.GetEnumAttribute<PriorityAttribute>();
                if (attr != null)
                {
                    Priority = attr.Priority;
                }
            }
        }
 
        private string sourceDeviceId = "";
        [Category("任务配置")]
        [Description("任务来源设备")]
        [TypeConverter(typeof(AllDeviceIdConverter))]
        public string SourceDeviceId
        {
            get => sourceDeviceId;
            set
            {
                if (sourceDeviceId != value)
                {
                    sourceDeviceId = value;
 
                    using (var scope = GlobalVar.Container.BeginLifetimeScope())
                    {
                        List<IDevice> deviceList = scope.Resolve<List<IDevice>>();
 
                        var device = deviceList.FirstOrDefault(u => u.Id == value);
                        SourceDeviceName = device.Name;
                    }
                }
            }
        }
 
        [Browsable(false)]
        [JsonIgnore]
        public string SourceDeviceName { get; set; } = "";
 
        [Browsable(false)]
        [JsonIgnore]
        public string BindId { get; set; } = "";
 
        [Browsable(false)]
        [JsonIgnore]
        public int WaitShift { get; set; } = 0;
 
        public string GetDisplayText()
        {
            return $"{SourceDeviceName}发起的{TaskType.ToString()}任务";
        }
    }
 
    public enum TaskType
    {
        [Priority(30)]
        UnloadEmptyTrayToMachine,
 
        [Priority(20)]
        LoadEmptyTrayToAGV,
 
        [Priority(30)]
        LoadFullTrayFromMachine,
 
        [Priority(20)]
        UnloadFullTrayToLine,
 
        [Priority(50)]
        Charge,
 
        [Priority(10)]
        IdleCharge,
    }
 
    public class PriorityAttribute : Attribute
    {
        public int Priority { get; set; }
 
        public PriorityAttribute(int priority)
        {
            Priority = priority;
        }
    }
 
    public partial class ProcessControl
    {
        private bool isEnableExecuteTask = true;
        public bool IsEnableExecuteTask
        {
            get => isEnableExecuteTask;
            set
            {
                isEnableExecuteTask = value;
 
                LogAsync(DateTime.Now, $"Set IsEnableExecuteTask {value.ToString()}", $"{(value ? "打开" : "关闭")}任务执行");
            }
        }
        List<AGVState> _disableStates = new List<AGVState>() { AGVState.InCharge, AGVState.Warning, AGVState.Unknown };
 
        private void Reset(string bindId = "")
        {
            WarningRemains.Clear();
            IsEnableExecuteTask = true;
 
            if (string.IsNullOrWhiteSpace(bindId))
            {
                Config.AGVBindCollection.ForEach(bind =>
                {
                    if (bind.UnitState == AGVState.Warning)
                    {
                        //bind.WarningMsg.Clear();
                        //bind.UnitState = AGVState.Idle;
                        bind.Reset();
                    }
                });
 
                LogAsync(DateTime.Now, "Reset", "执行全体复位操作");
            }
            else
            {
                var bind = Config.AGVBindCollection.FirstOrDefault(u => u.Id == bindId);
 
                if (bind != null && bind.UnitState == AGVState.Warning)
                {
                    //bind.WarningMsg.Clear();
                    //bind.UnitState = AGVState.Idle;
 
                    bind.Reset();
 
                    LogAsync(DateTime.Now, "Reset", $"执行{bind.AGV.Name}复位操作");
                }
            }
        }
 
        static object _taskLock = new object();
        NoticedList<TrayTask> TrayTaskCollection = new NoticedList<TrayTask>();
 
        private void InsertTask(TrayTask task)
        {
            lock (_taskLock)
            {
                if (TrayTaskCollection.Any(u => u.TaskType == task.TaskType && u.SourceDeviceId == task.SourceDeviceId))
                {
                    LogAsync(DateTime.Now, "重复任务", $"{task.SourceDeviceName}发起的{task.TaskType.ToString()}任务已存在任务列表中");
                    return;
                }
 
                int insertIndex = TrayTaskCollection.Count;
                var nextTask = TrayTaskCollection.FirstOrDefault(u => u.Priority < task.Priority && u.WaitShift == 0);
                if (nextTask != null)
                {
                    insertIndex = TrayTaskCollection.IndexOf(nextTask);
                }
 
                TrayTaskCollection.Insert(insertIndex, task);
            }
        }
 
        #region 任务触发
        private async void OnTaskListChanged(NotifyCollectionChangedAction action, List<TrayTask> task)
        {
            await Task.Run(() =>
            {
                if (action == NotifyCollectionChangedAction.Add)
                {
                    ExecuteTask();
                }
            });
        }
 
        private async void OnUnitStateChanged(string unitId, AGVState preState, AGVState currentState)
        {
            await Task.Run(() =>
            {
                if (currentState == AGVState.Idle || currentState == AGVState.IdleCharge)
                {
                    ExecuteTask(unitId);
                }
            });
        }
 
        private void ExecuteTask(string unitId = "")
        {
            TrayTask task = null;
 
            lock (_taskLock)
            {
                if (TrayTaskCollection.Count <= 0)
                {
                    return;
                }
 
                task = TrayTaskCollection.FirstOrDefault(u => string.IsNullOrWhiteSpace(u.BindId));
            }
 
            //任务是否已在执行中
            if (Config.AGVBindCollection.Any(u => u.CurrentTaskId == task.TaskId))
            {
                LogAsync(DateTime.Now, "任务执行中", $"{task.GetDisplayText()}正在执行中");
                return;
            }
 
            AGVBindUnit bind = null;
 
            if (string.IsNullOrWhiteSpace(unitId))
            {
                var available = Config.AGVBindCollection.Where(u => u.UnitState == AGVState.Idle || u.UnitState == AGVState.IdleCharge);
 
                switch (task.TaskType)
                {
                    case TaskType.LoadFullTrayFromMachine:
                        available = available.Where(u => u.FullTrayNum < Config.AGVAvailableTrayNums);
                        break;
                    case TaskType.UnloadEmptyTrayToMachine:
                        available = available.Where(u => u.EmptyTrayNum > 0);
                        break;
                    default:
                        break;
                }
 
                bind = available.FirstOrDefault();
            }
            else
            {
                bind = Config.AGVBindCollection.FirstOrDefault(u => u.Id == unitId && (u.UnitState == AGVState.Idle || u.UnitState == AGVState.IdleCharge));
            }
 
            if (bind == null)
            {
                LogAsync(DateTime.Now, $"暂时没有可执行任务的单元", "");
                ReArrangeTask(task);
                return;
            }
 
            if (task.Location == null)
            {
                switch (task.TaskType)
                {
                    case TaskType.LoadEmptyTrayToAGV:
                        task.Location = Config.PositionCollection.FirstOrDefault(u => !u.IsOccupied && u.Description == PathPositionDefinition.LoadEmptyTray);
                        break;
                    case TaskType.LoadFullTrayFromMachine:
                        task.Location = Config.PositionCollection.FirstOrDefault(u => !u.IsOccupied && u.Description == PathPositionDefinition.LoadFullTray && u.DeviceOwner == task.SourceDeviceId);
                        break;
                    case TaskType.UnloadEmptyTrayToMachine:
                        task.Location = Config.PositionCollection.FirstOrDefault(u => !u.IsOccupied && u.Description == PathPositionDefinition.UnloadEmptyTray && u.DeviceOwner == task.SourceDeviceId);
                        break;
                    case TaskType.UnloadFullTrayToLine:
                        task.Location = Config.PositionCollection.FirstOrDefault(u => !u.IsOccupied && u.Description == PathPositionDefinition.UnloadFullTray && u.DeviceOwner == task.SourceDeviceId);
                        break;
                    default:
                        break;
                }
            }
 
            if (task.Location == null)
            {
                ReArrangeTask(task);
                return;
            }
            else
            {
                task.Location.IsOccupied = true;
            }
 
            task.BindId = bind.Id;
 
            if (!string.IsNullOrWhiteSpace(bind.CurrentTaskId))
            {
                bind.AGV.CancelTask();
            }
 
            LogAsync(DateTime.Now, $"开始执行任务", task.GetDisplayText());
 
            bind.IsTaskCancelled = false;
            bind.IsTaskCancelling = false;
 
            bind.UnitState = AGVState.Running;
            bind.CurrentTaskId = task.TaskId;
 
            try
            {
                switch (task.TaskType)
                {
                    case TaskType.LoadEmptyTrayToAGV:
                        LoadEmptyTrayToAGV(task, bind);
                        break;
                    case TaskType.LoadFullTrayFromMachine:
                        LoadFullTrayFromMachine(task, bind);
                        break;
                    case TaskType.UnloadEmptyTrayToMachine:
                        UnloadEmptyTrayToMachine(task, bind);
                        break;
                    case TaskType.UnloadFullTrayToLine:
                        UnloadFullTrayToLine(task, bind);
                        break;
                    default:
                        break;
                }
 
                ////任务完成后检查电量
                //bind.AGV.BatteryHandle.Reset();
                //bool isNotTimeout = bind.AGV.BatteryHandle.WaitOne((bind.AGV.InitialConfig as SeerAGVInitialConfig).ScanInterval * 10);
 
                //if (!isNotTimeout)
                //{
                //    throw new ProcessException($"{bind.AGV.Name}获取电池状态超时");
                //}
            }
            catch (TaskCanceledException ex)
            {
                try
                {
                    CancelTask(bind);
                }
                catch (Exception)
                {
                    ExceptionHandle(task, bind, ex, $"任务{task.TaskId}取消失败,");
                    return;
                }
                finally
                {
                    bind.IsTaskCancelled = false;
                    bind.IsTaskCancelling = false;
                }
            }
            catch (Exception ex)
            {
                ExceptionHandle(task, bind, ex);
                return;
            }
            finally
            {
                //lock (_taskListLock)
                //{
                //    _taskList.RemoveAt(0);
                //}
            }
 
            LogAsync(DateTime.Now, $"任务{task.TaskId}流程结束", "");
 
            AfterTaskHandle(task, bind);
        }
 
        private void ReArrangeTask(TrayTask task)
        {
            task.WaitShift++;
 
            TrayTaskCollection.Remove(task);
 
            if (task.WaitShift > Config.DefaultWaitShift)
            {
                LogAsync(DateTime.Now, "任务无法执行", $"{task.GetDisplayText()}等待{task.WaitShift}次无法执行,已移出任务队列");
            }
            else
            {
                InsertTask(task);
            }
        }
 
        //AutoResetEvent _taskDoneHandle = new AutoResetEvent(true);
        Dictionary<string, AutoResetEvent> _bindTaskDoneHandleDict = new Dictionary<string, AutoResetEvent>();
        private void AfterTaskHandle(TrayTask task, AGVBindUnit bind, string warningMsg = "", bool isWarningRaised = false)
        {
            lock (_taskLock)
            {
                task.Location.IsOccupied = false;
                TrayTaskCollection.Remove(task);
            }
 
            bind.CurrentTaskId = "";
            if (isWarningRaised)
            {
                bind.WarningMsg.Add(warningMsg);
                bind.UnitState = AGVState.Warning;
            }
            else
            {
                //任务完成后检查电量
                bind.AGV.BatteryHandle.Reset();
                bool isNotTimeout = bind.AGV.BatteryHandle.WaitOne((bind.AGV.InitialConfig as SeerAGVInitialConfig).ScanInterval * 10);
 
                if (!isNotTimeout)
                {
                    string msg = $"{bind.AGV.Name}获取电池状态超时";
                    bind.WarningMsg.Add(msg);
                    new ProcessException(msg);
                    bind.UnitState = AGVState.Warning;
                }
                else
                {
                    SeerAGVInitialConfig iConfig = bind.AGV.InitialConfig as SeerAGVInitialConfig;
                    if (bind.AGV.BatteryLvl <= iConfig.BatteryLvlToCharge)
                    {
                        bind.UnitState = AGVState.InCharge;
 
                        var chargePosition = Config.PositionCollection.FirstOrDefault(u => !u.IsOccupied && u.Description == PathPositionDefinition.Charge);
 
                        if (chargePosition == null)
                        {
                            string msg = $"{bind.AGV.Name}目前无可用充电地址";
                            bind.WarningMsg.Add(msg);
                            new ProcessException(msg);
                            bind.UnitState = AGVState.Warning;
                        }
                        else
                        {
                            bind.AGV.TaskOrder(chargePosition.PositionCode, true);
                        }
                    }
                    else
                    {
                        bind.UnitState = AGVState.Idle;
                    }
                }
            }
 
            _bindTaskDoneHandleDict[bind.Id].Set();
        }
 
        /// <summary>
        /// 取消当前任务,如果已取卷宗,归还到原处
        /// </summary>
        /// <param name="bind"></param>
        private void CancelTask(AGVBindUnit bind)
        {
            bind.IsTaskCancelling = true;
 
            bind.AGV.CancelTask();
            bind.Robot.Move(new RobotPoint(), MoveType.Origin, true);
        }
 
        /// <summary>
        /// 过程异常处理,反馈异常消息到RabbitMQ
        /// </summary>
        /// <param name="task"></param>
        /// <param name="bind"></param>
        /// <param name="ex"></param>
        /// <param name="errorMsg"></param>
        private void ExceptionHandle(TrayTask task, AGVBindUnit bind, Exception ex, string errorMsg = "")
        {
            bool isWarningEx = false;
            if (ex is ProcessException)
            {
                isWarningEx = (ex as ProcessException).Level > 0;
                errorMsg += (ex as ProcessException).ErrorCode;
            }
            else
            {
                isWarningEx = true;
                errorMsg += ex.Message;
                LogAsync(DateTime.Now, $"{task.TaskId}异常", ex.GetExceptionMessage());
            }
 
            try
            {
                SwitchLight(bind.Robot, false);
                bind.Robot.Move(new RobotPoint(), MoveType.Origin, true);
            }
            catch (Exception)
            {
            }
 
            LogAsync(DateTime.Now, $"任务{task.GetDisplayText()}异常反馈", errorMsg);
 
            AfterTaskHandle(task, bind, errorMsg, isWarningEx);
        }
        #endregion
 
        #region 任务执行
        /// <summary>
        /// 将满Tray放置到产线上
        /// </summary>
        /// <param name="task"></param>
        /// <param name="bind"></param>
        private void UnloadFullTrayToLine(TrayTask task, AGVBindUnit bind)
        {
            string methodName = "UnloadFullTrayToLine";
 
            bind.AGV.TaskOrder(task.Location.PositionCode, true);
 
            var visionConfig = Config.VisionConfigCollection.FirstOrDefault(u => u.CameraId == bind.CameraId && u.PositionCode == task.Location.PositionCode);
 
            if (visionConfig == null)
                throw new ProcessException($"未能获取{bind.Camera.Name}在{task.Location.PositionCode}的视觉配置");
 
            while (bind.FullTrayNum > 0)
            {
                bind.Robot.Move(visionConfig.RobotSnapshotPoint, MoveType.AbsoluteMove, true);
 
                bool isLineReady = false;
                if (Config.IsEnableVisionGuide)
                {
                    int reTryTime = Config.LineBusyRetryTimes;
 
                    HDevEngineTool tool = null;
                    if (!_halconToolDict.ContainsKey(visionConfig.CameraOpConfig.AlgorithemPath))
                    {
                        throw new ProcessException($"未配置{methodName}的算法工具");
                    }
 
                    tool = _halconToolDict[visionConfig.CameraOpConfig.AlgorithemPath];
 
                    SwitchLight(bind.Robot, true);
                    Thread.Sleep(500);//等待灯开
 
                    do
                    {
                        RobotPoint point = new RobotPoint();
                        using (var hImage = CollectHImage(bind.Camera, visionConfig.CameraOpConfig, methodName))
                        {
                            tool.InputImageDic.Clear();
                            tool.InputImageDic["INPUT_Image"] = hImage;
 
                            tool.RunProcedure();
 
                            if (!tool.IsSuccessful)
                            {
                                throw new ProcessException($"{visionConfig.CameraOpConfig.AlgorithemPath}算法运行失败");
                            }
 
                            isLineReady = tool.GetResultTuple("OUTPUT_Result").I == 1;
                        }
 
                        if (!isLineReady)
                        {
                            LogAsync(DateTime.Now, $"{task.Location.PositionCode}位置线体繁忙", "");
                            Thread.Sleep(Config.LineBusyWaitInterval * 1000);
                            reTryTime--;
                        }
                        else
                        {
                            reTryTime = 0;
                        }
                    } while (reTryTime > 0);
 
                    SwitchLight(bind.Robot, false);
                }
                else
                {
                    isLineReady = true;
                }
 
                if (isLineReady)
                {
                    bind.Robot.UnLoad(bind.Robot.CurrentPoint, TrayType.FullTray, true);
                }
                else
                {
                    bind.Robot.Move(new RobotPoint(), MoveType.Origin, true);
                    break;
                }
            }
        }
 
        /// <summary>
        /// 将空Tray放置到压机上
        /// </summary>
        /// <param name="task"></param>
        /// <param name="bind"></param>
        private void UnloadEmptyTrayToMachine(TrayTask task, AGVBindUnit bind)
        {
            string methodName = "UnloadEmptyTrayToMachine";
 
            MachineRelatedOperation(task, bind, methodName);
 
            RobotPoint point = bind.Robot.CurrentPoint.DeepSerializeClone();
 
            int emptyTrayNum = 0;
            do
            {
                bind.Robot.UnLoad(point, TrayType.EmptyTray, true);
                emptyTrayNum++;
 
                bind.Robot.MonitorHandle.Reset();
                var isNotTimeout = bind.Robot.MonitorHandle.WaitOne((bind.Robot.InitialConfig as AuboRobotInitialConfig).ReplyTimeout * 3);
                if (!isNotTimeout)
                    throw new ProcessException($"{bind.Robot.Name}监听操作超时");
 
            } while (emptyTrayNum < Config.Machine_EmptyTrayNum && bind.EmptyTrayNum > 0);
        }
 
        /// <summary>
        /// 从压机上取满Tray到AGV
        /// </summary>
        /// <param name="task"></param>
        /// <param name="bind"></param>
        private void LoadFullTrayFromMachine(TrayTask task, AGVBindUnit bind)
        {
            string methodName = "LoadFullTrayFromMachine";
 
            MachineRelatedOperation(task, bind, methodName);
 
            RobotPoint point = bind.Robot.CurrentPoint.DeepSerializeClone();
 
            int fullTrayNum = Config.Machine_FullTrayNum;
            do
            {
                bind.Robot.Load(point, TrayType.FullTray, true);
                fullTrayNum--;
                bind.FullTrayNum++;
 
                bind.Robot.MonitorHandle.Reset();
                var isNotTimeout = bind.Robot.MonitorHandle.WaitOne((bind.Robot.InitialConfig as AuboRobotInitialConfig).ReplyTimeout * 3);
                if (!isNotTimeout)
                    throw new ProcessException($"{bind.Robot.Name}监听操作超时");
 
            } while (fullTrayNum > 0 && bind.FullTrayNum < Config.AGVAvailableTrayNums);
        }
 
        private void MachineRelatedOperation(TrayTask task, AGVBindUnit bind, string methodName)
        {
            bind.AGV.TaskOrder(task.Location.PositionCode, true);
 
            var visionConfig = Config.VisionConfigCollection.FirstOrDefault(u => u.CameraId == bind.CameraId && u.PositionCode == task.Location.PositionCode);
 
            if (visionConfig == null)
                throw new ProcessException($"未能获取{bind.Camera.Name}在{task.Location.PositionCode}的视觉配置");
 
            bind.Robot.Move(visionConfig.RobotSnapshotPoint, MoveType.AbsoluteMove, true);
 
            if (Config.IsEnableVisionGuide)
            {
                int repeatTime = Config.VisionGuideTimes;
 
                HDevEngineTool tool = null;
                if (!_halconToolDict.ContainsKey(visionConfig.CameraOpConfig.AlgorithemPath))
                {
                    throw new ProcessException($"未配置{methodName}的算法工具");
                }
 
                tool = _halconToolDict[visionConfig.CameraOpConfig.AlgorithemPath];
 
                SwitchLight(bind.Robot, true);
                Thread.Sleep(500);//等待灯开
 
                do
                {
                    RobotPoint point = new RobotPoint();
                    using (var hImage = CollectHImage(bind.Camera, visionConfig.CameraOpConfig, methodName))
                    {
                        tool.InputImageDic.Clear();
                        tool.InputImageDic["INPUT_Image"] = hImage;
 
                        tool.RunProcedure();
 
                        if (!tool.IsSuccessful)
                        {
                            throw new ProcessException($"{visionConfig.CameraOpConfig.AlgorithemPath}算法运行失败");
                        }
 
                        double du = tool.GetResultTuple("OUTPUT_X").D;
                        double dv = tool.GetResultTuple("OUTPUT_Y").D;
 
                        if (du < 0 || dv < 0)
                        {
                            throw new ProcessException($"{visionConfig.CameraOpConfig.AlgorithemPath}算法结果异常,点位信息获取失败");
                        }
 
                        du -= visionConfig.StandardPoint.X;
                        dv -= visionConfig.StandardPoint.Y;
 
                        HOperatorSet.AffineTransPoint2d(new HTuple(visionConfig.Matrix), du, dv, out HTuple dx, out HTuple dy);
 
                        point.X = (float)dx.D;
                        point.Y = (float)dy.D;
                        point.A = (float)tool.GetResultTuple("OUTPUT_Angle").D;
                    }
 
                    LogAsync(DateTime.Now, $"{methodName}引导坐标", point.GetDisplayText());
 
                    bind.Robot.Move(point, MoveType.RobotRelativeMove, true);
 
                    repeatTime--;
                } while (repeatTime > 0);
 
                SwitchLight(bind.Robot, false);
 
                //视觉导引后再做固定偏移
                bind.Robot.Move(visionConfig.RobotShift, MoveType.RobotRelativeMove, true);
            }
        }
 
        /// <summary>
        /// 人工装空Tray到AGV
        /// </summary>
        /// <param name="task"></param>
        /// <param name="bind"></param>
        private void LoadEmptyTrayToAGV(TrayTask task, AGVBindUnit bind)
        {
            bind.AGV.TaskOrder(task.Location.PositionCode, true);
            bind.Robot.Load(new RobotPoint(), TrayType.EmptyTray, true);
        }
        #endregion
    }
}