quanzhou
2 天以前 86f899fa91e811415614dff1a699141144bfc802
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using Bro.Common.Model;
using Bro.DataBase.Model;
using Bro.M135.Common;
using Bro.M135.DBManager;
using Bro.UI.Model.Winform;
using HalconDotNet;
using Microsoft.VisualBasic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.Util;
using NPOI.XSSF.UserModel;
using Sunny.UI;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Drawing.Imaging;
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;
using File = System.IO.File;
 
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();
            int numplca = Plc1.Read(1536, 1, out _)[0];
            string inputSequence = numplca.ToString();
 
            var productList = new List<int>() { 1 }.Select(u =>
            {
                string sequence = $"{inputSequence}_{u}";
                return FindProductBySequence(sequence, true);
            }).ToList();
 
            if (PlcNumForAll == -1)
            {
                PlcNumForAll = numplca;
            }
 
            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.ClassName == productList[0].Result);
 
            if (M141Config.StationCode == "S4" && productList[0].Result == "OK")
            {
                ////mysqlhelper.GetS2Result(productList[0].SEQUENCE);
                Plc1.WriteSingleAddress(1526, mysqlhelper.GetS2Result(productList[0].SEQUENCE) ? 1 : 2, out _);
 
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"产品{string.Join(",", productList.Select(u => u.PID))}检测反馈{mysqlhelper.GetS2Result(productList[0].SEQUENCE)}");
            }
            else
            {
                Plc1.WriteSingleAddress(1526, Defaultclass?.ClassValue ?? 2, out _);
            }
 
            Plc1.WriteSingleAddress(1516, 1, out _);
 
            //if (M141Config.ISupMES && (M141Config.MESchannel == -1 || M141Config.MESchannel == 1))
            //{
            //    if (M141Config.numpro >= 50)
            //    {
            //        M141Config.numpro = 0;
            //    }
 
            //    if (productList[0].Result == "OK")
            //    {
            //        M141Config.numpro++;
            //    }
 
            //    //mqtt.demes(productList[0], M141Config.zwoid);
            //    string Msgreceice = Task.Run(() => mqtt.MESForProduceAsync(productList[0], M141Config.zwoid, M141Config.numpro)).Result;
            //    if (Msgreceice == null)
            //    {
            //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"产品{productList[0].PID}数据上传MES异常 返回数据为null");
            //    }
            //    else
            //    {
            //        try
            //        {
            //            var obj = JsonConvert.DeserializeObject<AutoLineMacBarcodeQueueBak>(Msgreceice);
 
            //            if (obj.zstatus == "200")
            //            {
            //                LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"产品{productList[0].PID}数据上传MES成功  {Msgreceice}");
            //            }
            //            else
            //            {
            //                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"产品{productList[0].PID}数据上传MES失败  {Msgreceice}");
            //            }
            //        }
            //        catch
            //        {
            //            LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"产品{productList[0].PID}数据上传MES异常  {Msgreceice}");
            //        }
            //    }
 
 
 
            //    lock (plcnumlock)
            //    {
            //        int differ = numplca - PlcNumForAll;
            //        if (differ > 1)
            //        {
            //            for (int i = PlcNumForAll + 1; i < numplca; i++)
            //            {
            //                try
            //                {
            //                    var plist = mysqlhelper.GetProductList(i + "_1");
            //                    ProductModel newp = new ProductModel();
            //                    newp.SEQUENCE = plist[0].SEQUENCE;
            //                    newp.PID = plist[0].PID;
            //                    newp.BasketCode = plist[0].BasketCode;
            //                    newp.Result = "NG";
            //                    newp.SN = plist[0].SN;
            //                    var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.zwoid, M141Config.numpro)).Result;
 
            //                }
            //                catch
            //                {
 
            //                }
            //            }
            //        }
            //        else if (differ != -29998)
            //        {
            //            for (int i = PlcNumForAll + 1; i <= 29999; i++)
            //            {
            //                try
            //                {
            //                    var plist = mysqlhelper.GetProductList(i + "_1");
            //                    ProductModel newp = new ProductModel();
            //                    newp.SEQUENCE = plist[0].SEQUENCE;
            //                    newp.PID = plist[0].PID;
            //                    newp.BasketCode = plist[0].BasketCode;
            //                    newp.Result = "NG";
            //                    newp.SN = plist[0].SN;
            //                    var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.zwoid, M141Config.numpro)).Result;
 
            //                }
            //                catch
            //                {
 
            //                }
            //            }
 
 
 
            //            for (int i = 1; i < numplca; i++)
            //            {
            //                try
            //                {
            //                    var plist = mysqlhelper.GetProductList(i + "_1");
            //                    ProductModel newp = new ProductModel();
            //                    newp.SEQUENCE = plist[0].SEQUENCE;
            //                    newp.PID = plist[0].PID;
            //                    newp.BasketCode = plist[0].BasketCode;
            //                    newp.Result = "NG";
            //                    newp.SN = plist[0].SN;
            //                    var tems = Task.Run(() => mqtt.MESForProduceAsync(newp, M141Config.zwoid, M141Config.numpro)).Result;
 
            //                }
            //                catch
            //                {
 
            //                }
            //            }
 
 
            //        }
            //        PlcNumForAll = numplca;
            //    }
 
            //}
 
            return msg;
        }
 
        object plcnumlock = new object();
        int PlcNumForAll = -1;
 
        private bool _isDemoStarted = false;
        [ProcessMethod("OfflineDemo", "OfflineDemo", "离线测试", InvokeType.CalibInvoke)]
        public ResponseMessage OfflineDemo(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            if (config is OfflineDemoOperationConfig opConfig)
            {
                if (_isDemoStarted)
                {
                    _isDemoStarted = false;
                }
                else
                {
                    _isDemoStarted = true;
                    OfflineDemoAsync(opConfig.ImageFolder, opConfig.IsOK, opConfig.SaveImageTime);
                }
            }
 
            return new ResponseMessage();
        }
 
        private async void OfflineDemoAsync(string imageFolder, bool isok, int saveimagetime)
        {
            await Task.Run(() =>
            {
                var imageFileNames = new DirectoryInfo(imageFolder).GetFiles().Select(u => u.FullName).ToList();
 
                for (int i = 0; i < imageFileNames.Count; i++)
                {
                    if (!_isDemoStarted)
                    {
                        return;
                    }
                    var imageFile = Path.GetFileNameWithoutExtension(imageFileNames[i]);
                    if (imageFile.EndsWith("Fit"))
                    {
                        continue;
                    }
                    if (imageFile.EndsWith("OK") & isok == false)
                    {
                        continue;
                    }
                    if (imageFile.EndsWith("NG") & isok == true)
                    {
                        continue;
                    }
                    var nameDatas = imageFile.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    if (nameDatas.Count != 5)
                    {
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"文件{imageFile}命名不符合规范,不执行离线测试");
                        continue;
                    }
 
                    var sn = nameDatas[0] + "_1";
                    var imageSeq = nameDatas[2][^1].ToString();
                    var measureBind = M141Config.MeasureBindCollection.FirstOrDefault(u => u.ImageSaveSeq == imageSeq);
 
                    if (measureBind == null || !measureBind.IsFixed)
                    {
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"离线测试,工位{(measureBind == null ? "未匹配" : $"{measureBind.WorkPosition}未开启")}");
                        continue;
                    }
 
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"离线测试,产品{sn}开始工位{measureBind.WorkPosition}离线检测");
                    MLImageSet imgSet = new MLImageSet();
 
                    imgSet.HImage = new HalconDotNet.HImage(imageFileNames[i]);
                    imgSet.PID = sn;
 
                    var detectResults = ML.RunMLDetectionSync(imgSet, null, measureBind.DetectionId);
                    Thread.Sleep(saveimagetime);
                    imgSet.HImage?.Dispose();
                    imgSet.HImage = null;
 
                    Bitmap originImage = new Bitmap(imageFileNames[i]);
                    DetectResultSaveExcelAsync(detectResults, sn, originImage, DateTime.Now);
                }
            });
        }
 
        object _excelOpLock = new object();
        int _columnWidth = 0;
        int _columnWidth1 = 0;
 
        int _exportNum = 0;
 
        public async void DetectResultSaveExcelAsync(List<DetectResult> detectResults, string sn, Bitmap originImage, DateTime dt)
        {
            await Task.Run(() =>
            {
                if (detectResults.All(u => u.ResultState == EnumHelper.ResultState.OK))
                    return;
 
                try
                {
                    string excel_Path = Path.Combine(CSVHelper.BaseDirectory, $"{DateTime.Now.ToString("yyyyMMdd")}");
                    if (!Directory.Exists(excel_Path))//如果不存在就创建file文件夹
                    {
                        Directory.CreateDirectory(excel_Path);//创建该文件夹
                    }
                    excel_Path = Path.Combine(excel_Path, $"OfflineRecord_{DateTime.Now.ToString("yyyyMMdd")}.xlsx");
                    List<string> datas = new List<string>() { "检测时间", "SN", "缺陷名称", "位置", "缺陷面积", "实际面积", "缺陷截图1", "缺陷截图2" };
 
                    NPOI.SS.UserModel.IRow irow;
                    NPOI.SS.UserModel.ICell icell;
 
                    Interlocked.Increment(ref _exportNum);
                    lock (_excelOpLock)
                    {
                        if (!File.Exists(excel_Path))
                        {
                            XSSFWorkbook wb = new XSSFWorkbook();
                            ISheet sheet = wb.CreateSheet("DefectDetail");
                            irow = sheet.CreateRow(0);
                            for (int i = 0; i < datas.Count; i++)
                            {
                                icell = irow.CreateCell(i);
                                icell.SetCellValue(datas[i]);
                            }
                            FileStream fs = new FileStream(excel_Path, FileMode.OpenOrCreate, FileAccess.Write);
                            wb.Write(fs); fs.Close();
                            fs.Dispose();
                        }
 
                        using (FileStream newfs = new FileStream(excel_Path, FileMode.Open, FileAccess.ReadWrite))
                        {
                            //创建工作簿对象
                            XSSFWorkbook newwb = new XSSFWorkbook(newfs);
                            //根据工作表名获取工作簿对象,也可通过索引获取工作表wb.GetSheetAt(int index)
                            ISheet newsheet = newwb.GetSheet("DefectDetail");
                            int countrow = newsheet.LastRowNum + 1;
 
                            //ICellStyle hlink_style = newwb.CreateCellStyle();
                            //IFont hlink_font = newwb.CreateFont();
                            //hlink_font.Underline = FontUnderlineType.Single;
                            //hlink_font.Color = HSSFColor.Blue.Index;
                            //hlink_style.SetFont(hlink_font);
 
                            XSSFDrawing patriarchDefectImageFile = (XSSFDrawing)newsheet.CreateDrawingPatriarch();
 
                            var details = detectResults.SelectMany(u => u.NetResults).SelectMany(u => u.DetectDetails).Where(u => u.FinalResult != EnumHelper.ResultState.OK).ToList();
 
                            details.ForEach(d =>
                            {
                                //"检测时间", "SN", "缺陷名称", "位置", "缺陷面积", "实际面积", "缺陷截图1", "缺陷截图2"
                                List<string> data = new List<string>() { dt.ToString("HH:mm:ss.fff").ToString(), sn, d.ClassName, (d.Tag ?? "").ToString(), d.Area.ToString(), d.AreaInActual.ToString("f3") };
 
                                irow = newsheet.CreateRow(countrow);
 
                                for (int i = 0; i < datas.Count; i++)
                                {
                                    icell = irow.CreateCell(i);
 
                                    switch (i)
                                    {
                                        case 6:
                                            {
                                                byte[] bytesDefectImageFile = CaptureImage(originImage, (int)d.Rect.Width, (int)d.Rect.Height, (int)d.Rect.X, (int)d.Rect.Y, out int actWidth, out int actHeight);
                                                int pictureIdxDefectImageFile = newwb.AddPicture(bytesDefectImageFile, NPOI.SS.UserModel.PictureType.JPEG);
 
                                                // 插图片的位置  HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2) 后面再作解释
                                                XSSFClientAnchor anchorDefectImageFile = new XSSFClientAnchor(1, 1, 1, 1, i, countrow, i + 1, countrow + 1);
                                                //把图片插到相应的位置
                                                XSSFPicture pictDefectImageFile = (XSSFPicture)patriarchDefectImageFile.CreatePicture(anchorDefectImageFile, pictureIdxDefectImageFile);
 
                                                ////int colWidth = actWidth * 32;
                                                ////if (colWidth > _columnWidth)
                                                ////{
                                                ////    _columnWidth = colWidth;
                                                ////    newsheet.SetColumnWidth(i, _columnWidth);
                                                ////}
 
                                                irow.Height = (short)(actHeight * 16);
                                                //pictDefectImageFile.Resize();
                                            }
                                            break;
                                        case 7:
                                            {
                                                byte[] bytesDefectImageFile = CaptureImage(originImage, (int)d.Rect.Width, (int)d.Rect.Height, (int)d.Rect.X, (int)d.Rect.Y, out int actWidth, out int actHeight, d);
                                                int pictureIdxDefectImageFile = newwb.AddPicture(bytesDefectImageFile, NPOI.SS.UserModel.PictureType.JPEG);
 
                                                XSSFClientAnchor anchorDefectImageFile = new XSSFClientAnchor(1, 1, 1, 1, i, countrow, i + 5, countrow + 1);
                                                //把图片插到相应的位置
                                                XSSFPicture pictDefectImageFile = (XSSFPicture)patriarchDefectImageFile.CreatePicture(anchorDefectImageFile, pictureIdxDefectImageFile);
 
                                                //int colWidth = actWidth * 32;
                                                //if (colWidth > _columnWidth1)
                                                //{
                                                //    _columnWidth1 = colWidth;
                                                //    newsheet.SetColumnWidth(i, _columnWidth1);
                                                //}
                                                //pictDefectImageFile.Resize();
                                            }
                                            break;
                                        default:
                                            string strvalue = data[i];
                                            icell.SetCellValue(strvalue);
                                            break;
                                    }
                                }
                                countrow++;
 
                            });
 
                            using (var temp = File.OpenWrite(excel_Path))
                            {
                                newwb.Write(temp);//向打开的这个xls文件中写入数据 
                            }
                            newfs.Close();
                            newfs.Dispose();
                        }
                    }
                    Interlocked.Decrement(ref _exportNum);
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"{detectResults[0].PID}Excel输出完成,还有{_exportNum}条记录");
                }
                catch (Exception ex)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"{detectResults[0].PID}缺陷插入Excel报错:{ex.Message.ToString()}");
                }
                finally
                {
                    originImage.Dispose();
                    originImage = null;
                }
            });
        }
 
        int _spaceRemain = 60;
        //public byte[] CaptureImage(Bitmap originImage, int width, int height, int spaceX, int spaceY, out int actWidth, out int actHeight, DefectDetail defect = null)
        //{
        //    spaceX -= _spaceRemain;
        //    spaceY -= _spaceRemain;
 
        //    width += _spaceRemain * 2;
        //    height += _spaceRemain * 2;
 
        //    if (spaceX < 0)
        //    {
        //        spaceX = 0;
        //    }
 
        //    if (spaceY < 0)
        //    {
        //        spaceY = 0;
        //    }
 
        //    if (spaceX + width > originImage.Width)
        //    {
        //        width = originImage.Width - spaceX;
        //    }
 
        //    if (spaceY + height > originImage.Height)
        //    {
        //        height = originImage.Height - spaceY;
        //    }
 
        //    actHeight = height;
        //    actWidth = width;
 
        //    Bitmap imageBack = originImage;
 
        //    if (defect != null)
        //    {
        //        PolygonResultDisplay display = new PolygonResultDisplay(defect, defect.ClassName, Color.Red, false, (int)(width * GlobalVar.WIDTH_RATIO));
 
        //        imageBack = new Bitmap(originImage.Width, originImage.Height, PixelFormat.Format24bppRgb);
        //        using (Graphics g = Graphics.FromImage(imageBack))
        //        {
        //            g.DrawImage(originImage, 0, 0);
        //            display.Draw(g);
        //        }
        //    }
 
        //    //创建新图位图   
        //    Bitmap bitmap = new Bitmap(width, height, imageBack.PixelFormat);
        //    //创建作图区域   
        //    using (Graphics graphic = Graphics.FromImage(bitmap))
        //    {
        //        //截取原图相应区域写入作图区   
        //        graphic.DrawImage(imageBack, 0, 0, new Rectangle(spaceX, spaceY, width, height), GraphicsUnit.Pixel);
        //    }
 
        //    byte[] bt = null;
        //    using (MemoryStream mostream = new MemoryStream())
        //    {
        //        bitmap.Save(mostream, System.Drawing.Imaging.ImageFormat.Bmp);//将图像以指定的格式存入缓存内存流
        //        bt = new byte[mostream.Length];
        //        mostream.Position = 0;//设置留的初始位置
        //        mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
        //    }
 
        //    bitmap.Dispose();
        //    return bt;
        //}
 
        public byte[] CaptureImage(Bitmap originImage, int width, int height, int spaceX, int spaceY,
    out int actWidth, out int actHeight, DefectDetail defect = null)
        {
            spaceX -= _spaceRemain;
            spaceY -= _spaceRemain;
 
            width += _spaceRemain * 2;
            height += _spaceRemain * 2;
 
            if (spaceX < 0)
            {
                spaceX = 0;
            }
 
            if (spaceY < 0)
            {
                spaceY = 0;
            }
 
            if (spaceX + width > originImage.Width)
            {
                width = originImage.Width - spaceX;
            }
 
            if (spaceY + height > originImage.Height)
            {
                height = originImage.Height - spaceY;
            }
 
            actHeight = height;
            actWidth = width;
 
            Bitmap imageBack = originImage;
            bool needDisposeImageBack = false; // 新增:标记是否需要释放imageBack
 
            if (defect != null)
            {
                PolygonResultDisplay display = new PolygonResultDisplay(defect, defect.ClassName, Color.Red, false, (int)(width * GlobalVar.WIDTH_RATIO));
 
                // 修改点1:确保创建的Bitmap支持Graphics
                // 使用Format24bppRgb或Format32bppArgb
                imageBack = new Bitmap(originImage.Width, originImage.Height, PixelFormat.Format24bppRgb);
                needDisposeImageBack = true; // 标记为需要释放
 
                // 修改点2:检查原始图像格式,如果是索引格式需要特殊处理
                if (IsIndexedPixelFormat(originImage.PixelFormat))
                {
                    // 创建支持Graphics的格式
                    using (Bitmap tempImage = new Bitmap(originImage.Width, originImage.Height, PixelFormat.Format24bppRgb))
                    using (Graphics tempG = Graphics.FromImage(tempImage))
                    {
                        tempG.DrawImage(originImage, 0, 0);
 
                        using (Graphics g = Graphics.FromImage(imageBack))
                        {
                            g.DrawImage(tempImage, 0, 0);
                            display.Draw(g);
                        }
                    }
                }
                else
                {
                    // 原始代码逻辑
                    using (Graphics g = Graphics.FromImage(imageBack))
                    {
                        g.DrawImage(originImage, 0, 0);
                        display.Draw(g);
                    }
                }
            }
            else if (IsIndexedPixelFormat(originImage.PixelFormat))
            {
                // 修改点3:即使没有defect,如果是索引格式也需要转换
                imageBack = new Bitmap(originImage.Width, originImage.Height, PixelFormat.Format24bppRgb);
                needDisposeImageBack = true;
 
                using (Graphics g = Graphics.FromImage(imageBack))
                {
                    g.DrawImage(originImage, 0, 0);
                }
            }
 
            // 修改点4:确保bitmap的像素格式支持Graphics
            PixelFormat bitmapFormat = imageBack.PixelFormat;
            if (IsIndexedPixelFormat(bitmapFormat))
            {
                // 如果imageBack仍然是索引格式(理论上不应该),转换为支持格式
                bitmapFormat = PixelFormat.Format24bppRgb;
            }
 
            //创建新图位图   
            Bitmap bitmap = new Bitmap(width, height, bitmapFormat);
 
            //创建作图区域   
            using (Graphics graphic = Graphics.FromImage(bitmap))
            {
                //截取原图相应区域写入作图区   
                graphic.DrawImage(imageBack, 0, 0, new Rectangle(spaceX, spaceY, width, height), GraphicsUnit.Pixel);
            }
 
            byte[] bt = null;
            using (MemoryStream mostream = new MemoryStream())
            {
                bitmap.Save(mostream, System.Drawing.Imaging.ImageFormat.Bmp);//将图像以指定的格式存入缓存内存流
                bt = new byte[mostream.Length];
                mostream.Position = 0;//设置留的初始位置
                mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
            }
 
            bitmap.Dispose();
 
            // 修改点5:释放临时创建的imageBack
            if (needDisposeImageBack && imageBack != originImage)
            {
                imageBack.Dispose();
            }
 
            return bt;
        }
 
        // 新增辅助方法:检查是否为索引像素格式
        private bool IsIndexedPixelFormat(PixelFormat format)
        {
            return format == PixelFormat.Format1bppIndexed ||
                   format == PixelFormat.Format4bppIndexed ||
                   format == PixelFormat.Format8bppIndexed ||
                   format == PixelFormat.Indexed;
        }
 
        [ProcessMethod("printer", "printer", "打印机打印", InvokeType.TestInvoke)]
        public ResponseMessage Printer(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ResponseMessage msg = new ResponseMessage();
 
            Plc2 = invokeDevice as PLCBase;
            //string message = "nothing";
            if (M141Config.MES_codes.Count >= 1)
            {
                string message = M141Config.MES_codes[0].Printers_code;
                StartPrint(message, "Honeywell PX240S(300 dpi)1");
                M141Config.MES_codes.RemoveAt(0);
            }                               
            return msg;
        }
 
 
        public void PlcwritePrinter(int add, int value)
        {
            Plc2.WriteSingleAddress(add, value, out _);
        }
 
 
 
 
 
 
        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();
                    temp.ActualValue = null;
                    temp.MeasureResult = null;
                    temp.Source = "";
                    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;
 
            int num = 0;
 
            while (p.Details.Any(u => !u.IsDone) && num < 10)
            {
                num++;
                Thread.Sleep(500);
            }
 
 
            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<ISpec>()).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, "", p.ImagePaths);
 
            //产品序号+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, string name)
        {
            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);
                CSVRecordAsync(name, p.GetCSVData(_specHeadList, _positionList), _csvHead);
                //_manager_P_Product.UpdateProductResult(p.ID, p.PID, p.SN, p.Result);
            });
 
            //连续NG数据记录
            CheckContinuousNGAlarmAsync(p);
        }
 
 
 
        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; }
        }
 
 
 
 
      
 
 
 
 
    }
}