C3204
2025-12-22 ede58adb19d04a796ec00d8f3409b2b362af75b7
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
using HalconDotNet;
using LB_SmartVision.Forms.Pages.SettingPage;
using LB_SmartVision.Tool;
using LB_VisionFlowNode;
using LB_VisionProcesses;
using LB_VisionProcesses.Alogrithms;
using LB_VisionProcesses.Cameras;
using LB_VisionProcesses.Communicators;
using LB_VisionProcesses.Processes.ScriptTool;
using OpenCvSharp;
using System.Collections.Concurrent;
 
namespace LB_SmartVision.ProcessRun
{
    public class ProcessContext : IFlowContext
    {
        /// <summary>
        /// 通讯集合(Key:通讯名,Value:通讯句柄)
        /// </summary>
        public ObservableConcurrentDictionary<string, BaseCommunicator> dicCommunicators { get; set; }
 
        /// <summary>
        /// 相机集合(Key:相机SN,Value:相机句柄)
        /// </summary>
        public ObservableConcurrentDictionary<string, BaseCamera> dicCameras { get; set; }
 
        public ConcurrentDictionary<string, List<Tuple<string, string>>> dicInputsMapping { get; set; }
 
        public ConcurrentDictionary<string, List<string>> dicOutputsMapping { get; set; }
 
        /// <summary>
        /// 运行流程
        /// </summary>
        public ConcurrentDictionary<string, IProcess> dicContext = new ConcurrentDictionary<string, IProcess>();
 
        /// <summary>
        /// 运行标记
        /// </summary>
        public bool bRuning = false;
 
        /// <summary>
        /// 运行完成
        /// </summary>
        public bool bCompleted = true;
 
        /// <summary>
        /// 运行结果
        /// </summary>
        public bool Result = false;
 
        /// <summary>
        /// 运行消息
        /// </summary>
        public string Msg = string.Empty;
 
        /// <summary>
        /// 运行时间
        /// </summary>
        public double RunTime = 0;
 
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartTime = DateTime.Now;
 
        private HTuple ho_ImageWidth = new HTuple();
 
        private HTuple ho_ImageHeight = new HTuple();
 
        /// <summary>
        /// 用于绘制结果图的窗口控件
        /// </summary>
        private HWindowControl hWindowControl = new HWindowControl();
 
        public ProcessContext(ObservableConcurrentDictionary<string, BaseCamera> dicCameras, ObservableConcurrentDictionary<string, BaseCommunicator> dicCommunicators
            , ConcurrentDictionary<string, List<Tuple<string, string>>> dicInputsMapping, ConcurrentDictionary<string, List<string>> dicOutputsMapping)
        {
            this.dicCameras = dicCameras;
            this.dicCommunicators = dicCommunicators;
            this.dicInputsMapping = dicInputsMapping;
            this.dicOutputsMapping = dicOutputsMapping;
 
            hWindowControl.Size = new System.Drawing.Size(1920, 1080);
 
            TAlgorithm.set_display_font(hWindowControl.HalconWindow, 1080 / 20, "mono", "true", "false");
            HOperatorSet.SetLineWidth(hWindowControl.HalconWindow, 5);
 
            InitializeMethods();
            InitializeDelegates();
 
            mappingEngine = new ExpressionTreeMappingEngine(dicContext);
        }
 
        // 初始化
        ExpressionTreeMappingEngine mappingEngine = null;
 
        /// <summary>
        /// 编译映射
        /// </summary>
        public void CompileMappings()
        {
            mappingEngine = new ExpressionTreeMappingEngine(dicContext);
            mappingEngine.CompileMappings(dicInputsMapping);
        }
 
        /// <summary>
        /// 更新输入(高性能执行)
        /// </summary>
        /// <param name="process"></param>
        public void UpdateInputs(IProcess process)
        {
            mappingEngine.UpdateInputs(process);
        }
 
        //void UpdateInputs(IProcess process)
        //{
        //    string ProcessName = process.strProcessName;
        //    List<Tuple<string, string>> listTuples = dicInputsMapping[ProcessName];
 
        //    foreach (var tuple in listTuples)
        //    {
        //        if (string.IsNullOrEmpty(tuple.Item2) || tuple.Item2.Trim() == "")
        //            continue;
 
        //        string[] arrInputs = tuple.Item1.Split(".");
        //        if (arrInputs.Length < 3)
        //            continue;
 
        //        string InputProcessName = arrInputs[0];
        //        string strInput = arrInputs[1];
        //        string InputValueName = arrInputs[2];
 
        //        string[] arrOutputs = tuple.Item2.Split(".");
        //        if (arrOutputs.Length < 2)
        //            continue;
 
        //        string IndexProcessName = arrOutputs[0];
        //        string IndexIsInputOrOutput = arrOutputs[1];
        //        string IndexValueName = arrOutputs.Length == 3 ? arrOutputs[2] : "";
 
        //        //这里的o是你所指向的输出流程
        //        object o = dicContext[IndexProcessName];
 
        //        if (o == null)
        //            continue;
        //        else if (o is IProcess)
        //        {
        //            IProcess i = (IProcess)o;
        //            if (i.strProcessName != IndexProcessName)
        //                continue;
 
        //            if (InputValueName == "Image")
        //            {
        //                switch (IndexIsInputOrOutput)
        //                {
        //                    case "Inputs":
        //                        //实际上不允许索引的值是输入
        //                        if (IndexValueName == "Image")
        //                            process.InputImage = i.InputImage;
        //                        else
        //                            process.InputImage = i.Params.Inputs[IndexValueName];
        //                        break;
        //                    case "Outputs":
        //                        if (IndexValueName == "Image")
        //                            process.InputImage = i.OutputImage;
        //                        else
        //                            process.InputImage = i.Params.Outputs[IndexValueName];
        //                        break;
        //                    default:
        //                        process.InputImage = null;
        //                        break;
        //                }
 
        //                if (IndexValueName == "")
        //                    process.InputImage = null;
        //            }
        //            else if (InputValueName == "Fixture")
        //            {
        //                //赋值参数
        //                switch (IndexIsInputOrOutput)
        //                {
        //                    case "Inputs":
        //                        //实际上不允许索引的值是输入
        //                        process.Params.Fixture = i.Params.Fixture;
        //                        break;
        //                    case "Outputs":
        //                        process.Params.Fixture = i.Params.Fixture;
        //                        break;
        //                    default:
        //                        //process.Params.Fixture = new Fixture();
        //                        break;
        //                }
 
        //                if (IndexValueName == "")
        //                    process.Params.Fixture = new Fixture();
        //            }
        //            else if (IndexValueName == "Result")
        //            {
        //                //赋值参数
        //                switch (IndexIsInputOrOutput)
        //                {
        //                    case "Inputs":
        //                        //实际上不允许索引的值是输入
        //                        process.Params.Inputs[InputValueName] = i.Result;
        //                        break;
        //                    case "Outputs":
        //                        process.Params.Inputs[InputValueName] = i.Result;
        //                        break;
        //                    default:
        //                        process.Params.Inputs[InputValueName] = null;
        //                        break;
        //                }
        //            }
        //            else if (process.Params.Inputs.Contains(InputValueName))
        //            {
        //                //赋值参数
        //                switch (IndexIsInputOrOutput)
        //                {
        //                    case "Inputs":
        //                        //实际上不允许索引的值是输入
        //                        process.Params.Inputs[InputValueName] = i.Params.Inputs[IndexValueName];
        //                        break;
        //                    case "Outputs":
        //                        process.Params.Inputs[InputValueName] = i.Params.Outputs[IndexValueName];
        //                        break;
        //                    default:
        //                        process.Params.Inputs[InputValueName] = null;
        //                        break;
        //                }
        //            }
        //        }
        //    }
        //}
 
        public bool GetValue(string map, out object obj)
        {
            obj = null;
            if (string.IsNullOrEmpty(map))
                return false;
 
            try
            {
                string[] arrMap = map.Split(".");
                if (arrMap.Length <= 1)
                    return false;
 
                string IndexProcessName = arrMap[0];
                string IndexIsInputOrOutput = arrMap[1];
                string IndexValueName = arrMap.Length == 3 ? arrMap[2] : "";
 
                //这里的o是你所指向的输出流程
                object o = dicContext[IndexProcessName];
 
                if (o != null && o is IProcess i)
                {
                    if (i.strProcessName != IndexProcessName)
                        return false;
 
                    if (IndexValueName == "Result")
                    {
                        switch (IndexIsInputOrOutput)
                        {
                            case "Inputs":
                                //实际上不允许索引的值是输入
                                obj = i.Result;
                                break;
                            case "Outputs":
                                obj = i.Result;
                                break;
                            default:
                                return false;
                        }
                    }
                    else
                    {
                        //赋值参数
                        switch (IndexIsInputOrOutput)
                        {
                            case "Inputs":
                                obj = i.Params.Inputs[IndexValueName];
                                break;
                            case "Outputs":
                                obj = i.Params.Outputs[IndexValueName];
                                break;
                            default:
                                return false;
                        }
                    }
                    return true;
                }
                else
                    return false;
            }
            catch { obj = null; return false; }
        }
 
        public bool GetStringOutput(string map, out string str)
        {
            bool res = GetValue(map, out object obj);
            str = ProcessParams.ConvertToString(obj);
            return res;
        }
 
        public bool GetImage(Layout layout, out HObject InputImage, out HObject RecordImage)
        {
            InputImage = null; RecordImage = null;
            try
            {
                if (layout == null)
                    return false;
 
                string ProcessName = layout.ProcessName;
                string InputImageMap = layout.InputImage;
                string RecordImageMap1 = layout.RecordImage1;
                string RecordImageMap2 = layout.RecordImage2;
                string RecordImageMap3 = layout.RecordImage3;
 
                string[] arrOutputs = new string[] { };
                string IndexProcessName = string.Empty;
                string IndexIsInputOrOutput = string.Empty;
                string IndexValueName = string.Empty;
 
                #region 获取输入图片
                arrOutputs = InputImageMap.Split(".");
                if (arrOutputs.Length > 2)
                {
                    IndexProcessName = arrOutputs[0];
                    IndexIsInputOrOutput = arrOutputs[1];
                    IndexValueName = arrOutputs[2];
 
                    object o_InputImage = ((IProcess)dicContext[IndexProcessName]).OutputImage;
                    if (o_InputImage is HObject ho_image && ho_image.IsInitialized())
                        InputImage = ho_image;
                    else if (o_InputImage is Bitmap)
                    {
                        //将Mat转换为HObject
                        TAlgorithm.Bitmap2HObject((Bitmap)o_InputImage, out HObject ho_RecordImage);
                        InputImage = ho_RecordImage;
                    }
                    else if (o_InputImage is Mat)
                    {
                        //将Mat转换为HObject
                        TAlgorithm.Mat2HObject((Mat)o_InputImage, out HObject ho_RecordImage);
                        InputImage = ho_RecordImage;
                    }
 
                    if (InputImage != null && InputImage.IsInitialized())
                    {
                        HOperatorSet.GetImageSize(InputImage, out ho_ImageWidth, out ho_ImageHeight);
 
                        //图片尺寸变化才更新窗口尺寸[提高速度]
                        if ((ho_ImageWidth.Length > 0 && ho_ImageWidth.TupleInt() != hWindowControl.Size.Width)
                            || (ho_ImageHeight.Length > 0 && ho_ImageHeight.TupleInt() != hWindowControl.Size.Height))
                        {
                            hWindowControl.Invoke(new Action(() =>
                            {
                                hWindowControl.Size = new System.Drawing.Size(ho_ImageWidth, ho_ImageHeight);
                                TAlgorithm.set_display_font(hWindowControl.HalconWindow, ho_ImageWidth.I / 20, "mono", "true", "false");
                            }));
                        }
                    }
 
                    TAlgorithm.DispImage(InputImage, hWindowControl.HalconWindow);
                }
                #endregion
 
                #region 绘制结果图
                arrOutputs = RecordImageMap1.Split(".");
                if (arrOutputs.Length > 2)
                {
                    IndexProcessName = arrOutputs[0];
                    IndexIsInputOrOutput = arrOutputs[1];
                    IndexValueName = arrOutputs[2];
 
                    if (dicContext.ContainsKey(IndexProcessName))
                    {
                        ObjectRecord objectRecord1 = ((IProcess)dicContext[IndexProcessName]).Record;
                        if (objectRecord1 != null)
                        {
                            objectRecord1.Display(hWindowControl.HalconWindow);
                            objectRecord1.Dispose();
                        }
                    }
                }
 
                arrOutputs = RecordImageMap2.Split(".");
                if (arrOutputs.Length > 2)
                {
                    IndexProcessName = arrOutputs[0];
                    IndexIsInputOrOutput = arrOutputs[1];
                    IndexValueName = arrOutputs[2];
 
                    if (dicContext.ContainsKey(IndexProcessName))
                    {
                        ObjectRecord objectRecord2 = ((IProcess)dicContext[IndexProcessName]).Record;
                        if (objectRecord2 != null)
                        {
                            objectRecord2.Display(hWindowControl.HalconWindow);
                            objectRecord2.Dispose();
                        }
                    }
                }
 
                arrOutputs = RecordImageMap3.Split(".");
                if (arrOutputs.Length > 2)
                {
                    IndexProcessName = arrOutputs[0];
                    IndexIsInputOrOutput = arrOutputs[1];
                    IndexValueName = arrOutputs[2];
 
                    if (dicContext.ContainsKey(IndexProcessName))
                    {
                        ObjectRecord objectRecord3 = ((IProcess)dicContext[IndexProcessName]).Record;
                        if (objectRecord3 != null)
                        {
                            objectRecord3.Display(hWindowControl.HalconWindow);
                            objectRecord3.Dispose();
                        }
                    }
                }
 
                if (Result)
                {
                    Msg = "运行成功";
                    HOperatorSet.SetColor(hWindowControl.HalconWindow, "green");
                }
                else
                    HOperatorSet.SetColor(hWindowControl.HalconWindow, "red");
 
                TAlgorithm.DispMsg(Msg, hWindowControl.HalconWindow, Result ? "green" : "red", 0, 0);
                HOperatorSet.DumpWindowImage(out RecordImage, hWindowControl.HalconWindow);
                #endregion
 
                return true;
            }
            catch { return false; }
        }
        public bool GetCsv(CsvSetting csv, out List<string> DataTitle, out Dictionary<string, object> ResultData)
        {
            // 数据标题
            DataTitle = (new string[] { "名称", "时间", "耗时", "结果", "原因" }).ToList();
 
            ResultData = new Dictionary<string, object>();
            try
            {
                ResultData.Add("名称", csv.ProcessName);
                ResultData.Add("时间", DateTime.Now.ToString("HH:mm:ss.ff"));
                ResultData.Add("耗时", $"{RunTime.ToString("F2")}");
                ResultData.Add("结果", Result);
                ResultData.Add("原因", Msg);
 
                for (int i = 0; i < csv.Others.Count; i++)
                {
                    string title = $"数据{i}";
                    string map = csv.Others[i];
                    GetValue(map, out object obj);
                    if (obj == null)
                        continue;
 
                    Type type = obj.GetType();
                    switch (type)
                    {
                        case Type t when t == typeof(double):
                            ResultData.Add(title, ((double)obj).ToString("F4"));
                            DataTitle.Add(title);
                            break;
                        default:
                            ResultData.Add(title, ProcessParams.ConvertToString(obj));
                            DataTitle.Add(title);
                            break;
                    }
                }
 
                return true;
            }
            catch { return false; }
        }
 
        /// <summary>
        /// 非分支节点的统一调用方式
        /// </summary>
        private void RunNodeAsync(FlowNode node)
        {
            // 走默认分支
            node.BranchIndex = "0";
            string ProcessName = node.Text;
            try
            {
                if (dicContext.TryGetValue(ProcessName, out IProcess obj)
                    && obj is IProcess process)
                {
                    process.InputImage = null;
                    UpdateInputs(process);
 
                    // 不同节点跳过的方式不同
                    if (node.Break)
                    {
                        switch (node.Description)
                        {
                            case "T306通讯":
                                node.BranchIndex = "0";
                                node.Result = true;
                                process.Result = false;
                                process.Msg = "T306通讯未启用";
                                return;
                            default:
                                node.BranchIndex = "0";
                                node.Result = true;
                                process.Result = true;
                                process.Msg = string.Empty;
                                return;
                        }
                    }
 
                    if (!process.Run())
                    {
                        node.Result = false;
                        Result &= false;
 
                        if (!string.IsNullOrEmpty(process.Msg)
                            && !Msg.Contains($"[{process.strProcessName}]{process.Msg}"))
                            Msg += $"[{process.strProcessName}]{process.Msg}";
                    }
                    else
                        node.Result = true;
                }
            }
            catch (Exception ex)
            {
                node.Result = false;
                Result &= false;
                Msg += $"[{ProcessName}]运行发生意外,{ex.Message}";
            }
        }
 
 
        #region 注册工具事件
 
        [Node("相机取图", "取像工具", "Basic", "相机取图")]
        public void 相机取图(FlowNode node) { RunNodeAsync(node); }
 
        [Node("Halcon2D斑点工具", "Haclon2D工具", "Basic", "Halcon2D斑点工具")]
        public void Halcon2D斑点工具(FlowNode node) { RunNodeAsync(node); }
 
 
        #endregion
 
 
 
 
 
        [Node("开始", "控制", "Logic", "开始")]
        public override void 开始(FlowNode node)
        {
            StartTime = DateTime.Now;
            RunTime = 0;
 
            Result = true;
            bRuning = true;
            bCompleted = false;
            Msg = string.Empty;
 
            HOperatorSet.ClearWindow(hWindowControl.HalconWindow);
            HOperatorSet.SetColor(hWindowControl.HalconWindow, "green");
        }
 
        [Node("结束", "控制", "Logic", "结束")]
        public override void 结束(FlowNode node)
        {
            bRuning = false;
            bCompleted = true;
 
            if (Result)
                Msg = "运行成功";
 
            RunTime = (DateTime.Now - StartTime).TotalMilliseconds;
        }
 
        [Node("分支", "控制", "Logic", "分支")]
        public override void 分支(FlowNode node)
        {
            string ProcessName = node.Text;
            node.BranchIndex = "-1";
            node.Result = true;
            try
            {
                if (dicContext.TryGetValue(ProcessName, out IProcess obj) && obj is ScriptTool script)
                {
                    UpdateInputs(script);
                    if (node.Break)
                    {
                        node.BranchIndex = "0";
                        node.Result = true;
                        script.Result = true;
                        script.Msg = string.Empty;
                        return;
                    }
 
                    if (script.Params.Outputs.Count >= 2)
                    {
                        if (!script.Run())
                        {
                            node.Result = false;
                            Result &= false;
                            Msg = $"[{ProcessName}]{script.Msg}";
                        }
 
                        for (int i = 0; i < script.Params.Outputs.Count; i++)
                        {
                            if (script.Params.Outputs[$"Branch{i}"] != null
                                && Convert.ToBoolean(script.Params.Outputs[$"Branch{i}"]))
                            {
                                node.BranchIndex = i.ToString();
                                return;
                            }
                        }
 
                        node.Result = false;
                        Result &= false;
                        Msg = $"[{ProcessName}]无满足条件的分支";
                    }
                    else
                    {
                        node.Result = false;
                        Result &= false;
                        Msg = $"[{ProcessName}]分支数量不为2";
                    }
                }
                else
                {
                    node.Result = false;
                    Result &= false;
                }
            }
            catch (Exception ex)
            {
                node.Result = false;
                Result &= false;
                Msg = $"[{ProcessName}]运行发生意外,{ex.Message}";
            }
        }
 
        [Node("多分支", "控制", "Logic", "多分支")]
        public override void 多分支(FlowNode node)
        {
            if (node.Break)
            {
                node.BranchIndex = "0";
                node.Result = true;
                return;
            }
 
            string ProcessName = node.Text;
            node.BranchIndex = "-1";
            node.Result = true;
            try
            {
                if (dicContext.TryGetValue(ProcessName, out IProcess obj) && obj is ScriptTool script)
                {
                    UpdateInputs(script);
                    if (node.Break)
                    {
                        node.BranchIndex = "0";
                        node.Result = true;
                        script.Result = true;
                        script.Msg = string.Empty;
                        return;
                    }
 
                    if (script.Params.Outputs.Count >= 1)
                    {
                        if (!script.Run())
                        {
                            node.Result = false;
                            Result &= false;
                            Msg = $"[{ProcessName}]{script.Msg}";
                        }
 
                        for (int i = 0; i < script.Params.Outputs.Count; i++)
                        {
                            if (script.Params.Outputs[$"Branch{i}"] != null
                                && Convert.ToBoolean(script.Params.Outputs[$"Branch{i}"]))
                            {
                                node.BranchIndex = i.ToString();
                                return;
                            }
                        }
 
                        node.Result = false;
                        Result &= false;
                        Msg = $"[{ProcessName}]无满足条件的分支";
                    }
                    else
                    {
                        node.Result = false;
                        Result &= false;
                        Msg = $"[{ProcessName}]多分支数量小于1";
                    }
                }
                else
                {
                    node.Result = false;
                    Result &= false;
                }
            }
            catch (Exception ex)
            {
                node.Result = false;
                Result &= false;
                Msg = $"[{ProcessName}]运行发生意外,{ex.Message}";
            }
        }
    }
}