M182轴承端盖外观缺陷AOI
kingno
2025-09-18 1894ccc4014d813ea60cf276ac066e5870a82566
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
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 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;
        }
 
 
        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 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()}");
                }
            });
        }
 
        protected List<ISpec> GenerateSpecByMeasureItems(List<MeasureItemBind> measureItems)
        {
            List<ISpec> measureSpecs = new List<ISpec>();
 
            measureItems.ForEach(m =>
            {
                var originSpec = M141Config.SpecCollection.FirstOrDefault(u => u.Code == m.SpecCode);
                if (originSpec == null)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"{m.SpecCode}设置的检测标准未能在配置中获取");
                    return;
                }
 
                if (m.IsSubscribeSpecForPoints)
                {
                    int index = 0;
                    m.MeasurePointNameCollection.ForEach(mp =>
                    {
                        var spec_p = originSpec.Copy<Spec>();
                        spec_p.Code = mp.MeasurePointName;
                        spec_p.OutputIndex = index;
 
                        measureSpecs.Add(spec_p);
 
                        index++;
                    });
                }
                else
                {
                    var spec = originSpec.Copy<Spec>();
                    if (!string.IsNullOrWhiteSpace(m.FAIName))
                    {
                        spec.Code = m.FAIName;
                    }
                    measureSpecs.Add(spec);
                }
            });
 
            return measureSpecs;
        }
 
        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 waitTimes = 1;
            if (p.Details.Any(u => u.IsDone == false) && waitTimes > 0)
            {
             
                waitTimes--;
            }
 
            if (waitTimes == 0)
            {
                var unfinishedPositions = p.Details.Where(u => u.IsDone == false).Select(u => u.PositionName).ToList();
                if (unfinishedPositions.Count > 0)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"产品{string.Join(",", unfinishedPositions)}站点结果未完成");
                }
            }
 
            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, "");
 
    
            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)));
 
            //ReplyRealTimeData(p.DataTag as List<ContourPoint>, specList);
 
            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(() =>
            //{
            //    if (M141Config.IsEnableOEEDataUpload)
            //    {
            //        OEEDataUpload(M141Config.OEEConfig_WorkPlace, p.SN, p.Details.SelectMany(u => u.ResultList).ToList());
            //    }
            //});
 
            _taskFactory.StartNew(() =>
            {
                if (string.IsNullOrWhiteSpace(_csvHead))
                {
                    _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);
            });
 
     
        }
 
 
 
    
    }
}