领胜LDS 键盘AOI检测项目
patrick.xu
2021-01-11 f06ae0e33e33f1ed5f198827b9b5a53e765b3eee
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
using Bro.Common.Helper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace Bro.M071.Process
{
    public partial class M071Process
    {
        #region MES
        //WebApiHelper _webApiHelper = new WebApiHelper();
 
        public Action<string, bool> OnCheckHintUpload { get; set; }
        public Action<string> OnOperatorLogin { get; set; }
        #endregion
 
        private string barcode = "";
        public string BarCode
        {
            get => barcode;
            set
            {
                barcode = value;
 
                if (!string.IsNullOrWhiteSpace(barcode))
                {
                    if (!CheckIncoming(barcode))
                    {
                        barcode = "";
                    }
                }
            }
        }
 
        private string operatorCode = "";
        public string OperatorCode
        {
            get => operatorCode;
            set
            {
                operatorCode = value;
 
                if (!string.IsNullOrWhiteSpace(operatorCode))
                {
                    OnOperatorLogin?.Invoke(operatorCode);
 
                    OnCheckHintUpload?.Invoke($"操作员登录:{operatorCode}", false);
                }
            }
        }
 
        #region WebService Method
        MethodInfo incomingCheckMethod = null;
        MethodInfo dataUploadMethod = null;
 
        const string IncomingCheckMethodName = "CheckFormerData";
        const string DataUploadMethodName = "HighLowKey_DataUpLoad";
 
        private object IncomingCheckObj = null;
        public MethodInfo IncomingCheckMethod
        {
            get
            {
                if (incomingCheckMethod == null)
                {
                    incomingCheckMethod = InitialMESWebServiceMethod(IncomingCheckMethodName, out IncomingCheckObj);
                }
 
                return incomingCheckMethod;
            }
            set => incomingCheckMethod = value;
        }
 
        private object DataUploadObj = null;
        public MethodInfo DataUploadMethod
        {
            get
            {
                if (dataUploadMethod == null)
                {
                    dataUploadMethod = InitialMESWebServiceMethod(DataUploadMethodName, out DataUploadObj);
                }
 
                return dataUploadMethod;
            }
            set => dataUploadMethod = value;
        }
 
        private MethodInfo InitialMESWebServiceMethod(string methodName, out object invokeClass)
        {
            invokeClass = null;
 
            if (!Config.IsEnableMESUpload)
                return null;
 
            // 读取配置文件,获取配置信息
            var urlParas = Config.MESURL.Split(new char[] { '/', '.' }, StringSplitOptions.RemoveEmptyEntries);
            string className = urlParas[urlParas.Length - 2];
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MESAPI");
            if (Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
 
            // 调用WebServiceHelper
            WebServiceHelper.CreateWebServiceDLL(Config.MESURL, className, methodName, filePath);
 
            // 读取dll内容
            byte[] filedata = File.ReadAllBytes(filePath + className + "_" + methodName + ".dll");
            // 加载程序集信息
            Assembly asm = Assembly.Load(filedata);
            Type t = asm.GetType(className);
 
            // 创建实例
            invokeClass = Activator.CreateInstance(t);
            return t.GetMethod(methodName);
        }
        #endregion
 
        private bool CheckIncoming(string barcode)
        {
            if (!Config.IsEnableMESUpload)
                return true;
 
            //dynamic paras = new
            //{
            //    FGcode = barcode,
            //    station = Config.StationCode,
            //};
 
            //string url = $"{Config.MESURL}CheckFormerData";
            //string paraStr = JsonConvert.SerializeObject(paras);
            //LogAsync(DateTime.Now, $"MES入料检测 {url}", paraStr);
 
            //IncomingCheckMethod = InitialMESWebServiceMethod(IncomingCheckMethodName, out IncomingCheckObj);
 
            Stopwatch sw = new Stopwatch();
            sw.Start();
            //var result = _webApiHelper.dooPost(url, paraStr);
 
            object[] paras = new object[] { barcode, Config.StationCode, Config.ProjectCode };
 
            if (Config.IsEnableMESLog)
            {
                LogAsync(DateTime.Now, $"MES入料检测", JsonConvert.SerializeObject(paras));
            }
 
            var result = IncomingCheckMethod?.Invoke(IncomingCheckObj, paras).ToString();
            var mesReturn = (MESIncomingCheckReturn)int.Parse(result);
            sw.Stop();
            LogAsync(DateTime.Now, $"{barcode}产品条码检测,{result}|{mesReturn.ToString()}", $"耗时:{sw.ElapsedMilliseconds}ms");
 
            bool isOK = mesReturn == MESIncomingCheckReturn.检测PASS;
            OnCheckHintUpload?.Invoke("条码检测" + mesReturn.ToString(), !isOK);
 
            return isOK;
        }
 
        private void MESCheckDataUpload(ProductionMeasurement pMeasure)
        {
            if (!Config.IsEnableMESUpload)
                return;
 
            //dynamic paras = new
            //{
            //    checkTimes = Config.IsDisableMultipleCheckTimes,
            //    Project = Config.ProjectCode,
            //    FGcode = pMeasure.Barcode,
            //    CheckTime = pMeasure.EndTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
            //    ProcessCode = Config.StationCode,
            //    Result = pMeasure.PResult == "OK" ? "PASS" : "FAIL",
            //    Line = Config.LineCode,
            //    SlantCheckData = GetMESSlantData(pMeasure),
            //    AlignmentCheckData = GetMESAlignmentData(pMeasure),
            //};
 
            //string url = $"{Config.MESURL}HighLowKey_DataUpload";
            //string paraStr = JsonConvert.SerializeObject(paras);
            //LogAsync(DateTime.Now, $"MES数据上传 {url}", paraStr);
 
            //DataUploadMethod = InitialMESWebServiceMethod(DataUploadMethodName, out DataUploadObj);
 
            Stopwatch sw = new Stopwatch();
            sw.Start();
            //var result = _webApiHelper.dooPost(url, paraStr);
 
            DateTime checkTime = pMeasure.EndTime.Value;
            object[] paras = new object[]
            {
                Config.IsDisableMultipleCheckTimes,
                Config.ProjectCode,
                pMeasure.Barcode,
                checkTime.ToString("yyyy-MM-dd HH:mm:ss"),
                Config.StationCode,
                pMeasure.PResult == "OK" ? "PASS" : "FAIL",
                Config.LineCode,
                GetMESSlantData(pMeasure),
                GetMESAlignmentData(pMeasure),
                GetNGKeys(pMeasure)
            };
 
            if (Config.IsEnableMESLog)
            {
                LogAsync(DateTime.Now, $"{barcode}产品检测数据上传", JsonConvert.SerializeObject(paras));
            }
 
            var result = DataUploadMethod?.Invoke(DataUploadObj, paras).ToString();
            var mesReturn = (MESUploadReturn)int.Parse(result);
            sw.Stop();
            LogAsync(DateTime.Now, $"{barcode}产品检测数据上传,{result}|{mesReturn.ToString()}", $"耗时:{sw.ElapsedMilliseconds}ms");
 
            OnCheckHintUpload?.Invoke("检测数据" + mesReturn.ToString(), mesReturn != MESUploadReturn.上传成功);
        }
 
        private string GetMESAlignmentData(ProductionMeasurement pMeasure)
        {
            return string.Join(",", pMeasure.Measurements.Where(u => u.MeasureType.StartsWith("Alignment")).Select(u => $"{u.Name}:{u.Spec.ActualValue.Value.ToString(_precision)}"));
        }
 
        private string GetMESSlantData(ProductionMeasurement pMeasure)
        {
            return string.Join(",", pMeasure.Measurements.Where(u => u.MeasureType.StartsWith("Slant")).Select(u => $"{u.Name}:{u.Spec.ActualValue.Value.ToString(_precision)}"));
        }
 
        private string GetNGKeys(ProductionMeasurement pMeasure)
        {
            string ngCodes = "";
            Dictionary<string, List<string>> ngCodeDict = new Dictionary<string, List<string>>();
 
            var ngList = pMeasure.Measurements.Where(m => m.Spec.MeasureResult != true).ToList();
            if (ngList.Count == 0)
                return "";
 
            ngList.GroupBy(m => m.MeasureType).ToList().ForEach(g =>
                  {
                      var mType = Config.MeasureTypeCollection.FirstOrDefault(u => u.Code == g.Key);
                      if (mType != null)
                      {
                          if (!ngCodeDict.ContainsKey(mType.NGCode))
                          {
                              ngCodeDict[mType.NGCode] = new List<string>();
                          }
 
                          g.ToList().ForEach(k =>
                          {
                              k.KeyUnitCollection.Select(kk => kk.Key).ToList().ForEach(key =>
                              {
                                  string uploadKeyCode = key;
                                  var keyCodeMap = Config.KeyCodeMappingCollection.FirstOrDefault(kcm => kcm.Key == key);
                                  if (keyCodeMap != null)
                                  {
                                      uploadKeyCode = keyCodeMap.KeyCode;
                                  }
 
                                  if (!ngCodeDict[mType.NGCode].Contains(uploadKeyCode))
                                  {
                                      ngCodeDict[mType.NGCode].Add(uploadKeyCode);
                                  }
                              });
                          });
                      }
                  });
 
            if (ngCodeDict.Count > 0)
            {
                ngCodes = string.Join(";", ngCodeDict.ToList().Select(u => $"{u.Key}:{string.Join(",", u.Value)}"));
            }
 
            return ngCodes;
        }
    }
 
    public enum MESIncomingCheckReturn
    {
        上传结果未知 = -3,
        未查询到工序信息 = -2,
        未查询到SN信息 = -1,
        检测FAIL = 0,
        检测PASS = 1,
    }
 
    public enum MESUploadReturn
    {
        上传结果未知 = -1,
        上传失败 = 0,
        上传成功 = 1,
        工序检测异常 = 2,
        检测次数异常 = 3,
    }
}