alielie
2026-04-23 ef52fd6fd07508883dce4eb002acda59f0169e59
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
using HMI.Base;
using HMI.Core.Entity;
using HMI.Core.Manager;
using HMI.Core.Util;
using HMI.UI;
using HMI.UI.Entity;
using HMI.UI.Util;
using NationalInstruments.TestStand.Interop.API;
using NationalInstruments.TestStand.Interop.UI.Ax;
using Panuon.WPF.UI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
 
namespace Plugin.JarUI
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class JarUI : PluginControl
    {
        public JarUI()
        {
            DataContext = this;
            InitializeComponent();
            InitTsEngine();
            InitProducts();
        }
 
        public override void InitFinish()
        {
            string iniFile = Path.Combine(BaseFolder, "Config.ini");
            if (!File.Exists(iniFile))
            {
                File.Create(iniFile);
            }
            this.iniFile = iniFile;
        }
 
        #region Properties
 
        #region TestStand相关
        private AxApplicationMgr AxApplicationMgr;
        /// <summary>
        /// TS 引擎
        /// </summary>
        private Engine engine = null;
 
        private string testSeqFile = string.Empty;
        /// <summary>
        /// 测试序列
        /// </summary>
        private SequenceFile testSeq = null;
 
        /// <summary>
        /// 测试模型序列
        /// </summary>
        private SequenceFile modeSeq = null;
        public SequenceContext SequenceContext { get; private set; } = null;
        private Execution execution = null;
        #endregion
 
        private bool _isRunning;
        public bool IsRunning
        {
            get => _isRunning;
            set
            {
                Dispatcher.Invoke(() =>
                {
                    startBtn.IsEnabled = !value;
                    stopBtn.IsEnabled = value;
                    CbProduct.IsEnabled = !value;
                });
                Set(ref _isRunning, value);
            }
        }
 
        private ObservableCollection<ProductData> _products;
 
        public ObservableCollection<ProductData> Products
        {
            get { return _products; }
            set { Set(ref _products, value); }
        }
 
        private ProductData _selectedProduct;
 
        public ProductData SelectedProduct
        {
            get { return _selectedProduct; }
            set
            {
                Set(ref _selectedProduct, value);
                SetTestSeqFile(value);
            }
        }
 
        private bool _enableMes;
        public bool EnableMes
        {
            get => _enableMes;
            set
            {
                if (WriteConfig("EnableMes", value))
                {
                    Set(ref _enableMes, value);
                }
            }
        }
 
 
        private bool isLoadOk = false;
        private string iniFile;
        private JarCell selectedCell;
 
        private JarCell[] tsSockets;
        private Dictionary<string, JarCell> socketMap = new Dictionary<string, JarCell>();
        private SerialPort serialPort;
        #endregion
 
        private void RefershUI()
        {
            tsSockets = new JarCell[18];
            for (int i = 0; i < 18; i++)
            {
                var cell = new JarCell(i);
                cell.GotFocus += Cell_GotFocus;
                uGrid.Children.Add(cell);
                tsSockets[i] = cell;
                socketMap.Add(cell.Name, cell);
            }
        }
 
        private void Cell_GotFocus(object sender, RoutedEventArgs e)
        {
            selectedCell = sender as JarCell;
        }
 
        private void SetTestSeqFile(ProductData product)
        {
            if (product == null)
            {
                testSeqFile = null;
                return;
            }
            string name = product.Name;
            List<ParameterData> parameters = ProductManager.GetParametersByProductName(name);
            testSeqFile = parameters.FirstOrDefault(p => p.Name == "TestSequence")?.Value?.ToString();
            StartSequence();
        }
 
        private void InitProducts()
        {
            Products = ProductManager.GetProducts<ObservableCollection<ProductData>>();
            if (Products != null && Products.Count > 0)
            {
                List<ParameterData> parameters =
                    ParameterManager.GetCommonParameter<List<ParameterData>>();
                string tmpNum = parameters?.FirstOrDefault(p => p.Name == "SocketNum")?.Value?.ToString();
                string lastModel = engine?.Globals.GetValString("StationState.ProductModel", 1);
 
                if (!string.IsNullOrEmpty(lastModel))
                {
                    var product = Products.FirstOrDefault(p => p.Name == lastModel);
                    if (product != null)
                    {
                        SelectedProduct = product;
                        RefershUI();
                        return;
                    }
                }
                SelectedProduct = Products[0];
                RefershUI();
            }
        }
 
        private bool WriteConfig(string name, bool value)
        {
            //IniFileHelper.WriteIniData("Config", name, value.ToString(), CountIniPath);
            try
            {
                if (ParameterManager.UpdateCommonParameter(name, value, out string errMsg))
                {
                    SequenceContext?.StationGlobals.SetValBoolean($"SystemSetting.{name}", 1, value);
                    return true;
                }
                else
                {
                    throw new Exception(errMsg);
                }
            }
            catch (Exception ex)
            {
                MsgBoxHelper2.Error(ex.Message);
                return false;
            }
        }
 
        /// <summary>
        /// 读取配置文件里的几个属性
        /// </summary>
        /// <param name="pass"></param>
        /// <param name="fail"></param>
        private void ReadConfig()
        {
            ParameterData value;
            try
            {
                value = ParameterManager.GetCommonParameterByName("EnableMes");
                _enableMes = bool.Parse(value.Value);
                Set("EnableMes");
            }
            catch
            {
                _enableMes = false;
                Set("EnableMes");
            }
 
            //try
            //{
            //    value = ParameterManager.GetCommonParameterByName("EnableNGPause");
            //    _enableNGPause = bool.Parse(value.Value);
            //    Set("EnableNGPause");
            //}
            //catch
            //{
            //    _enableNGPause = false;
            //    Set("EnableNGPause");
            //}
 
            //try
            //{
            //    value = ParameterManager.GetCommonParameterByName("EnableCanLog");
            //    _enableCanLog = bool.Parse(value.Value);
            //    Set("EnableCanLog");
            //}
            //catch
            //{
            //    _enableCanLog = false;
            //    Set("EnableCanLog");
            //}
 
            //try
            //{
            //    value = ParameterManager.GetCommonParameterByName("EnableDebugMode");
            //    _enableDebugMode = bool.Parse(value.Value);
            //    Set("EnableDebugMode");
            //}
            //catch
            //{
            //    _enableDebugMode = false;
            //    Set("EnableDebugMode");
            //}
 
            //try
            //{
            //    value = ParameterManager.GetCommonParameterByName("EnableSimpleMode");
            //    EnableSimpleMode = bool.Parse(value.Value);
            //}
            //catch
            //{
            //    EnableSimpleMode = false;
            //}
 
            //try
            //{
            //    value = ParameterManager.GetCommonParameterByName("UI_ShowInfoDock");
            //    UI_ShowInfoDock = bool.Parse(value.Value);
            //}
            //catch
            //{
            //    UI_ShowInfoDock = false;
            //}
 
            //try
            //{
 
            //    value = ParameterManager.GetCommonParameterByName("TestReportFolder");
            //    csvDir = value.Value;
            //    if (!Directory.Exists(csvDir))
            //    {
            //        Directory.CreateDirectory(csvDir);
            //    }
            //}
            //catch
            //{
            //    csvDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestReport");
            //}
        }
 
        #region 扫码枪相关
        /// <summary>
        /// 设置扫码枪
        /// </summary>
        private void InitScanner()
        {
            if (serialPort != null) return;
            ScannerConfig common = ScannerConfig.ReadFromIni(iniFile, "Config");
            // 配置串口
            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)
            {
                log.Error("Init Scan Gun Failed.", ex);
                Dispatcher.Invoke(() =>
                {
                    MsgBoxHelper.Error(this, $"{this.lang("Tr.InitGunFailed")}: {ex.StackTrace}");
                });
            }
        }
        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.UTF8.GetString(buffer);
                System.Threading.Thread.Sleep(50);
            }
            return barcode;
        }
 
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                SerialPort sp = (SerialPort)sender;
                string barcode = ReadDataFrom(sp);
                if (selectedCell != null)
                {
                    Dispatcher.Invoke(() =>
                    {
                        selectedCell.SetSn(barcode);
                    });
                    SequenceContext.StationGlobals.SetValString($"StationState.SN[{selectedCell.Index}]", 1, barcode);
                    SequenceContext.StationGlobals.SetValBoolean($"StationState.Socket_{selectedCell.Index}", 1, true);
                }
            }
            catch (Exception ex)
            {
                log.Error("Get Scan Gun Data Failed.", ex);
                MessageBox.Show($"{this.lang("Tr.GetGunData")}: {ex.StackTrace}");
            }
        }
        #endregion
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            switch (btn?.Name)
            {
                case "startBtn":
                    StartBtnClick();
                    break;
                case "stopBtn":
                    StopBtnClick();
                    break;
                case "scannerSettingBtn":
                    ScannerSetting ss = new ScannerSetting
                    {
                        Owner = Window.GetWindow(this)
                    };
                    if (ss.Open(true, "Config", iniFile) == true)
                    {
                        serialPort?.Close();
                        InitScanner();
                    }
                    break;
                default:
                    break;
            }
        }
 
        private void StartBtnClick()
        {
            new MaskWindow(Window.GetWindow(this),
                (win) =>
                {
                    try
                    {
                        StartSequence();
                    }
                    finally
                    {
                        win.Dispatcher.Invoke(() =>
                        {
                            win.Close();
                        });
                    }
                }).Info(LangUtil.Get("Ts.SequenceIsStarting"));
        }
 
        public void StopBtnClick()
        {
            new MaskWindow((WindowX)Window.GetWindow(this),
                    (win) =>
                    {
                        try
                        {
                            bool stoped = StopSequence();
                            if (stoped)
                            {
                                IsRunning = false;
                            }
                        }
                        finally
                        {
                            Dispatcher.Invoke(() =>
                            {
                                win.Close();
                            });
                        }
                    }
                    ).Info(LangUtil.Get("App.SequenceIsStopping"));
        }
 
        private bool StopSequence()
        {
            try
            {
                SequenceContext?.StationGlobals.SetValBoolean("StationState.StopTest", 1, true);
                log.Info($"Stop Result: {SequenceContext?.StationGlobals.GetValBoolean("StationState.StopTest", 1)}");
                if (this.execution == null) return true;
                return this.execution.WaitForEndEx(2000, true, null, null);
            }
            catch (Exception ex)
            {
                log.Error("Stop Sequence Failed.", ex);
                MsgBoxHelper.Error(this, $"{LangUtil.Get("Ts.StopSequenceFail")}: {ex.Message}");
                return false;
            }
        }
 
        private void PluginControl_Loaded(object sender, RoutedEventArgs e)
        {
            new MaskWindow((WindowX)Window.GetWindow(this),
                (win) =>
                {
                    try
                    {
                        InitScanner();
                        isLoadOk = true;
                        StartSequence();
                    }
                    catch (Exception ex)
                    {
                        log.Error("TsExecution Loaded Failed.", ex);
                        Dispatcher.Invoke(() =>
                        {
                            MsgBoxHelper.Error(this, $"{LangUtil.Get("Ts.UserControlLoadFailed")}: {ex.Message}");
                        });
                    }
                    Dispatcher.Invoke(() =>
                    {
                        if (isLoadOk) Loaded -= PluginControl_Loaded;
                    });
                }
                ).Info(LangUtil.Get("App.SequenceIsStarting"));
        }
 
        #region teststand初始化相关
        /// <summary>
        /// 启动测试序列
        /// </summary>
        private void StartSequence()
        {
            try
            {
                if (!isLoadOk) return;
                engine?.Globals.SetValString("StationState.ProductModel", 1, SelectedProduct?.Name);
                engine?.CommitGlobalsToDisk(promptOnSaveConflicts: false);
                this.modeSeq = this.engine.GetSequenceFileEx(@"C:\Program Files\National Instruments\TestStand 2020\Components\Models\TestStandModels\ParallelModel.seq");
                this.testSeq = this.engine.GetSequenceFileEx(this.testSeqFile, 0, TypeConflictHandlerTypes.ConflictHandler_UseGlobalType);
                this.execution = this.engine.NewExecution(this.testSeq, "Test UUTs", this.modeSeq, false, 0, null, null, null);
                IsRunning = true;
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() =>
                {
                    log.Error("Start Sequence Failed.", ex);
                    MsgBoxHelper.Error(this, $"{LangUtil.Get("Ts.StartSequenceFail")}: {ex.Message}");
                });
            }
        }
 
        /// <summary>
        /// 初始化TestStand引擎
        /// </summary>
        private void InitTsEngine()
        {
            try
            {
                AxApplicationMgr = new AxApplicationMgr();
                AxApplicationMgr.ExitApplication += new EventHandler(this.AxApplicationMgr_ExitApplication);
                AxApplicationMgr.UIMessageEvent +=
                    new _ApplicationMgrEvents_UIMessageEventEventHandler(this.AxApplicationMgr_UIMessageEvent);
                AxApplicationMgr.ExecutionClosed +=
                    new _ApplicationMgrEvents_ExecutionClosedEventHandler(this.AxApplicationMgr_ExecutionClosed);
                ((System.ComponentModel.ISupportInitialize)(AxApplicationMgr)).BeginInit();
                host.Child = AxApplicationMgr;
                ((System.ComponentModel.ISupportInitialize)(AxApplicationMgr)).EndInit();
 
                this.engine = this.AxApplicationMgr.GetEngine();
                this.engine.PersistBreakpoints = false;
                this.AxApplicationMgr.IsEditor = true;
                this.AxApplicationMgr.LoginOnStart = false;
                this.AxApplicationMgr.Start();
                this.modeSeq = this.engine.GetSequenceFileEx(@"C:\Program Files\National Instruments\TestStand 2020\Components\Models\TestStandModels\ParallelModel.seq");
            }
            catch (Exception ex)
            {
                log.Error("InitTsEngine Failed.", ex);
                throw ex;
            }
        }
 
        /// <summary>
        /// 退出应用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AxApplicationMgr_ExitApplication(object sender, EventArgs e)
        {
            //Environment.ExitCode = this.AxApplicationMgr.ExitCode;
            //this.Close();
        }
 
        /// <summary>
        /// 进程结束事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AxApplicationMgr_ExecutionClosed(object sender, _ApplicationMgrEvents_ExecutionClosedEvent e)
        {
            try
            {
                if (this.testSeq == null)
                    return;
                this.engine.ReleaseSequenceFileEx(this.testSeq, 0);
                this.engine.ReleaseSequenceFileEx(this.modeSeq, 0);
                this.engine.UnloadAllModules();
                this.testSeq = null;
                this.modeSeq = null;
            }
            catch (Exception ex)
            {
                log.Error("ReleaseSequenceFileEx Failed.", ex);
                MsgBoxHelper.Error(Window.GetWindow(this), $"{LangUtil.Get("Ts.ReleaseSequenceFileFail")}: {ex.Message}");
            }
        }
 
        /// <summary>
        /// TestStand用户交互事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AxApplicationMgr_UIMessageEvent(object sender, _ApplicationMgrEvents_UIMessageEventEvent e)
        {
            try
            {
                int EventCase = Convert.ToInt32(e.uiMsg.Event);
                int MethodCode = Convert.ToInt16(e.uiMsg.NumericData);
                string strData = e.uiMsg.StringData;
 
                try
                {
                    log.Info($"Event: {EventCase}, NumericData: {MethodCode}, StringData: {strData}");
                }
                catch
                {
 
                }
 
                if (EventCase != 10015) return;
                switch (MethodCode)
                {
                    case 0:
                        /// 设置句柄
                        this.SequenceContext = (SequenceContext)e.uiMsg.ActiveXData;
                        break;
                    case 1:
                        var arr1 = strData.Split(';');
                        int index1 = int.Parse(arr1[0]);
                        this.tsSockets[index1].SetStatus(arr1[1]);
                        break;
                    case 2:
                        var arr2 = strData.Split(';');
                        int index2 = int.Parse(arr2[0]);
                        this.tsSockets[index2].SetInfo(arr2[1]);
                        break;
                    case 8:
                        IsRunning = false;
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                log.Warn("Ts Event Error.", ex);
            }
        }
        #endregion
 
 
    }
}