alielie
2025-04-10 6bcafc823e836ecd5790f87178a906333699f868
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
using HMI.Base;
using HMI.Core;
using HMI.Core.Entity;
using HMI.Core.Manager;
using HMI.Core.Util;
using HMI.UI;
using HMI.UI.Util;
using HMI.Util;
using NationalInstruments.TestStand.Interop.API;
using NationalInstruments.TestStand.Interop.UI.Ax;
using Panuon.WPF.UI;
using ScottPlot;
using ScottPlot.Plottables;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.DataVisualization.Charting;
 
namespace Plugin.TsExecution
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class TsExecution : PluginControl
    {
        //private OpcInterface.OpcInterface OpcHandle = new OpcInterface.OpcInterface();
        #region TestStand事件
        /// <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 AxApplicationMgr AxApplicationMgr;
        private Execution execution = null;
 
        private Chart chart;
        #endregion
 
        private List<SingleControl> tsSockets = new List<SingleControl>();
        /// <summary>
        /// 样件模式状态
        /// </summary>
        private bool sampleStatus;
        public bool SampleStatus
        {
            get { return sampleStatus; }
            set
            {
                Set(ref sampleStatus, value);
                SampleTest(value);
            }
        }
 
        private bool isLoadOK = false;
        private Timer GCTimer;
 
        private int PassAmount = 0;
        private int FailAmount = 0;
 
        /// <summary>
        /// Socket数量
        /// </summary>
        private int socketNum = 1;
 
        private ProductData selectedProduct;
 
        public ProductData SelectedProduct
        {
            get { return selectedProduct; }
            set
            {
                Set(ref selectedProduct, value);
                SetTestSeqFile(value);
            }
        }
 
        private ObservableCollection<ProductData> products;
 
        public ObservableCollection<ProductData> Products
        {
            get { return products; }
            set
            {
                Set(ref products, value);
            }
        }
 
        private Pie pie;
        private string CountIniPath;
 
        private bool alarmVisiable;
        public bool AlarmVisiable
        {
            get => alarmVisiable;
            set
            {
                Set(ref alarmVisiable, value);
            }
        }
 
        public TsExecution()
        {
            DataContext = this;
            GCTimer = new Timer();
            InitializeComponent();
            InitChart();
            InitTsEngine();
            //初始化TestStand引擎
            this.InitTestStandEngine();
 
        }
 
        public override void SetBaseFolder(string folder)
        {
            CountIniPath = Path.Combine(folder, "Count.ini");
            base.SetBaseFolder(folder);
        }
 
        public override void InitFinish()
        {
            this.ReadCount(out int pass, out int fail);
            this.DisplayCount(pass, fail);
            UpdateChart(pass, fail);
            InitProducts();
            base.InitFinish();
        }
 
        /// <summary>
        /// 初始化Winform图表
        /// </summary>
        private void InitChart()
        {
            pieChart.Plot.Axes.Frameless();
            pieChart.Plot.HideGrid();
            pieChart.Plot.DataBackground.Color = Colors.Transparent;
 
            var legend = pieChart.Plot.ShowLegend(Alignment.UpperRight);
            legend.Alignment = Alignment.UpperRight;
            legend.Padding = new PixelPadding(0);
            legend.FontSize = (float)CustomFontSizeConverter.CountFontSize(20, 300, 300);
            pieChart.UserInputProcessor.Disable();
            pieChart.Plot.Font.Automatic();
 
            List<PieSlice> slices = new List<PieSlice> {
    new PieSlice() { Value = 5, FillColor = Colors.Green,
        LabelFontSize = (float)CustomFontSizeConverter.CountFontSize(20,300,300),
        Label = "Pass",LegendText="Pass" },
    new PieSlice() { Value = 2, FillColor = Colors.Red,
        LabelFontSize = (float)CustomFontSizeConverter.CountFontSize(20,300,300),
        Label = "Fail",LegendText="Fail" } };
 
 
            pie = pieChart.Plot.Add.Pie(slices);
        }
 
        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();
                if (!string.IsNullOrEmpty(tmpNum))
                {
                    this.socketNum = Convert.ToInt32(tmpNum);
                }
                SelectedProduct = Products[0];
                RefershUI();
            }
            SampleStatus = false;
        }
 
        /// <summary>
        /// 初始化TestStand引擎
        /// </summary>
        private void InitTsEngine()
        {
            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();
        }
 
        private void PluginControl_Loaded(object sender, RoutedEventArgs e)
        {
            new MaskWindow((WindowX)Window.GetWindow(this),
                (win) =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            //连接OPChandle
                            //this.OpcHandle.Connect2("127.0.0.1", 6543, 18081, out string ErrMsg, null);
                            //启动测试进程
                            StartSequence();
                            isLoadOK = true;
                        }
                        catch (Exception ex)
                        {
                            log.Error("TsExecution Loaded Failed.", ex);
                            MsgBoxHelper.Error(this, $"{LangUtil.Get("Ts.UserControlLoadFailed")}: {ex.Message}");
                        }
 
                        try
                        {
                            if (Environment.Version.ToString() != this.AxApplicationMgr.GetEngine().DotNetCLRVersion)
                                this.GCTimer.Enabled = true;
                        }
                        catch (Exception ex)
                        {
                            log.Error("TsExecution GCTimer Start Failed", ex);
                            MsgBoxHelper.Error(this, $"{LangUtil.Get("Ts.LoadFailed")}: {ex.Message}");
                        }
                        finally
                        {
                            win.Close();
                        }
                        if (isLoadOK) Loaded -= PluginControl_Loaded;
                    });
                }
                ).Info(LangUtil.Get("App.UsercontrolIsLoading"));
        }
 
        private void RefershUI()
        {
            panel.Children.Clear();
            //重新生成子面板
            for (int i = 0; i < this.socketNum; i++)
            {
                SingleControl control = new SingleControl(i, CountIniPath);
                panel.Children.Add(control);
                tsSockets.Add(control);
            }
            if (tsSockets.Count == 1)
            {
                panel.Columns = 1;
            }
            else
            {
                panel.Columns = 2;
            }
        }
 
        /// <summary>
        /// 初始化TestStand引擎
        /// </summary>
        private void InitTestStandEngine()
        {
            try
            {
                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)
            {
                throw new Exception(LangUtil.Get("Ts.InitTestStandEngineFail"), ex);
            }
        }
 
        /// <summary>
        /// 读取Count配置文件的pass和fail数
        /// </summary>
        /// <param name="pass">合格数</param>
        /// <param name="fail">不合格数</param>
        private void ReadCount(out int pass, out int fail)
        {
            pass = Convert.ToInt32(IniFileHelper.ReadIniData("Count", "Pass", "", CountIniPath));
            fail = Convert.ToInt32(IniFileHelper.ReadIniData("Count", "Fail", "", CountIniPath));
        }
 
        private void WriteCount(int pass, int fail)
        {
            IniFileHelper.WriteIniData("Count", "Pass", pass.ToString(), CountIniPath);
            IniFileHelper.WriteIniData("Count", "Fail", fail.ToString(), CountIniPath);
        }
 
        /// <summary>
        /// 刷新计数
        /// </summary>
        /// <param name="pass">合格数</param>
        /// <param name="fail">不合格数</param>
        private void DisplayCount(int pass, int fail)
        {
            int total = pass + fail;
            double passRate;
            if (total == 0)
            {
                passRate = 0.00;
            }
            else
            {
                passRate = (double)pass / (double)total * 100.00;
            }
            this.TbPass.Text = pass.ToString();
            this.TbFail.Text = fail.ToString();
            this.TbTotal.Text = total.ToString();
            this.TbPassRate.Text = string.Format("{0:0.00}", passRate) + "%";
            WriteCount(pass, fail);
        }
 
        /// <summary>
        /// 启动样件测试
        /// </summary>
        /// <param name="flag"></param>
        /// <exception cref="Exception"></exception>
        private void SampleTest(bool flag)
        {
            try
            {
                if (this.tsSockets.Count == 0)
                    return;
                if (this.tsSockets[0].SequenceFileContext == null)
                    return;
                bool val = this.tsSockets[0].SequenceFileContext.StationGlobals.Exists("StationState.Sample", 0);
                if (val)
                {
                    this.tsSockets[0].SequenceFileContext.StationGlobals.SetValBoolean("StationState.Sample", 0, flag);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(LangUtil.Get("Ts.SampleTestFail"), ex);
            }
        }
 
        /// <summary>
        /// 启动测试序列
        /// </summary>
        private void StartSequence()
        {
            //MaskWindow mask = new MaskWindow();
            try
            {
                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);
 
                Dispatcher.Invoke(() =>
                {
                    this.CbProduct.IsEnabled = false;
                    this.BtnStartSeq.IsEnabled = false;
                    this.BtnStopSeq.IsEnabled = true;
                });
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() =>
                {
                    log.Error("Start Sequence Failed.", ex);
                    MsgBoxHelper.Error(this, $"{LangUtil.Get("Ts.StartSequenceFail")}: {ex.Message}");
                });
            }
            finally
            {
 
            }
        }
 
        public void StopSequenceClick()
        {
            new MaskWindow((WindowX)Window.GetWindow(this),
                    (win) =>
                    {
                        Dispatcher.Invoke(() =>
                        {
                            try
                            {
                                StopSequence();
                            }
                            finally
                            {
                                win.Close();
                            }
                        });
                    }
                    ).Info(LangUtil.Get("App.SequenceIsStopping"));
        }
 
        /// <summary>
        /// 停止测试序列
        /// </summary>
        private void StopSequence()
        {
            try
            {
                if (this.tsSockets.Count > 0 && this.tsSockets[0]?.SequenceFileContext != null)
                {
                    bool val = this.tsSockets[0].SequenceFileContext.StationGlobals.Exists("StationState.StopTest", 0);
                    if (val)
                    {
                        tsSockets[0].SequenceFileContext.StationGlobals.SetValBoolean("StationState.StopTest", 0, true);
                        bool isStop = this.execution.WaitForEndEx(2000, true, null, null);
                    }
                }
                this.CbProduct.IsEnabled = true;
                this.BtnStartSeq.IsEnabled = true;
                this.BtnStopSeq.IsEnabled = false;
            }
            catch (Exception ex)
            {
                log.Error("Stop Sequence Failed.", ex);
                MsgBoxHelper.Error(this, $"{LangUtil.Get("Ts.StopSequenceFail")}: {ex.Message}");
            }
        }
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            switch (btn.Name)
            {
                case "BtnStartSeq":
                    StartClick();
                    break;
                case "BtnStopSeq":
                    StopSequenceClick();
                    break;
                case "BtnClearNum":
                    ClearNum();
                    break;
                case "BtnSample":
                    SampleStatus = !SampleStatus;
                    break;
                default:
                    break;
            }
        }
 
        private void StartClick()
        {
            new MaskWindow(Window.GetWindow(this),
                (win) =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            StartSequence();
                        }
                        finally
                        {
                            win.Close();
                        }
                    });
                }).Info(LangUtil.Get("Ts.SequenceIsStarting"));
        }
 
        /// <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, NationalInstruments.TestStand.Interop.UI.Ax._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 Index = Convert.ToInt16(e.uiMsg.NumericData);//SocketIndex
                switch (EventCase)
                {
                    case 10001://传递SocketContext
                        tsSockets[Index].SequenceFileContext = (SequenceContext)e.uiMsg.ActiveXData;
                        break;
 
                    case 10002://更新测试状态
                        string status = e.uiMsg.StringData;
                        this.tsSockets[Index].UpdateStatus(status);
                        this.UpdateTestCounter();
                        break;
 
                    case 10003://发送测试数据
                        string[] TestItems = e.uiMsg.StringData.Split('\t');
                        tsSockets[Index].AddTestData(TestItems[0], TestItems[4], TestItems[1], TestItems[2], TestItems[3], TestItems[5]);
 
                        break;
 
                    case 10004://发送测试过程信息
                        this.tsSockets[Index].CurrentStep = e.uiMsg.StringData;
                        break;
 
                    case 10005://初始化测试数据,清空测试数据
                        this.tsSockets[Index].IniTestData();
                        break;
 
                    case 10006://发送产品条码
                        this.tsSockets[Index].Barcode = e.uiMsg.StringData;
                        break;
 
                    case 10007://开始测试计时
                        tsSockets[Index].ElapseTime = "Start Timing";
                        BtnStopSeq.IsEnabled = false;
                        break;
 
                    case 10008://停止测试计时
                        tsSockets[Index].ElapseTime = "Stop Timing";
                        BtnStopSeq.IsEnabled = true;
                        break;
 
                    case 10009:
                        // 
                        break;
 
                    case 10010:
 
                        //PropertyObj.SetValBoolean("Locals.MD5_Used", 0, true);
                        //PropertyObj.SetValVariant("FileGlobals.MD5_Value", 0, MD5_DATA);
                        //PropertyObj.SetValVariant("StationGlobals.MD5", 0, MD5_DATA);
                        break;
 
                    case 10011:
                        // write model
 
                        break;
 
                    case 10012:
                        // read model
 
                        break;
 
                    case 10013:
                        // read continue
 
 
                        break;
 
                    case 10014:
 
                        break;
 
                    case 10015:
 
                        break;
                    case 10016://显示3D拼接图片
 
                        break;
                    case 10017://更新测试计时,针对部分计时有PLC完成的项目
                        this.tsSockets[Index].ElapseTime = e.uiMsg.StringData;
                        break;
                    case (int)UIMessageCodes.UIMsg_EndExecution://执行结束
                        this.BtnStartSeq.IsEnabled = true;
                        this.BtnStopSeq.IsEnabled = true;
                        // this.ReleaseSequenceFile();
                        break;
                    case 10030://显示测试进度
                        int ProcessVal = Convert.ToInt32(e.uiMsg.StringData);
                        this.tsSockets[Index].SetTestProcess(ProcessVal);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                log.Warn("Ts Event Error.", ex);
            }
        }
 
        private void UpdateTestCounter()
        {
            int PassNum = 0;
            int FailNum = 0;
            foreach (SingleControl socket in this.tsSockets)
            {
                PassNum += socket.PassNum;
                FailNum += socket.FailNum;
            }
            this.DisplayCount(PassNum, FailNum);
            UpdateChart(PassNum, FailNum);
        }
 
        private void UpdateChart(int pass, int fail)
        {
            pie.Slices[0].Value = pass;
            pie.Slices[1].Value = fail;
            pieChart.Refresh();
        }
 
        private void SetTestSeqFile(ProductData product)
        {
            string name = product.Name;
            List<ParameterData> parameters = ProductManager.GetParametersByProductName(name);
            testSeqFile = parameters.FirstOrDefault(p => p.Name == "TestSequence")?.Value?.ToString();
        }
 
        private void ClearNum()
        {
            if (MsgBoxHelper.WarnMessage(Window.GetWindow(this), LangUtil.Get("Ts.MakeSureClearNum")) == MessageBoxResult.OK)
            {
                PassAmount = 0;
                FailAmount = 0;
                DisplayCount(PassAmount, FailAmount);
                UpdateChart(PassAmount, FailAmount);
                //this.OpcHandle.DoFctWriteSingle("Count_Clear", "1", out string ErrMsg);
                foreach (SingleControl socket in tsSockets)
                {
                    socket.ResetCounter();
                }
            }
        }
 
        public override void OnClose(object sender, CancelEventArgs e)
        {
            StopSequence();
            this.engine?.ReleaseSequenceFileEx(this.testSeq, 0);
            this.engine?.ReleaseSequenceFileEx(this.modeSeq, 0);
            this.engine?.UnloadAllModules();
            this.testSeq = null;
            this.modeSeq = null;
            base.OnClose(sender, e);
        }
 
        private void PluginControl_SizeChanged(object sender, SizeChangedEventArgs e)
        {
 
        }
    }
}