wenxiangchao
2026-11-02 fe2aa4880d5c9fd88088ad0ed81ebaca05629f5f
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
using HMI.Core.Manager;
using HMI.Core.Setting;
using HMI.Core.Util;
using HMI.UI.Util;
using HMI.Util;
using Panuon.WPF.UI;
using Plugin.TestResult.Lixun;
using Plugin.TestResult.Model;
using Plugin.TestResult.Util;
using Plugin.TestResult_WPF.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Windows;
using System.Windows.Input;
 
namespace Plugin.TestResult_WPF
{
    public class BarcodeEventArg
    {
        public string name { get; private set; }
        public string positionCode { get; private set; }
        public string snrCode { get; private set; }
        public CellInfo lastInfo { get; private set; }
 
        public BarcodeEventArg(string name, string positionCode, string snrCode, CellInfo lastInfo)
        {
            this.name = name;
            this.positionCode = positionCode;
            this.snrCode = snrCode;
            this.lastInfo = lastInfo;
        }
    }
 
    /// <summary>
    /// Scanner.xaml 的交互逻辑
    /// </summary>
    public partial class Scanner : WindowX
    {
        private string _title;
 
        public string title
        {
            get { return _title; }
            set => Set(ref _title, value);
        }
 
        public event EventHandler<BarcodeEventArg> FinishBarcode;
        public event EventHandler<RoutedEventArgs> ComplateClick;
 
        private static Dictionary<string, CellInfo> snrCache = new Dictionary<string, CellInfo>();
        SerialPort serialPort;
 
        private string model;
        private int columns;
        private int rows;
        private int ovenIndex;
        private CellInfo targetCellInfo;
        public Scanner(int index, string title, string model, int columns, int rows)
        {
            this.ovenIndex = index;
            this.title = title;
            this.model = model;
            this.columns = columns;
            this.rows = rows;
            this.DataContext = this;
            InitializeComponent();
            Loaded += Scanner_Loaded;
        }
 
        private void Scanner_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                InitScanner();
                Loaded -= Scanner_Loaded;
            }
            catch (Exception ex)
            {
                ViewControl.Logger.Error("Open Scanner Window Error.", ex);
                MsgBoxHelper.Error(this, $"{ex.Message}");
            }
        }
 
        /// <summary>
        /// 设置扫码枪
        /// </summary>
        private void InitScanner()
        {
            string comStr = "";
            if (serialPort != null) return;
 
            string section = this.Tag.ToString();
            ScannerConfig common = ScannerConfig.ReadFromIni(ViewControl.SannerIniFile, "Config");
 
            string portName = IniFileHelper.ReadIniData(section, "PortName", "", ViewControl.SannerIniFile);
            if (string.IsNullOrEmpty(portName))
            {
                if (section.StartsWith("A"))
                {
                    portName = "COM1";
                }
                else
                {
                    portName = "COM2";
                }
            }
            common.PortName = portName;
 
 
            // 配置串口
            serialPort = new SerialPort
            {
                PortName = common.PortName,
                BaudRate = common.BaudRate,
                Parity = Parity.None,
                DataBits = common.DataBits,
                StopBits = common.StopBits,
                Handshake = Handshake.None,
                DtrEnable = common.DtrEnable,
                RtsEnable = common.RtsEnable
                //ReadTimeout = 500,
                //WriteTimeout = 500,
                //ReciveBufferSize=4096
            };
 
            try
            {
                // 打开串口
                serialPort.Open();
                // 注册接收数据事件
                serialPort.DataReceived += SerialPort_DataReceived;
            }
            catch (Exception ex)
            {
                ViewControl.Logger.Error("Init Scan Gun Failed.", ex);
                MsgBoxHelper.Error(this, $"{this.lang("Tr.InitGunFailed")}: {ex.StackTrace}");
            }
        }
 
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPort sp = (SerialPort)sender;
                string barcode = ReadDataFrom(sp).Trim();
 
                //string barcode = 
                Dispatcher.Invoke(() =>
                {
                    if (snrText.IsFocused)
                    {
                        snrText.Text = barcode;
                        Con_Click(null, null);
                    }
                    else
                    {
                        try
                        {
                            var targetCellInfo = ScannerParser.GetCellInfoByCode(this.model, this.columns, this.rows, barcode);
                            if (!TestResultView.nameTables.ContainsKey(targetCellInfo.OvenName))
                            {
                                MsgBoxHelper2.Error($"老化炉 [{targetCellInfo.OvenName}] 不存在,请检查配置");
                                return;
                            }
                            var sourceTable = TestResultView.tables[this.ovenIndex];
                            if (sourceTable.title != targetCellInfo.OvenName)
                            {
                                MsgBoxHelper2.Error($"请切换至 [{targetCellInfo.OvenName}] 区扫码,当前为 [{sourceTable.title}] 区!");
                                return;
                            }
 
                            var oven = TestResultView.nameTables[targetCellInfo.OvenName];
                            if (oven.cells.Length < targetCellInfo.Index + 1)
                            {
                                MsgBoxHelper2.Error($"穴位号 [{barcode}] 超出索引 {targetCellInfo.Index}");
                                return;
                            }
 
                            this.targetCellInfo = targetCellInfo;
                            positionText.Text = barcode;
                            //positionText.Focus();
                            //snrText.Text = "";
                            snrText.Focus();
                        }
                        catch (Exception ex)
                        {
                            ViewControl.Logger.Error("Parse Position Code Error.", ex);
                            MsgBoxHelper2.Error($"穴位号 [{barcode}] 解析失败: {ex.Message}");
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ViewControl.Logger.Error("Get Scan Gun Data Failed.", ex);
                MessageBox.Show($"{this.lang("Tr.GetGunData")}: {ex.StackTrace}");
            }
        }
 
        public static void InsertNewCode(string snr, CellInfo info)
        {
            snrCache[snr] = info;
        }
 
        public static void RemoveSNR(string snr)
        {
            snrCache.Remove(snr);
        }
 
        private void SendCode(string tag, string position, string snr)
        {
            if (snrCache.ContainsKey(snr))
            {
                string oldPosition = snrCache[snr].OriginCode;
                if (MsgBoxHelper2.WarnChoose($"条码[{snr}]已放置于[{oldPosition}]中,是否清除?") == MessageBoxResult.OK)
                {
                    try
                    {
                        FinishBarcode.Invoke(this, new BarcodeEventArg(tag, position, null, snrCache[snr]));
                        snrCache.Remove(snr);
                        FinishBarcode.Invoke(this, new BarcodeEventArg(tag, position, snr, null));
                    }
                    catch (Exception ex)
                    {
                        ToastHelper.Error(ex.Message);
                    }
                }
            }
            else
            {
                FinishBarcode.Invoke(this, new BarcodeEventArg(tag, position, snr, null));
            }
        }
 
        private void Con_Click(object sender, RoutedEventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                string position = positionText.Text, snr = snrText.Text;
                try
                {
                    var EnableMes = ParameterManager.GetCommonParameterByName<bool>("EnableMes", false);
                    if (ParamSetting.CustomerCode == "LIXUN" && EnableMes)
                    {
                        var table = TestResultView.nameTables[targetCellInfo.OvenName];
                        // TestResultView.tables[this.ovenIndex]
                        string currentPn = table.CbProduct.Text;
 
                        /// 检查格式
                        if (!SNValidator.ValidateSN(currentPn, snr, out string msg))
                        {
                            table.GetSingleCell(targetCellInfo.Index).LightRed(true, out _);
                            MsgBoxHelper2.Error($"检查产品条码异常:{msg}");
                            snrText.Text = string.Empty;
                            snrText.Focus();
                            return;
                        }
 
                        /// 获取站名
                        string stationName = ProductManager.GetParameterByProductAndName(currentPn, "MES站位")?.Value;
                        if (string.IsNullOrEmpty(stationName))
                        {
                            table.GetSingleCell(targetCellInfo.Index).LightRed(true, out _);
                            MsgBoxHelper2.Error($"检查产品条码异常,当前产品[{currentPn}]未设置参数MES站位");
                            snrText.Text = string.Empty;
                            snrText.Focus();
                            return;
                        }
 
                        /// 检查PN
                        if (PNUtil.GetPN(ParamSetting.MesAddress, stationName, snr, out string pn, out msg))
                        {
 
                            if (pn != currentPn)
                            {
                                table.GetSingleCell(targetCellInfo.Index).LightRed(true, out _);
                                MsgBoxHelper2.Error($"当前测试料号为 [{currentPn}],扫码产品料号为 [{pn}] 不允许测试");
                                snrText.Text = string.Empty;
                                snrText.Focus();
                                return;
                            }
                        }
                        else
                        {
                            table.GetSingleCell(targetCellInfo.Index).LightRed(true, out _);
                            MsgBoxHelper2.Error($"检查产品条码异常:{msg}");
                            snrText.Text = string.Empty;
                            snrText.Focus();
                            return;
                        }
 
                        /// 检查工序
                        if (PNUtil.CheckIn(ViewControl.Logger, ParamSetting.MesAddress, stationName, snr, out bool needCheckIn, out msg))
                        {
                            if (needCheckIn != true)
                            {
                                table.GetSingleCell(targetCellInfo.Index).LightRed(true, out _);
                                MsgBoxHelper2.Error($"条码[{snr}]工序不在本站:{msg}");
                                snrText.Text = string.Empty;
                                snrText.Focus();
                                return;
                            }
                        }
                        else
                        {
                            table.GetSingleCell(targetCellInfo.Index).LightRed(true, out _);
                            MsgBoxHelper2.Error($"条码[{snr}]CheckIn失败:{msg}");
                            snrText.Text = string.Empty;
                            snrText.Focus();
                            return;
                        }
                    }
                    //var _ = ScannerParser.GetCellInfoByCode(this.model, this.columns, this.rows, snr);
                    //ToastHelper.Warning(this, "产品码格式异常");
                    //snrText.Text = string.Empty;
                    //snrText.Focus();
                    //return;
                }
                catch (Exception ex)
                {
                    ViewControl.Logger.Error("Scanner Check Error.", ex);
                    MsgBoxHelper2.Error($"扫码检查异常:{ex.Message}");
                    return;
                }
 
                if (string.IsNullOrEmpty(position) || string.IsNullOrEmpty(snr))
                {
                    ToastHelper.Warning(this, this.lang("Tr.PleaseInputSnrs"));
                    return;
                }
                try
                {
                    SendCode(Tag.ToString(), position, snr);
                    positionText.Text = "";
                    snrText.Text = "";
                    positionText.Focus();
                }
                catch (Exception ex)
                {
                    ViewControl.Logger.Error("Con_Click Failed.", ex);
                    ToastHelper.Warning(this, ex.Message);
                }
            });
        }
 
        /// <summary>
        /// 原来的完成扫描逻辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void Ok_Click(object sender, RoutedEventArgs e)
        //{
        //    string position = positionText.Text, snr = snrText.Text;
        //    if (string.IsNullOrEmpty(position) || string.IsNullOrEmpty(snr))
        //    {
        //        ToastHelper.Warning(this, this.lang("Tr.PleaseInputSnrs"));
        //        return;
        //    }
        //    try
        //    {
        //        SendCode(Tag.ToString(), position, snr);
        //        this.Close();
        //    }
        //    catch (Exception ex)
        //    {
        //        ViewControl.Logger.Error("Con_Click Failed.", ex);
        //        ToastHelper.Warning(this, ex.Message);
        //    }
        //}
 
        private void Ok_Click(object sender, RoutedEventArgs e)
        {
            ComplateClick?.Invoke(this, e);
            this.Close();
        }
 
        private string ReadDataFrom(SerialPort sp)
        {
            string barcode = "";
            while (sp.BytesToRead > 0)
            {
                byte[] buffer = new byte[sp.BytesToRead];
                sp.Read(buffer, 0, buffer.Length);
                barcode += System.Text.Encoding.ASCII.GetString(buffer);
                System.Threading.Thread.Sleep(50);
            }
            return barcode;
        }
 
        private void Window_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                targetCellInfo = null;
                serialPort.Dispose();
                serialPort = null;
            }
            catch (Exception ex)
            {
            }
        }
 
        private void TextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //string barcode = 
                Dispatcher.Invoke(() =>
                {
                    if (snrText.IsFocused)
                    {
                        Con_Click(null, null);
                    }
                    else
                    {
                        //if (ParamSetting.CustomerCode != "LIXUN")
                        //{
                        //    snrText.Focus();
                        //    return;
                        //}
                        string barcode = positionText.Text;
                        try
                        {
                            targetCellInfo = ScannerParser.GetCellInfoByCode(this.model, this.columns, this.rows, barcode);
                            if (!TestResultView.nameTables.ContainsKey(targetCellInfo.OvenName))
                            {
                                MsgBoxHelper2.Error($"老化炉 [{targetCellInfo.OvenName}] 不存在,请检查配置");
                                positionText.Text = string.Empty;
                                positionText.Focus();
                                targetCellInfo = null;
                                return;
                            }
 
                            var sourceTable = TestResultView.tables[this.ovenIndex];
                            if (sourceTable.title != targetCellInfo.OvenName)
                            {
                                MsgBoxHelper2.Error($"请切换至 [{targetCellInfo.OvenName}] 区扫码,当前为 [{sourceTable.title}] 区!");
                                positionText.Text = string.Empty;
                                positionText.Focus();
                                targetCellInfo = null;
                                return;
                            }
 
                            var oven = TestResultView.nameTables[targetCellInfo.OvenName];
                            if (oven.cells.Length < targetCellInfo.Index + 1)
                            {
                                MsgBoxHelper2.Error($"穴位号 [{barcode}] 超出索引 {targetCellInfo.Index}");
                                positionText.Text = string.Empty;
                                positionText.Focus();
                                targetCellInfo = null;
                                return;
                            }
                            snrText.Focus();
                        }
                        catch (Exception ex)
                        {
                            positionText.Text = string.Empty;
                            positionText.Focus();
                            ViewControl.Logger.Error("Parse Position Code Error.", ex);
                            MsgBoxHelper2.Error($"穴位号 [{barcode}] 解析失败: {ex.Message}");
                        }
                    }
                });
            }
        }
    }
}