kingno
5 天以前 caf4dd3c752f5982adcd3708d2e8f976f81ff49f
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
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using Bro.Common.Model;
using Bro.M135.Common;
using Bro.M141.Process;
using Bro.UI.Model.Winform;
using HalconDotNet;
using Newtonsoft.Json;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.Streaming.Values;
using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using static Bro.Common.Helper.EnumHelper;
using static NPOI.HSSF.Util.HSSFColor;
using static Org.BouncyCastle.Crypto.Engines.SM2Engine;
using static Org.BouncyCastle.Math.EC.ECCurve;
using static ScottPlot.Plottable.PopulationPlot;
 
namespace Bro.M141_AOI1.Process
{
    [Process("AOI1", EnumHelper.DeviceAttributeType.Device)]
    public class AOI1Process : M141Process
    {
        #region constructor
        public AOI1Process() : base() { }
        public AOI1Process(string productCode) : base(productCode) { }
        #endregion
 
        AOI1Config ConfigAOI1 => Config as AOI1Config;
 
        public override void Open()
        {
 
            //string configPath = @"C:\Users\30263\Desktop\666.txt";
 
            //string _configBackupStr = "";
            //using (StreamReader reader = new StreamReader(configPath, System.Text.Encoding.UTF8))
            //{
            //    _configBackupStr = reader.ReadToEnd();
 
            //}
 
            //ProductModel p = JsonConvert.DeserializeObject<ProductModel>(_configBackupStr, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
 
            base.Open();
        }
 
 
        [ProcessMethod("", "PositionCheck_P1", "工位1检测", InvokeType.TestInvoke)]
        public ResponseMessage PositionCheck_P1(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            var positionSet = M141Config.WorkPositionCollection.Where(u => u.IsEnabled).FirstOrDefault(u => u.TriggerValue == "1#");
            if (positionSet == null)
            {
                throw new ProcessException($"P1检测未能获取对应的可用工位信息");
            }
            var plcnum = Plc1.Read(positionSet.plcnum, 1, out _);
 
            config.TriggerStr = "1#,1,Str," + plcnum[0];
            ResponseMessage msg = RunImageCheck_plc(config);
            msg.IsReply = false;
 
            return msg;
        }
 
 
        [ProcessMethod("", "PositionCheck_P2", "工位2检测", InvokeType.TestInvoke)]
        public ResponseMessage PositionCheck_P2(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            var positionSet = M141Config.WorkPositionCollection.Where(u => u.IsEnabled).FirstOrDefault(u => u.TriggerValue == "2#");
            if (positionSet == null)
            {
                throw new ProcessException($"P2检测未能获取对应的可用工位信息");
            }
            var plcnum = Plc1.Read(positionSet.plcnum, 1, out _);
 
            config.TriggerStr = "2#,1,Str," + plcnum[0];
            ResponseMessage msg = RunImageCheck_plc(config);
            msg.IsReply = false;
 
            return msg;
        }
 
 
        [ProcessMethod("", "PositionCheck_P3", "工位3检测", InvokeType.TestInvoke)]
        public ResponseMessage PositionCheck_P3(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            var positionSet = M141Config.WorkPositionCollection.Where(u => u.IsEnabled).FirstOrDefault(u => u.TriggerValue == "3#");
            if (positionSet == null)
            {
                throw new ProcessException($"P3检测未能获取对应的可用工位信息");
            }
            var plcnum = Plc1.Read(positionSet.plcnum, 1, out _);
 
            config.TriggerStr = "3#,1,Str," + plcnum[0];
            ResponseMessage msg = RunImageCheck_plc(config);
            msg.IsReply = false;
 
            return msg;
        }
 
 
        [ProcessMethod("ImageCheck", "ReadBarcode", "读码", InvokeType.TestInvoke)]
        public ResponseMessage ReadBarcode(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ResponseMessage msg = new ResponseMessage();
            if (config is IImageCheckOperationConfig opConfig)
            {
                if (invokeDevice is TcpClientWrapBase BarcodeScanner)
                {
                    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;
 
                    string barcode = BarcodeScannerCommunicate(BarcodeScanner);
 
                    List<double> ret = new List<double>();
                    if ("NOREAD".Equals(barcode.ToUpper()))
                    {
                        ret.Add(999);
                    }
                    else
                    {
                        if (barcode.Split('-').Length > 5)
                        {
                            int mh = Plc1.Read(4000, 1, out _)[0];
                            string codestr = barcode.Split('-')[4];
                            if (codestr == "L")
                            {
                                codestr = "10";
                            }
 
                            if (codestr.Equals(mh.ToString()))
                            {
                                ret.Add(1);
                            }
                            else
                            {
                                ret.Add(2);
                                Plc1.WriteSingleAddress(4010, 1, out _);//给plc报警
                            }
                        }
                        else
                        {
                            ret.Add(999);
                        }
                    }
 
                    FillSpecResults(results[0].PID, results[0].Specs, ret, opConfig.Products[0].SEQUENCE);
 
 
                    opConfig.Products[0].SN = barcode;
                    opConfig.Products[0].PID = barcode + "_1";
                    opConfig.Products[0].Details.ForEach(u =>
                    {
                        u.SN = barcode;
                        u.PID = barcode + "_1";
                        u.ResultList.ForEach(x =>
                    {
 
                        x.PID = barcode + "_1";
 
                    });
                    });
 
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{opConfig.Products[0].PID}条码获取为{barcode}");
                }
            }
            return msg;
        }
 
 
        [ProcessMethod("ImageCheck", "ReadBarcode2", "读栏具码", InvokeType.TestInvoke)]
        public ResponseMessage ReadBarcode2(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ResponseMessage msg = new ResponseMessage();
 
            if (invokeDevice is TcpClientWrapBase BarcodeScanner2)
            {
                string barcode = BarcodeScannerCommunicate(BarcodeScanner2);
                if (string.IsNullOrEmpty(barcode) || "noread".Equals(barcode.ToLower()))
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"栏具码获取失败");
                    Plc1.WriteSingleAddress(1524, 2, out _);
                    Plc1.WriteSingleAddress(1514, 1, out _);
                }
                else
                {
                    Plc1.WriteSingleAddress(1524, 1, out _);
                    Plc1.WriteSingleAddress(1514, 1, out _);
                    ConfigAOI1.basketcode = barcode;
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"获取到栏具码为{barcode}");
 
                    mysqlhelper.NewBasketcode(barcode);
                    RerefreshBasketcode();
 
                }
            }
 
            return msg;
        }
 
 
        private string BarcodeScannerCommunicate(TcpClientWrapBase client)
        {
            string barcode = "";
 
            for (int i = 0; i < 3; i++)
            {
                if (client.WriteAndRead("start", out string error, out barcode, true))
                {
                    barcode = barcode.Trim(' ', '\r', '\n');
                    if (CheckBarcodeValid(barcode))
                    {
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{client.Name}扫码完成,反馈{barcode}");
                        return barcode;
                    }
                    else
                    {
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{client.Name}第{i + 1}扫码完成,反馈{barcode},不是合法条码");
                        Thread.Sleep(200);
                    }
                }
                else
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Error, $"{client.Name}扫码失败,{error}");
                    break;
                }
            }
 
            return "NOREAD";
        }
 
 
        private bool CheckBarcodeValid(string barcode)
        {
            bool isBarcodeValid = true;
            if (string.IsNullOrWhiteSpace(barcode) || barcode == "NA" || barcode == "NoRead")
            {
                isBarcodeValid = false;
            }
            return isBarcodeValid;
        }
 
 
        [ProcessMethod("ImageCheck", "CheckLineProfile", "检测产品线轮廓度", InvokeType.TestInvoke)]
        public ResponseMessage CheckLineProfile(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ResponseMessage msg = new ResponseMessage();
            try
            {
                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();
 
                    List<ContourPoint> CheckPointList = GetPointListFromConfigSelection(opConfig.CheckPointList);
                    msg.DataObj = results;
                    CheckPointList = CheckPointList.OrderBy(u => u.index).ToList();
 
                    List<double> pointdataF = new List<double>();
                    foreach (var item in CheckPointList)
                    {
                        pointdataF.Add(item.X);
                        pointdataF.Add(item.Y);
                    }
 
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"检测产品线轮廓度输入点数据  {string.Join(',', pointdataF)}");
 
                    var tool = GetHalconTool(null, "", opConfig.AlgorithemPath);
                    var ret = tool.RunProcedure(new Dictionary<string, HalconDotNet.HTuple>() { { "INPUT_Points", pointdataF.ToArray() } }, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results", "OUTPUT_PointZ" }, null);
 
                    if (ret == null)
                    {
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"脚本{opConfig.AlgorithemPath}运行异常,返回值为null");
                    }
                    else if (!ret.Item1)
                    {
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"脚本{opConfig.AlgorithemPath}运行异常,{ret.Item4}");
                    }
                    else
                    {
                        //List<double> datasX = ret.Item2["OUTPUT_PointX"].HTupleToDouble();
                        //List<double> datasY = ret.Item2["OUTPUT_PointY"].HTupleToDouble();
                        List<double> datasZ = ret.Item2["OUTPUT_PointZ"].HTupleToDouble();
 
                        //LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{results[0].PID}获取数据OUTPUT_PointX   {string.Join(",", datasX.Select(u => u.ToString("f4")))}");
                        //LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{results[0].PID}获取数据OUTPUT_PointY   {string.Join(",", datasY.Select(u => u.ToString("f4")))}");
                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{results[0].PID}获取数据OUTPUT_PointZ   {string.Join(",", datasZ.Select(u => u.ToString("f4")))}");
 
 
                        if (datasZ.Count == CheckPointList.Count)
                        {
                            string Postion = "P" + opConfig.TriggerStr.Split('#')[0];
                            string csvhead = "Time,Pid,Postion";
                            string csvdata = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}T,{results[0].PID},{Postion}";
 
                            for (int i = 0; i < CheckPointList.Count; i++)
                            {
                                CheckPointList[i].ActualZ = datasZ[i] + CheckPointList[i].compensateZ;
 
                                csvhead += $",{CheckPointList[i].Name}_X";
                                csvhead += $",{CheckPointList[i].Name}_Y";
                                csvhead += $",{CheckPointList[i].Name}_Z";
 
                                csvdata += $",{CheckPointList[i].X.ToString("F4")}";
                                csvdata += $",{CheckPointList[i].Y.ToString("F4")}";
                                csvdata += $",{CheckPointList[i].ActualZ.ToString("F4")}";
                            }
 
                            foreach (var item in results[0].Specs.AsParallel())
                            {
                                var temcal = ConfigAOI1.MeasureItemBinds.FirstOrDefault(u => u.SpecCode == item.Code);
 
                                if (temcal == null)
                                {
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"检测项 {item.Code}未能获取计算公式");
                                }
                                else
                                {
                                    List<double> pointdata = new List<double>();
                                    foreach (var item1 in temcal.MeasurePointNameCollection)
                                    {
                                        var point = CheckPointList.FirstOrDefault(u => u.Name == item1.MeasurePointName);
                                        if (point == null)
                                        {
                                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"未能找到检测项{item.Code}的点数据{item1.MeasurePointName}");
                                        }
                                        else
                                        {
                                            if (item1.ContourEdge == ContourEdge.X)
                                            {
                                                pointdata.Add(point.X);
                                            }
                                            else if (item1.ContourEdge == ContourEdge.Y)
                                            {
                                                pointdata.Add(point.Y);
                                            }
                                            else if (item1.ContourEdge == ContourEdge.Z)
                                            {
                                                pointdata.Add(point.ActualZ);
                                            }
                                        }
 
                                    }
 
                                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{results[0].PID}   {item.Code}输入计算公式数据 {string.Join(",", pointdata.Select(u => u.ToString("f4")))}");
                                    var toolcal = GetHalconTool(null, "", temcal.AlgorithemPath);
                                    var retcal = toolcal.RunProcedure(new Dictionary<string, HalconDotNet.HTuple>() { { "INPUT_Points", pointdata.ToArray() } }, null, new List<string>() { "OUTPUT_Results" }, null);
 
                                    if (retcal != null && !ret.Item1)
                                    {
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"未能找到检测项{item.Code}的计算公式算法运行异常{retcal?.Item4}");
                                    }
                                    else
                                    {
                                        item.ActualValue = retcal.Item2["OUTPUT_Results"].HTupleToDouble()[0];
                                        LogAsync(DateTime.Now, EnumHelper.LogLevel.Detail, $"{results[0].PID}获取计算公式数据{item.Code}  {item.GetMeasureValueStr()}");
                                    }
                                }
                            }
 
 
                            CSVRecordAsync($"ContourPointRecord_{Postion}.csv", csvdata, csvhead);
                        }
                        else
                        {
                            LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"脚本{opConfig.AlgorithemPath}输出数据长度异常");
                            throw new Exception();
                        }
                    }
 
                }
            }
            catch (Exception re)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"{re.ToString()}");
            }
 
            return msg;
        }
 
 
        [ProcessMethod("ImageCheck", "GetMatrix", "获取矩阵", InvokeType.TestInvoke)]
        public ResponseMessage GetMatrix(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ResponseMessage msg = new ResponseMessage();
            if (config is IImageCheckOperationConfig opConfig)
            {
                var tool = GetHalconTool(null, "", opConfig.AlgorithemPath);
                var ret = tool.RunProcedure(null, new Dictionary<string, HalconDotNet.HObject>() { { "INPUT_Image", opConfig.ImageSet.HImage } }, new List<string>() { "OUTPUT_Results" }, null);
 
 
                if (ret == null)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"脚本{opConfig.AlgorithemPath}运行异常,返回值为null");
                }
                else if (!ret.Item1)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"脚本{opConfig.AlgorithemPath}运行异常,{ret.Item4}");
                }
                else
                {
                    List<double> datas = ret.Item2["OUTPUT_Results"].HTupleToDouble();
                    opConfig.Products[0].Centermatrix = datas;
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Action, $"产品{opConfig.Products[0].PID}矩阵获取为 {string.Join(',', datas)}");
                }
            }
            return msg;
        }
 
 
    }
}