kingno
2025-04-01 044e5d0e1491ef25976cf3e25cf7fdf2baf6cb7d
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
using Bro.Common.Base;
using Bro.Common.Helper;
using Bro.Common.Interface;
using Bro.Common.Model;
using Bro.M135.Common;
using Bro.M135.DBManager;
using Bro.UI.Model.Winform;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Bro.M135.Process
{
    public partial class M141_WS1_Process : IUpdateProductData
    {
        #region Constructor
        public M141_WS1_Process() : base() { }
 
        public M141_WS1_Process(string productCode) : base(productCode) { }
        #endregion
 
        M135Config M135Config => Config as M135Config;
 
        object _productListLock = new object();
        List<ProductModel_M135> ProductList = new List<ProductModel_M135>();
 
        MachineLearningBase ML = null;
        TcpListenerWrap TcpListener = null;
        PointLaser_OmronDriver PointLaser_Upper = null;
        PointLaser_OmronDriver PointLaser_Down = null;
 
        Spec _errorSpec = null;
 
        int _backgroundImageWidth = 2448;
        public event Action<string, List<IShapeElement>> OnPositionResultUpdated;
        public event Action<ProductModel> OnUpdateProductData;
 
        string STATION_NAME => string.IsNullOrWhiteSpace(M135Config.StationCode) ? "M135_Size" : M135Config.StationCode;
 
        public override void Open()
        {
            base.Open();
 
            //if (_manager_P_Product == null)
            //{
            //    try
            //    {
            //        _manager_P_Product = new Manager_P_PRODUCT();
            //    }
            //    catch (Exception ex)
            //    {
            //        LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"数据库初始化异常,{ex.GetExceptionMessage()}");
            //        throw ex;
            //    }
            //}
 
            ML = DeviceCollection.FirstOrDefault(u => u is MachineLearningBase) as MachineLearningBase;
            if (ML == null)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Information, $"未设置ML实例");
            }
 
            TcpListener = DeviceCollection.FirstOrDefault(u => u is TcpListenerWrap) as TcpListenerWrap;
            if (TcpListener == null)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"未设置TCP监听实例");
            }
 
            _errorSpec = M135Config.SpecCollection.FirstOrDefault(u => u.Code == M135Config.CheckErrorSpecCode) as Spec;
            if (_errorSpec == null)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Warning, $"未设置检测异常Spec");
            }
 
            PointLaser_Upper = DeviceCollection.FirstOrDefault(u => u.Id == M135Config.PointLaserId_Upper) as PointLaser_OmronDriver;
            if (PointLaser_Upper == null)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"未设置或选择上方点激光设备");
            }
 
            PointLaser_Down = DeviceCollection.FirstOrDefault(u => u.Id == M135Config.PointLaserId_Down) as PointLaser_OmronDriver;
            if (PointLaser_Down == null)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"未设置或选择下方点激光设备");
            }
 
            _csvHead = "";
            _contourPointDataHead = "";
            _pointHeightHead = "";
            _triggerSource_P1 = "";
 
            InitialProductList();
 
            if (File.Exists(M135Config.BackgroundImageFilePath))
            {
                Bitmap bkImage = new Bitmap(M135Config.BackgroundImageFilePath);
                _backgroundImageWidth = bkImage.Width;
            }
        }
 
        public override void InitialProcessMethods()
        {
            base.InitialProcessMethods();
            OldDataClear.Instance.RunClearOldData(M135Config.DBDataTimeLimit);
        }
 
        public override void ProcessRunStateChanged()
        {
            base.ProcessRunStateChanged();
 
            if (CurrentState == EnumHelper.RunState.Running)
            {
                OldDataClear.Instance.SetAllowFlag(false, M135Config.DBDataTimeLimit);
            }
            else
            {
                OldDataClear.Instance.SetAllowFlag(true, M135Config.DBDataTimeLimit);
            }
        }
 
        private void NewProductIntoList(ProductModel_M135 p)
        {
            lock (_productListLock)
            {
                ProductList.Insert(0, p);
 
                while (ProductList.Count > 200)
                {
                    ProductList.RemoveAt(ProductList.Count - 1);
                }
            }
 
            //Task.Run(() =>
            //{
            var isNewDone = _manager_P_Product.NewProduct(p, p.Details, out string msg);
            if (!isNewDone)
            {
                LogAsync(DateTime.Now, EnumHelper.LogLevel.Exception, $"产品{p.PID}数据库新增异常,{msg}");
            }
            //});
        }
 
        private ProductModel_M135 FindProductModelByBarcode(string barcode)
        {
            var p = ProductList.FirstOrDefault(u => u.SN == barcode);
 
            if (p == null && M135Config.IsAllowTempProduct)
            {
                p = new ProductModel_M135();
                p.SN = barcode;
 
                ProductList.Add(p);
            }
 
            return p;
        }
 
        protected void FillSpecResults(List<ISpec> detectSpec, List<double> results)
        {
            detectSpec.ForEach(s =>
            {
                if (!s.IsEnabled)
                    return;
 
                if (results.Count > s.OutputIndex)
                {
                    s.ActualValue = results[s.OutputIndex];
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Assist, $"{s.Code}赋值{s.GetMeasureValueStr()},结果{s.GetMeasureResultStr()}");
                }
            });
        }
 
        private List<double> ConvertXY2Data(List<double> xList, List<double> yList)
        {
            List<double> list = new List<double>();
 
            for (int i = 0; i < xList.Count && i < yList.Count; i++)
            {
                list.Add(xList[i]);
                list.Add(yList[i]);
            }
 
            return list;
        }
 
        private void ConvertData2XY(List<double> data, out List<double> xList, out List<double> yList)
        {
            xList = new List<double>();
            yList = new List<double>();
 
            for (int i = 0; i < data.Count; i += 2)
            {
                xList.Add(data[i]);
                yList.Add(data[i + 1]);
            }
        }
 
        private List<ISpec> GetSpecListFromConfigSelection(List<SpecSelector> specSelectors)
        {
            List<ISpec> specList = new List<ISpec>();
            specSelectors.ForEach(u =>
            {
                var spec = M135Config.SpecCollection.FirstOrDefault(s => s.Code == u.SpecCode);
                if (spec != null)
                {
                    specList.Add(spec.Copy());
                }
            });
 
            return specList;
        }
 
        private async void UpdatePositionResultDisplay(P_PRODUCT_DETAIL detail, bool isOK, string positionName)
        {
            await Task.Run(() =>
            {
                if (detail == null)
                {
                    LogAsync(DateTime.Now, EnumHelper.LogLevel.Warning, $"无法显示检测明细信息");
                    return;
                }
 
                List<IShapeElement> eleList = new List<IShapeElement>();
 
                TextDisplay txt = new TextDisplay();
                eleList.Add(txt);
 
                txt.StartX = txt.StartY = (int)(_backgroundImageWidth * GlobalVar.WIDTH_RATIO);
 
                txt.AddText($"{detail.SN} {(isOK ? "OK" : "NG")}", isOK ? Color.Lime : Color.White, isOK ? Color.Transparent : Color.Red);
 
                txt.AddText(" ", Color.Transparent, Color.Transparent);
 
                var ngSpecCode = new List<string>();
 
                detail.SpecList.ForEach(s =>
                {
                    GetIndicatorFromSpec(s, eleList, txt, ngSpecCode);
                });
 
                detail.ResultList.SelectMany(u => u.Specs).ToList().ForEach(s =>
                {
                    GetIndicatorFromSpec(s, eleList, txt, ngSpecCode);
                });
 
                var defects = new List<string>(detail.DefectList);
                defects.AddRange(detail.ResultList.GetDefectDescList());
 
                defects = defects.Except(ngSpecCode).Distinct().ToList();
                defects.ForEach(u =>
                {
                    txt.AddText(u, Color.Red, Color.Transparent);
 
                    var indicator = M135Config.DefectIndicatorCollection.FirstOrDefault(d => d.DefectName == u);
                    if (indicator != null)
                    {
                        var cloneIndicator = indicator.Clone() as DefectRectangleIndicator;
                        eleList.Add(cloneIndicator);
                    }
                });
 
                OnPositionResultUpdated?.Invoke(positionName, eleList);
            });
        }
 
        private void GetIndicatorFromSpec(ISpec s, List<IShapeElement> eleList, TextDisplay txt, List<string> ngSpecCode)
        {
            txt.AddText($"{s.Code} {s.GetMeasureValueStr()}", s.MeasureResult == true ? Color.Lime : Color.Red, Color.Transparent);
 
            if (s.MeasureResult != true)
            {
                var indicator = M135Config.DefectIndicatorCollection.FirstOrDefault(u => u.DefectName == s.Code);
                if (indicator != null)
                {
                    var cloneIndicator = indicator.Clone() as DefectRectangleIndicator;
                    cloneIndicator.DefectName += $" {s.GetMeasureValueStr()}";
 
                    eleList.Add(cloneIndicator);
                }
 
                ngSpecCode.Add(s.Code);
            }
        }
 
        private async void UpdateOverAllProductResultToUI(ProductModel_M135 product, bool isOK)
        {
            await Task.Run(() =>
            {
                List<IShapeElement> eleList = new List<IShapeElement>();
 
                TextDisplay txt = new TextDisplay();
                eleList.Add(txt);
 
                txt.StartX = txt.StartY = (int)(_backgroundImageWidth * GlobalVar.WIDTH_RATIO);
 
                txt.AddText($"{product.SN} {product.Result}", isOK ? Color.Lime : Color.White, isOK ? Color.Transparent : Color.Red);
 
                txt.AddText(" ", Color.Transparent, Color.Transparent);
 
                var ngSpecCode = new List<string>();
 
                product.Details.ForEach(d =>
                {
                    d.SpecList.ForEach(s =>
                    {
                        GetIndicatorFromSpec(s, eleList, txt, ngSpecCode);
                    });
 
                    d.ResultList.SelectMany(u => u.Specs).ToList().ForEach(s =>
                    {
                        GetIndicatorFromSpec(s, eleList, txt, ngSpecCode);
                    });
 
                    var defects = new List<string>(d.DefectList);
                    defects.AddRange(d.ResultList.GetDefectDescList());
 
                    defects = defects.Except(ngSpecCode).Distinct().ToList();
                    defects.ForEach(u =>
                    {
                        txt.AddText(u, Color.Red, Color.Transparent);
 
                        var indicator = M135Config.DefectIndicatorCollection.FirstOrDefault(d => d.DefectName == u);
                        if (indicator != null)
                        {
                            var cloneIndicator = indicator.Clone() as DefectRectangleIndicator;
                            eleList.Add(cloneIndicator);
                        }
                    });
                });
 
                OnPositionResultUpdated?.Invoke("", eleList);
            });
        }
 
        [ProcessMethod("", "UpdateProdcutModelToListTest", "上传至产品列表测试", InvokeType.TestInvoke)]
        public ResponseMessage UpdateProdcutModelToListTest(IOperationConfig config, IDevice invokeDevice, IDevice sourceDevice)
        {
            ProductModel p = new ProductModel();
            p.SN = "123456";
            p.Result = "Ng";
 
            Spec spec = new Spec() { Code = "SpecTest", StandardValue = 100, Tolrenance_Negative = 10, Tolrenance_Positive = 10 };
            spec.ActualValue = 101;
 
            P_PRODUCT_DETAIL detail = new P_PRODUCT_DETAIL() { PositionName = "S1", STATION_CODE = "M135" };
            detail.SpecList = new List<Spec>();
            for (int i = 0; i < 10; i++)
            {
                var specClone = (Spec)spec.Copy();
                specClone.Code = $"FAI_{i}";
                specClone.ActualValue = new Random().Next(80, 120);
 
                detail.SpecList.Add(specClone);
            }
 
            detail.DefectList = new List<string>() { "压伤" };
 
            p.Details.Add(detail);
 
            OnUpdateProductData?.Invoke(p);
 
            return new ResponseMessage();
        }
    }
}