kingno
2025-04-01 2120c4a86e6b7bfe2b8e27f79c0ebe2efddbc0e0
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
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using Bro.Common.Model;
using Bro.M135.Common;
using HalconDotNet;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Text.Encodings.Web;
using System.Windows.Forms;
using System.Xml.Linq;
using static NPOI.HSSF.Util.HSSFColor;
using static System.Net.Mime.MediaTypeNames;
using static System.Net.WebRequestMethods;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
 
namespace Bro.M141.Process
{
    public partial class M141Process
    {
        Dictionary<string, List<double>> dicdate = new Dictionary<string, List<double>>();
        ManualResetEvent set1 = new ManualResetEvent(false);
        ManualResetEvent set2 = new ManualResetEvent(false);
 
        [ProcessMethod("ImageCheck", "ImageCheckOperation", "通用图片检测操作", InvokeType.TestInvoke)]
        public ResponseMessage ImageCheckOperation(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
 
            ResponseMessage msg = new ResponseMessage();
 
            if (config is IImageCheckOperationConfig opConfig)
            {
 
                var results = opConfig.Products.Select(u =>
                {
                    DetectResult result = new DetectResult();
                    result.PID = u.PID;
                    result.Specs = GetSpecListFromConfigSelection(opConfig.SpecCollection);
                    return result;
                }).ToList();
 
                msg.DataObj = results;
 
 
                var tool = GetHalconTool(null, "", opConfig.AlgorithemPath);
                Tuple<bool, Dictionary<string, HTuple>, Dictionary<string, HObject>, string, int> ret = null;
 
 
                //if (opConfig.BDstate)
                //{
                //    List<double> bdlist = M141Config.BDCollection.FirstOrDefault(u => u.CameraId == opConfig.ExecuteDevice && u.CheckIndex == opConfig.BDindex)?.BDList;
                //    if (bdlist == null)
                //    {
                //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"未找到标定配置,序号{opConfig.BDindex}");
                //        return msg;
                //    }
                //    ret = tool.RunProcedure(new Dictionary<string, HTuple>() { { "INPUT_CalibrationData", bdlist.ToArray() } }, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
                //}
                //else
                {
                    ret = tool.RunProcedure(null, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
                }
 
 
                //var ret = tool.RunProcedure(null, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
 
                if (!ret.Item1)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"脚本{opConfig.AlgorithemPath}运行异常,{ret.Item4}");
                }
                else
                {
                    //for (int i = 1; i <= 2; i++)
                    //{
                    //    var p = opConfig.Products.FirstOrDefault(u => u.SEQUENCE.EndsWith(i.ToString()));
                    //    if (p != null)
                    //    {
                    //        var pResult = results.FirstOrDefault(u => u.PID == p.PID);
                    //        var datas = ret.Item2[$"OUTPUT_Results_{i}"].HTupleToDouble();
 
                    //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"当前脚本结果OUTPUT_Results_{i}:{string.Join(",", datas.Select(u => u.ToString("f3")))}");
 
                    //        if (pResult != null && datas.Count > 0)
                    //        {
                    //            FillSpecResults(pResult.PID, pResult.Specs, datas);
                    //        }
                    //    }
                    //}
 
                    opConfig.Products.ForEach(p =>
                    {
                        var pResult = results.FirstOrDefault(u => u.PID == p.PID);
 
                        string i = p.SEQUENCE[p.SEQUENCE.Length - 1].ToString();
                        var datas = ret.Item2[$"OUTPUT_Results_{i}"].HTupleToDouble();
 
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"当前脚本结果OUTPUT_Results_{i}:{string.Join(",", datas.Select(u => u.ToString("f3")))}");
 
                        if (pResult != null && datas.Count > 0)
                        {
                            FillSpecResults(pResult.PID, pResult.Specs, datas, p.SEQUENCE);
                        }
                    });
                }
            }
 
            return msg;
        }
 
        [ProcessMethod("ImageCheck", "ImageCheckOperation2", "通用图片检测操作,数据交互输出", InvokeType.TestInvoke)]
        public ResponseMessage ImageCheckOperationOUT(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ResponseMessage msg = new ResponseMessage();
 
            if (config is IImageCheckOperationConfig opConfig)
            {
                var results = opConfig.Products.Select(u =>
                {
                    DetectResult result = new DetectResult();
                    result.PID = u.PID;
                    result.Specs = GetSpecListFromConfigSelection(opConfig.SpecCollection);
                    return result;
                }).ToList();
 
                msg.DataObj = results;
 
 
                var tool = GetHalconTool(null, "", opConfig.AlgorithemPath);
                Tuple<bool, Dictionary<string, HTuple>, Dictionary<string, HObject>, string, int> ret = null;
 
 
 
                //if (opConfig.BDstate)
                //{
                //    List<double> bdlist = M141Config.BDCollection.FirstOrDefault(u => u.CameraId == opConfig.ExecuteDevice && u.CheckIndex == opConfig.BDindex)?.BDList;
                //    if (bdlist == null)
                //    {
                //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"未找到标定配置,序号{opConfig.BDindex}");
                //        return msg;
                //    }
                //    ret = tool.RunProcedure(new Dictionary<string, HTuple>() { { "INPUT_CalibrationData", bdlist.ToArray() } }, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2", "OUTPUT_TransmitData" }, null);
                //}
                //else
                {
                    ret = tool.RunProcedure(null, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2", "OUTPUT_TransmitData" }, null);
                }
 
 
                //var ret = tool.RunProcedure(null, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
 
                if (!ret.Item1)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"脚本{opConfig.AlgorithemPath}运行异常,{ret.Item4}");
                }
                else
                {
                    //for (int i = 1; i <= 2; i++)
                    //{
                    //    var p = opConfig.Products.FirstOrDefault(u => u.SEQUENCE.EndsWith(i.ToString()));
                    //    if (p != null)
                    //    {
                    //        var pResult = results.FirstOrDefault(u => u.PID == p.PID);
                    //        var datas = ret.Item2[$"OUTPUT_Results_{i}"].HTupleToDouble();
 
                    //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"当前脚本结果OUTPUT_Results_{i}:{string.Join(",", datas.Select(u => u.ToString("f3")))}");
 
                    //        if (pResult != null && datas.Count > 0)
                    //        {
                    //            FillSpecResults(pResult.PID, pResult.Specs, datas);
                    //        }
                    //    }
                    //}
 
                    opConfig.Products.ForEach(p =>
                    {
                        var pResult = results.FirstOrDefault(u => u.PID == p.PID);
                        string i = p.SEQUENCE[p.SEQUENCE.Length - 1].ToString();
                        var datas = ret.Item2[$"OUTPUT_Results_{i}"].HTupleToDouble();
                        dicdate[i] = ret.Item2["OUTPUT_TransmitData"].HTupleToDouble();
 
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"数据交互输出{i}  {string.Join(",", dicdate[i])}");
                        if (i == "1")
                        {
                            set1.Set();
                        }
                        else
                        {
                            set2.Set();
                        }
 
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"当前脚本结果OUTPUT_Results_{i}:{string.Join(",", datas.Select(u => u.ToString("f3")))}");
 
                        if (pResult != null && datas.Count > 0)
                        {
                            FillSpecResults(pResult.PID, pResult.Specs, datas, p.SEQUENCE);
                        }
                    });
                }
            }
 
            return msg;
        }
 
        [ProcessMethod("ImageCheck", "ImageCheckOperation3", "通用图片检测操作,数据交互输入,不清数据", InvokeType.TestInvoke)]
        public ResponseMessage ImageCheckOperationIN1(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ResponseMessage msg = new ResponseMessage();
 
            if (config is IImageCheckOperationConfig opConfig)
            {
                var results = opConfig.Products.Select(u =>
                {
                    DetectResult result = new DetectResult();
                    result.PID = u.PID;
                    result.Specs = GetSpecListFromConfigSelection(opConfig.SpecCollection);
                    return result;
                }).ToList();
 
                msg.DataObj = results;
 
 
                var tool = GetHalconTool(null, "", opConfig.AlgorithemPath);
                Tuple<bool, Dictionary<string, HTuple>, Dictionary<string, HObject>, string, int> ret = null;
 
 
                string index = "1";
                opConfig.Products.ForEach(p =>
                {
                    index = p.SEQUENCE[p.SEQUENCE.Length - 1].ToString();
                });
 
                if (dicdate[index].Count == 0)
                {
                    if (index == "1")
                    {
                        set1.Reset();
                        set1.WaitOne(3000);
                    }
                    else
                    {
                        set2.Reset();
                        set2.WaitOne(3000);
                    }
                }
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"数据交互输入{index}  {string.Join(",", dicdate[index])}");
                double[] tem = dicdate[index].ToArray();
 
 
                //if (opConfig.BDstate)
                //{
                //    List<double> bdlist = M141Config.BDCollection.FirstOrDefault(u => u.CameraId == opConfig.ExecuteDevice && u.CheckIndex == opConfig.BDindex)?.BDList;
                //    if (bdlist == null)
                //    {
                //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"未找到标定配置,序号{opConfig.BDindex}");
                //        return msg;
                //    }
 
 
                //    ret = tool.RunProcedure(new Dictionary<string, HTuple>() { { "INPUT_TransmitData", tem }, { "INPUT_CalibrationData", bdlist.ToArray() } }, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
 
                //}
                //else
                {
                    ret = tool.RunProcedure(new Dictionary<string, HTuple>() { { "INPUT_TransmitData", tem } }, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
                }
 
 
 
 
 
                ret = tool.RunProcedure(new Dictionary<string, HTuple>() { { "INPUT_TransmitData", tem } }, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
 
                //var ret = tool.RunProcedure(null, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
 
                if (!ret.Item1)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"脚本{opConfig.AlgorithemPath}运行异常,{ret.Item4}");
                }
                else
                {
                    //for (int i = 1; i <= 2; i++)
                    //{
                    //    var p = opConfig.Products.FirstOrDefault(u => u.SEQUENCE.EndsWith(i.ToString()));
                    //    if (p != null)
                    //    {
                    //        var pResult = results.FirstOrDefault(u => u.PID == p.PID);
                    //        var datas = ret.Item2[$"OUTPUT_Results_{i}"].HTupleToDouble();
 
                    //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"当前脚本结果OUTPUT_Results_{i}:{string.Join(",", datas.Select(u => u.ToString("f3")))}");
 
                    //        if (pResult != null && datas.Count > 0)
                    //        {
                    //            FillSpecResults(pResult.PID, pResult.Specs, datas);
                    //        }
                    //    }
                    //}
 
                    opConfig.Products.ForEach(p =>
                    {
                        var pResult = results.FirstOrDefault(u => u.PID == p.PID);
 
                        string i = p.SEQUENCE[p.SEQUENCE.Length - 1].ToString();
                        var datas = ret.Item2[$"OUTPUT_Results_{i}"].HTupleToDouble();
 
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"当前脚本结果OUTPUT_Results_{i}:{string.Join(",", datas.Select(u => u.ToString("f3")))}");
 
                        if (pResult != null && datas.Count > 0)
                        {
                            FillSpecResults(pResult.PID, pResult.Specs, datas, p.SEQUENCE);
                        }
                    });
                }
            }
 
            return msg;
        }
 
        [ProcessMethod("ImageCheck", "ImageCheckOperation4", "通用图片检测操作,数据交互输入,清数据", InvokeType.TestInvoke)]
        public ResponseMessage ImageCheckOperationIN2(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ResponseMessage msg = new ResponseMessage();
 
            if (config is IImageCheckOperationConfig opConfig)
            {
                var results = opConfig.Products.Select(u =>
                {
                    DetectResult result = new DetectResult();
                    result.PID = u.PID;
                    result.Specs = GetSpecListFromConfigSelection(opConfig.SpecCollection);
                    return result;
                }).ToList();
 
                msg.DataObj = results;
 
 
                var tool = GetHalconTool(null, "", opConfig.AlgorithemPath);
                Tuple<bool, Dictionary<string, HTuple>, Dictionary<string, HObject>, string, int> ret = null;
 
                string index = "1";
                opConfig.Products.ForEach(p =>
                {
                    index = p.SEQUENCE[p.SEQUENCE.Length - 1].ToString();
 
                });
 
                if (dicdate[index].Count == 0)
                {
                    if (index == "1")
                    {
                        set1.Reset();
                        set1.WaitOne(3000);
                    }
                    else
                    {
                        set2.Reset();
                        set2.WaitOne(3000);
                    }
                }
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"数据交互输入{index}  {string.Join(",", dicdate[index])}");
                double[] tem = dicdate[index].ToArray();
 
 
 
 
                //if (opConfig.BDstate)
                //{
                //    List<double> bdlist = M141Config.BDCollection.FirstOrDefault(u => u.CameraId == opConfig.ExecuteDevice && u.CheckIndex == opConfig.BDindex)?.BDList;
                //    if (bdlist == null)
                //    {
                //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"未找到标定配置,序号{opConfig.BDindex}");
                //        return msg;
                //    }
 
 
                //    ret = tool.RunProcedure(new Dictionary<string, HTuple>() { { "INPUT_TransmitData", tem }, { "INPUT_CalibrationData", bdlist.ToArray() } }, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
 
                //}
                //else
                {
                    ret = tool.RunProcedure(new Dictionary<string, HTuple>() { { "INPUT_TransmitData", tem } }, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
                }
                //ret = tool.RunProcedure(new Dictionary<string, HTuple>() { { "INPUT_TransmitData", tem } }, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
 
                dicdate[index].Clear();
 
                //var ret = tool.RunProcedure(null, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results_1", "OUTPUT_Results_2" }, null);
 
                if (!ret.Item1)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"脚本{opConfig.AlgorithemPath}运行异常,{ret.Item4}");
                }
                else
                {
                    //for (int i = 1; i <= 2; i++)
                    //{
                    //    var p = opConfig.Products.FirstOrDefault(u => u.SEQUENCE.EndsWith(i.ToString()));
                    //    if (p != null)
                    //    {
                    //        var pResult = results.FirstOrDefault(u => u.PID == p.PID);
                    //        var datas = ret.Item2[$"OUTPUT_Results_{i}"].HTupleToDouble();
 
                    //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"当前脚本结果OUTPUT_Results_{i}:{string.Join(",", datas.Select(u => u.ToString("f3")))}");
 
                    //        if (pResult != null && datas.Count > 0)
                    //        {
                    //            FillSpecResults(pResult.PID, pResult.Specs, datas);
                    //        }
                    //    }
                    //}
 
                    opConfig.Products.ForEach(p =>
                    {
                        var pResult = results.FirstOrDefault(u => u.PID == p.PID);
 
                        string i = p.SEQUENCE[p.SEQUENCE.Length - 1].ToString();
                        var datas = ret.Item2[$"OUTPUT_Results_{i}"].HTupleToDouble();
 
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"当前脚本结果OUTPUT_Results_{i}:{string.Join(",", datas.Select(u => u.ToString("f3")))}");
 
                        if (pResult != null && datas.Count > 0)
                        {
                            FillSpecResults(pResult.PID, pResult.Specs, datas, p.SEQUENCE);
                        }
                    });
                }
            }
 
            return msg;
        }
 
 
        [ProcessMethod("", "ProductDataUpload", "产品数据汇总", InvokeType.TestInvoke)]
        public ResponseMessage ProductDataUpload(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ResponseMessage msg = new ResponseMessage();
            string inputSequence = Plc1.Read(1536, 1, out _)[0].ToString();
 
            var productList = new List<int>() { 1 }.Select(u =>
            {
                string sequence = $"{inputSequence}_{u}";
                return FindProductBySequence(sequence, true);
            }).ToList();
 
 
            int waitInterval = 300;
            int repeatTime = M141Config.DetectTimeout / waitInterval;
 
            do
            {
                if (productList.All(p => !string.IsNullOrWhiteSpace(p.Result)))
                {
                    break;
                }
                else
                {
                    Thread.Sleep(waitInterval);
                    repeatTime--;
                }
 
                if (repeatTime < 0)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"产品{string.Join(",", productList.Select(u => u.PID))}检测获取汇总结果超时,使用当前结果");
                    break;
                }
            } while (true);
 
 
            var Defaultclass = M141Config.DefectClassCollection.FirstOrDefault(u => u.IsDefault);
            productList.ForEach(p =>
            {
                if (Defaultclass == null)
                {
                    if (string.IsNullOrEmpty(p.Result))
                    {
                        p.Result = "NG";
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(p.Result))
                    {
                        p.Result = Defaultclass.ClassName;
                    }
                }
 
                Plc1.WriteSingleAddress(1526, p.Result.ToUpper().Contains("NG") ? 2 : 1, out _);
            });
            Plc1.WriteSingleAddress(1516, 1, out _);
 
            return msg;
        }
 
 
 
 
        protected List<ISpec> GetSpecListFromConfigSelection(List<SpecSelector> specSelectors)
        {
            List<ISpec> specList = new List<ISpec>();
            specSelectors.ForEach(u =>
            {
                var spec = M141Config.SpecCollection.FirstOrDefault(s => s.Code == u.SpecCode);
                if (spec != null)
                {
                    var temp = spec.Copy<Spec>();
                    temp.ActualValue = null;
                    temp.MeasureResult = null;
                    specList.Add(temp);
                }
            });
            return specList;
        }
 
 
        protected List<ContourPoint> GetPointListFromConfigSelection(List<PointSelector> specSelectors)
        {
            List<ContourPoint> specList = new List<ContourPoint>();
            specSelectors.ForEach(u =>
            {
                var spec = M141Config.MeasurePointCollection.FirstOrDefault(s => s.Name == u.pointCode);
                if (spec != null)
                {
                    var temp = spec.Copy();
                    specList.Add(temp);
                }
            });
            return specList;
        }
 
        protected void FillSpecResults(string pid, List<ISpec> detectSpec, List<double> results, string SEQUENCE)
        {
            detectSpec.ForEach(s =>
            {
                if (!s.IsEnabled)
                    return;
 
                if (results.Count > s.OutputIndex)
                {
                    s.ActualValue = results[s.OutputIndex];
                    if (s.IsEnableCompensation && s.CompensationValue.Count > 1)
                    {
                        string index1 = SEQUENCE.Split('_')[SEQUENCE.Split('_').Count() - 1];
                        if (index1 == "2")
                        {
                            s.ActualValue += s.CompensationValue[1];
                        }
                        else
                        {
                            s.ActualValue += s.CompensationValue[0];
                        }
                    }
 
 
 
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{pid}检测项{s.Code}赋值{s.GetMeasureValueStr()},结果{s.GetMeasureResultStr()}");
                }
                else
                {
                    s.ActualValue = null;
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"产品{pid}检测项{s.Code}未能赋值,结果{s.GetMeasureResultStr()}");
                }
            });
        }
 
 
 
        DateTime? _ct = null;
 
 
        string _csvHead = "";
        List<string> _specHeadList = null;
        List<string> _positionList = new List<string>();
        private void UpdateProductResult(ProductModel p, out bool isOK)
        {
            isOK = false;
 
            p.InitialDetailSpecs();
            var resultList = p.Details.SelectMany(u => u.ResultList).ToList();
            resultList.ForEach(u => u.SetResult());
            var defects = resultList.GetDefectDescList();
 
            var ngSpecCodes = p.Details.SelectMany(u => u.SpecList ?? new List<Spec>()).Where(u => u.MeasureResult != true).Select(u => u.Code);
            var ngDefectDescList = p.Details.SelectMany(u => u.DefectList ?? new List<string>()).ToList();
 
            defects.AddRange(ngSpecCodes);
            defects.AddRange(ngDefectDescList);
 
            if (p.Details.Any(u => !u.IsDone))
            {
                defects.Add("TBD");
            }
            defects = defects.Distinct().ToList();
 
            isOK = defects.Count <= 0;
 
            UpdateDefectAsync(defects);
            var defectClass = GetDefectClassFromDefectList(defects);
            UpdateResult(DateTime.Now, p.SN, defectClass.ClassName, "");
 
            //产品序号+1
            Interlocked.Increment(ref _productIndex);
 
            List<ISpec> specList = new List<ISpec>();
            specList.AddRange(p.Details.SelectMany(u => u.SpecList).ToList().ConvertAll(u => (ISpec)u));
            specList.AddRange(p.Details.SelectMany(u => u.ResultList.SelectMany(d => d.Specs)));
 
 
 
            p.Result = defectClass.ClassName;
            p.EndTime = DateTime.Now;
 
            LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{p.PID} {p.SEQUENCE} {p.SN}检测结果{p.Result},缺陷明细:{string.Join(",", defects)}");
            //}
            //catch (Exception e)
            //{
            //    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, e.ToString());
            //}
        }
 
 
 
        private void UpdateProductResultAsync(ProductModel p)
        {
            UpdateProductResult(p, out bool isOK);
 
            _taskFactory.StartNew(() =>
            {
                _csvHead = p.GetCSVHead(ref _specHeadList, ref _positionList);
                CSVRecordAsync($"ProductRecord_{DateTime.Now.ToString("yyyyMMdd")}.csv", p.GetCSVData(_specHeadList, _positionList), _csvHead);
                //_manager_P_Product.UpdateProductResult(p.ID, p.PID, p.SN, p.Result);
            });
 
        }
 
 
 
        public bool HttpPost(string url, string postDataStr, out string Result, out StatusCode_en ResultStatus)
        {
 
 
            bool flag = false;
            Result = string.Empty;
            ResultStatus = new StatusCode_en();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response;
            try
            {
                request.Timeout = 2000;//连接MES超时不超过2S
                byte[] bytesToPost = System.Text.Encoding.UTF8.GetBytes(postDataStr); //转换为bytes数据
                request.Method = "POST";
                request.ContentType = "text/xml; charset=utf-8";
                //request.ContentLength = bytesToPost.Length;
 
                //                POST / CYWebService.asmx / X3221_AOI2_Upload HTTP / 1.1
                //Host: 10.8.0.66
                //Content - Type: application / x - www - form - urlencoded
                //Content - Length: length
 
                //json = string
 
                //request.ContentType = "application/json";
 
                //request.Headers["Authorization"] = "09a2815ab6814ea3a87166d2bf866085"; //客供
                //request.Headers["Content-MD5"] = "c69fac58411218a8f4a7b1f8e00cf791";//MD5解析
                request.Accept = "*/*";
                CookieContainer cookie = new CookieContainer();
                request.CookieContainer = cookie;
                #region 其他没有设置的参数
                //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);//添加长度后写入流后关闭不了,可能流方式不同问题
                //request.Referer = "";
                //request.Accept = "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                //request.Headers["Accept-Language"] = "zh-CN,zh;q=0.";
                //request.Headers["Accept-Charset"] = "GBK,utf-8;q=0.7,*;q=0.3";
                //request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1";
                //request.KeepAlive = true;
                //Stream myRequestStream = request.GetRequestStream();
                //StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));           
                //myStreamWriter.Write(bytesToPost);
                //myStreamWriter.Flush();
                //myStreamWriter.Close();
                #endregion
                Stream stream = request.GetRequestStream();
                byte[] bs = System.Text.Encoding.UTF8.GetBytes(postDataStr);
                stream.Write(bs, 0, bs.Length);
                stream.Flush();
                stream.Close();
                response = (HttpWebResponse)request.GetResponse();
 
                ResultStatus = new StatusCode_en
                {
                    StatusCode = (int)response.StatusCode,
                    StatusCodeDiscribe = response.StatusDescription,
                };
                response.Cookies = cookie.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                //获取全部返回值XML字符串
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                Result = myStreamReader.ReadToEnd();
                flag = true;
            }
            catch (WebException ex)
            {
                //response = (HttpWebResponse)ex.Response;//有些异常如操作超时,对象会为空,想要详细数据不建议加判断
                ResultStatus = new StatusCode_en
                {
                    ErrDiscribe = ex.Message
                };
                flag = false;
            }
            return flag;
        }
 
        public class StatusCode_en//结果合集
        {
            /// <summary>
            /// 状态码,如404
            /// </summary>
            public int StatusCode { get; set; }
            /// <summary>
            /// 状态描述,如NotFound
            /// </summary>
            public string StatusCodeDiscribe { get; set; }
            /// <summary>
            /// 错误描述,如
            /// </summary>
            public string ErrDiscribe { get; set; }
        }
 
        public class Mes_re//结果合集
        {
 
            public int code { get; set; }
 
            public string msg { get; set; }
 
            public object value { get; set; }
 
            public object data { get; set; }
        }
 
 
 
 
 
    }
}