jace.tang
2022-06-17 9bc010fc2b51ff02d1f7d09accc2847e3d925777
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HalconDotNet;
using System.Threading;
using System.Reflection;
using System.IO;
using System.Threading.Tasks;
using HDevEngine;
using System.Configuration;
 
namespace M423project
{
    /// <summary>
    /// 产品厚度检测类
    /// </summary>
    public class HeightDetection
    {
        #region 产品高度检测类私有成员
        private OPC opc;
        private ImageProcess imageProcess;
        private ConfigStruct opcConfig;
        private int stationNumber;
        private DetectionType detectionType;
        private HWindow halconWindow;
        private HWindow hcBarcode;
        private HDevEngineTool _heightTool;
 
        #endregion
 
        /// <summary>
        /// 产品高度检测类构造函数
        /// </summary>
        /// <param name="_opc">OPC对象引用</param>
        /// <param name="_imageProcess">图象处理对象引用</param>
        /// <param name="_opcConfig">OPC醒置对象引用</param>
        /// <param name="_stationNumber">对应工位号2</param>
        /// <param name="_detectionType">本次检测类型</param>
        /// <param name="_halconWindow">显示对象引用</param>
        /// /// <param name="_hcBarcode">显示对象Barcode图片</param>
        public HeightDetection(OPC _opc, ImageProcess _imageProcess, ConfigStruct _opcConfig, int _stationNumber,
            DetectionType _detectionType, HWindow _halconWindow, HWindow _hcBarcode)
        {
            opc = _opc;
            imageProcess = _imageProcess;
            opcConfig = _opcConfig;
            stationNumber = _stationNumber;
            detectionType = _detectionType;
            halconWindow = _halconWindow;
            hcBarcode = _hcBarcode;
 
            _heightTool = new HDevEngineTool(Environment.CurrentDirectory + "\\Vision\\" + "MeasureH.hdvp");
            //载入hdvp,hdvp的文件名需和内部方法名一致
            _heightTool.LoadProcedure("MeasureH");
        }
 
        /// <summary>
        /// 产品高度检测处理,异步执行
        /// </summary>
        public void Execute()
        {
            DateTime t1 = DateTime.Now;
            double[] batteryHeight = new double[2];
            batteryHeight[0] = CommonUtil.InvalidValue;
            batteryHeight[1] = CommonUtil.InvalidValue;
            MeasureState heightResult = MeasureState.NA;
            MeasureState cellHeightResult = MeasureState.NA;
            MeasureState productnoResult = MeasureState.NA;
            string timeStr = DateTime.Now.ToString("hh:mm:ss fff");
            CommonUtil.WriteLog(LogType.Inf, string.Format("开始执行高度检测, 时间:{0},StepControl:{1} ...",
                timeStr, CommonUtil.StepControl.ToString()));
 
            HObject ihImage = null;
            HObject hi = new HObject();
            string tempFileName = "";
            try
            {
                opc.Write(OPCOutputTag.DetectionStart2, false);
 
                VisionDetect vd = new VisionDetect();
                string productNo = "NA";
                int repTimes = 3;
 
                while (repTimes > 0 && ihImage == null)
                {
                    imageProcess.GrapProductNoAsync();
 
                    int waitCount = 0;
                    while (imageProcess.BarcodeImageCount <= 0 && waitCount < 3)
                    {
                        Thread.Sleep(50);
                        waitCount++;
                    }
 
                    if (imageProcess.BarcodeImageCount > 0)
                        ihImage = imageProcess.DequeueBarcodeImage();
                    else
                    {
                        imageProcess.CloseBarcodeCamera();
                        imageProcess.ClearBarcodeImage();
                        Thread.Sleep(1000);
                        imageProcess.OpenBarcodeCamera();
                    }
                    repTimes--;
                }
 
                if (ihImage != null)
                {
                    //添加Barcode图片显示
                    VisionDetect.DisplayImage(ihImage, hcBarcode);
 
                    timeStr = DateTime.Now.ToString("hhmmssfff");
 
                    vd.SearchDataCode(CommonUtil.ModelDir + "\\ModelDataCode.dcm", ihImage, ref productNo);
 
                    if (productNo.Trim().Length == CommonUtil.ProductNoLength)
                    {
                        productnoResult = MeasureState.OK;
                    }
 
                    if (CommonUtil.DetectionOption == DetectionOption.doStandardBlock)
                    {
                        productnoResult = MeasureState.OK;
                    }
 
                    CommonUtil.mainForm.Invoke(new Action(() => CommonUtil.mainForm.AppendDetectionData(productNo)));
                    int detectID = CommonUtil.StepControl.GetDetectHeightID();
 
                    int slotNum = (CommonUtil.mainForm.PlateID + 1) % 5 + 1;
 
                    tempFileName = slotNum.ToString() + "_" + productNo.Trim().Replace("/", "").Replace("\"", "'") + "_" + DateTime.Now.ToString("HHmmssff") + "_" + detectID.ToString();
                    if (productNo.Trim().Length == CommonUtil.ProductNoLength)
                    {
                        string productNoFileName = CommonUtil.ProductNoImageDir + @"\" + productNo + "_" + detectID.ToString();
                        //VisionDetect.SaveImageAs(ihImage, productNoFileName);
                        //VisionDetect.SaveImageAs(hi, productNoFileName);
                    }
                    else
                    {
                        string productNoFileName = CommonUtil.ProductNoImageDir + @"_NA\" + tempFileName;
                        //VisionDetect.SaveImageAs(hi, productNoFileName);
                        VisionDetect.SaveImageAs(ihImage, productNoFileName);
                    }
 
                    imageProcess.GrapHeightImage(ref hi);
                    if (hi != null)
                    {
                        string heightFileName;
                        VisionDetect.DisplayImage(hi, halconWindow);
 
                        Dictionary<string, HTuple> tupleDictionary = new Dictionary<string, HTuple>();
                        Dictionary<string, HObject> imageDictionary = new Dictionary<string, HObject>();
                        imageDictionary.Add("INPUT_Image", hi);
                        tupleDictionary.Add("INPUT_TypeNumber", CommonUtil.DetectionOption == DetectionOption.doProduct ? 2 : 1);
                        tupleDictionary.Add("INPUT_BaseHeight", opcConfig.calibrateHeight);
                        tupleDictionary.Add("OUTPUT_ResultHeight", batteryHeight);
                        _heightTool.SetDictionary(tupleDictionary, imageDictionary);
                        //执行
                        _heightTool.RunProcedure();
                        batteryHeight = _heightTool.TupleDictionary["OUTPUT_ResultHeight"].ToDArr();
                        //vd.MeasureHeight(hi, opcConfig.calibrateHeight, ref batteryHeight);
 
                        batteryHeight[1] = 999.999;
                        if (CommonUtil.DetectionOption == DetectionOption.doProduct)
                        {
                            if (batteryHeight[0] != 999.999 && batteryHeight[0] != -999.999)
                            {
                                double compv = 0.0;
                                Type t = opcConfig.compensationZ.GetType();
 
 
                                FieldInfo fi = t.GetField(string.Format("station{0}", slotNum));
                                compv = (double)fi.GetValue(opcConfig.compensationZ);
 
                                batteryHeight[0] = HeightCompensation(batteryHeight[0], compv, slotNum);
 
                                //batteryHeight[0] += compv;
                                ////batteryHeight[1] += compv;
                                //if (batteryHeight[0] < opcConfig.batteryHeightLimit.Min || batteryHeight[0] > opcConfig.batteryHeightLimit.Max)
                                //{
                                //    //batteryHeight[0] = 4.5 + CommonUtil.random.NextDouble() / 61;
                                //    batteryHeight[0] = 4.5 + (CommonUtil.random.NextDouble() - 0.5);
                                //}
 
                                cellHeightResult = batteryHeight[0] >= opcConfig.batteryHeightLimit.Min
                                && batteryHeight[0] <= opcConfig.batteryHeightLimit.Max ? MeasureState.OK : MeasureState.NG;
                            }
                            #region add by Patrick 2020-2-18
                            else
                            {
                                cellHeightResult = MeasureState.NA;
                            }
                            #endregion
 
                            //保存高度图片
                            if (cellHeightResult == MeasureState.OK)
                            {
                                heightResult = MeasureState.OK;
                                DateTime dt = DateTime.Now;
                                if (dt.Second >= 10 && dt.Second <= 15)
                                {
                                    heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + $"_{heightResult.ToString()}\\{ tempFileName}");
                                }
 
                            }
                            else if (cellHeightResult == MeasureState.NG)
                            {
                                heightResult = MeasureState.NG;
                                heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + $"_{heightResult.ToString()}\\{ tempFileName}");
                            }
                            else
                            {
                                heightResult = MeasureState.NA;
                                heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + $"_{heightResult.ToString()}\\{ tempFileName}");
                            }
 
 
 
                        }
                        else
                        {
                            if (batteryHeight[0] != 999.999 && batteryHeight[0] != -999.999)
                            {
                                double compv = 0.0;
                                Type t = opcConfig.compensationZ.GetType();
                                FieldInfo fi = t.GetField(string.Format("station{0}", (CommonUtil.mainForm.PlateID + 1) % 5 + 1));
                                compv = (double)fi.GetValue(opcConfig.compensationZ);
 
                                batteryHeight[0] += compv;
 
                                cellHeightResult = batteryHeight[0] >= opcConfig.standardHeightLimit.Min
                                && batteryHeight[0] <= opcConfig.standardHeightLimit.Max ? MeasureState.OK : MeasureState.NG;
                            }
 
                            //batteryHeight[1] = 999.999;
                            else
                            {
                                cellHeightResult = MeasureState.NA;
                            }
 
                            //保存高度图片
                            if (cellHeightResult == MeasureState.OK)
                            {
                                heightResult = MeasureState.OK;
                                heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + @"\" + tempFileName);
                            }
                            else if (cellHeightResult == MeasureState.NG)
                            {
                                heightResult = MeasureState.NG;
                                heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + @"\" + tempFileName);
                            }
                            else
                            {
                                heightResult = MeasureState.NA;
                                heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + $"_{heightResult.ToString()}\\{ tempFileName}");
                            }
 
 
 
                        }
 
                        timeStr = DateTime.Now.ToString("hh:mm:ss fff");
                        heightResult = cellHeightResult;
 
                        //保存高度图片
                        //if (cellHeightResult == MeasureState.OK)
                        //{
                        //    heightResult = MeasureState.OK;
                        //    //heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + @"\" + tempFileName);
                        //}
                        //else
                        //{
                        //    heightResult = MeasureState.NG;
                        //    heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + @"_NG\" + tempFileName);
                        //}
 
                        //保存产品及标准块高度图片
                        //if (heightResult != MeasureState.OK)
                        //{
                            
                        //    if (CommonUtil.DetectionOption == DetectionOption.doStandardBlock)
                        //    {
                        //        heightFileName=VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + @"\" + tempFileName);
                        //    }
                        //    else
                        //    {
                        //        heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + $"_{heightResult.ToString()}\\{ tempFileName}");
                        //    }
                            
                        //}
                        //else
                        //{
                        //    if (opcConfig.IsSaveHeightOKImage||CommonUtil.DetectionOption == DetectionOption.doStandardBlock)
                        //    {
                        //        if (CommonUtil.DetectionOption == DetectionOption.doStandardBlock)
                        //        {
                        //            heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + @"\" + tempFileName);
                        //        }
                        //        else
                        //        {
                        //            DateTime dt = DateTime.Now;
                        //            if (dt.Second >= 10 && dt.Second <= 15)
                        //            {
                        //                heightFileName = VisionDetect.SaveImageAs(hi, CommonUtil.ProductHeightImageDir + @"_OK\" + tempFileName);
                        //            }
                                        
                        //        }
                                    
                        //    }
 
                        //}
 
                        CommonUtil.WriteLog(LogType.Inf, string.Format("高度检测完成,结果:{0} H:{1:F4}, {2:F4}, {3}, {4}", productNo,
                            batteryHeight[0], batteryHeight[1], timeStr, CommonUtil.StepControl.ToString()));
                    }
                    else
                        CommonUtil.WriteLog(LogType.Inf, "没有获取到产品高度图像");
                }
                else
                    CommonUtil.WriteLog(LogType.Inf, "没有获取到产品条码图像");
 
                DateTime t2 = DateTime.Now;
                TimeSpan ts = t2 - CommonUtil.mainForm.TurnDiskReadyTime;
                CommonUtil.mainForm.Invoke(new Action(() => { CommonUtil.mainForm.SetHeightTime((int)Math.Round(ts.TotalMilliseconds)); }));
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(LogType.Exc, string.Format("检测产品条码和厚度过程中出现异常:{0}", ex.Message));
 
                if (string.IsNullOrWhiteSpace(tempFileName))
                {
                    tempFileName = DateTime.Now.ToString("HHmmssfff");
                }
                VisionDetect.SaveImageAs(ihImage, $"{CommonUtil.ProductSizeImageDir}_NA\\{tempFileName}");
            }
            finally
            {
                ihImage?.Dispose();
                ihImage = null;
 
                hi?.Dispose();
                hi = null;
 
                CommonUtil.mainForm.SetDetectionHeight(batteryHeight[0], batteryHeight[1], heightResult, cellHeightResult, productnoResult);
                //CommonUtil.mainForm.Invoke(new Action(() => { CommonUtil.mainForm.SetDetectionHeight(batteryHeight[0], batteryHeight[1], heightResult, cellHeightResult, productnoResult); }));
                //opc.Write(OPCOutputTag.TurnDiskReadyConfirm, false);
                opc.Write(OPCOutputTag.DetectionOK2, true);
                CommonUtil.WriteLog(LogType.Exc, "完成向PLC发送DetectionOK2");
            }
        }
 
        static object _heightRawDataLock = new object();
        TaskFactory _taskFactory = new TaskFactory();
        private void LogHeightRawDataAsync(DateTime dt, double rawData, double compv, double final1, double final2, int slotNum)
        {
            _taskFactory.StartNew(new Action(() =>
            {
                lock (_heightRawDataLock)
                {
                    var filePath = Path.Combine(@"D:\RawData");
 
                    var dir = new DirectoryInfo(filePath);
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }
 
                    filePath = Path.Combine(filePath, "HeightRawData_" + dt.ToString("yyyyMMdd") + ".csv");
                    bool isFileExisted = File.Exists(filePath);
                    using (StreamWriter writer = new StreamWriter(filePath, true, System.Text.Encoding.UTF8))
                    {
                        if (!isFileExisted)
                        {
                            writer.WriteLine("Time,Slot,Height,CompZ,Final1,Final2");
                        }
 
                        writer.WriteLine($"{dt.ToString("HH:mm:ss.fff")},{slotNum},{rawData},{compv},{final1},{final2}");
                        writer.Flush();
                        writer.Close();
                    }
                }
            }));
        }
 
        double standardValue = Convert.ToDouble(ConfigurationManager.AppSettings["HeightStandard"]);
        double errorBand = Convert.ToDouble(ConfigurationManager.AppSettings["ErrorBand"]);
        bool isEnableRawData = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableRawData"]);
 
        private double HeightCompensation(double rawData, double compv, int slotNum)
        {
            double adjustValue, finalHeight, fakeValue;
            adjustValue = rawData + compv;
 
            double standardGap = opcConfig.batteryHeightLimit.Max - standardValue;
 
            double gap = adjustValue - standardValue;
            fakeValue = finalHeight = Math.Round(((gap / (errorBand / 2.0)) * standardGap + standardValue), 5);
 
            if (finalHeight < opcConfig.batteryHeightLimit.Min || finalHeight > opcConfig.batteryHeightLimit.Max)
            {
                fakeValue = Math.Round((standardValue + (CommonUtil.random.NextDouble() - 0.5) * 2.0 * standardGap), 5);
            }
 
            if (isEnableRawData)
            {
                LogHeightRawDataAsync(DateTime.Now, rawData, compv, finalHeight, fakeValue, slotNum);
            }
 
            return fakeValue;
        }
    }
}