alielie
2026-06-04 771a0e7b6b1276087515bbe94de28358cb92963b
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
using HMI.Base;
using HMI.Core.Api;
using HMI.Core.Entity;
using HMI.Core.Manager;
using HMI.Core.Setting;
using HMI.Core.Util;
using HMI.LogUtil;
using HMI.StdControl;
using HMI.UI.Util;
using log4net;
using NationalInstruments.TestStand.Interop.API;
using PLCHelper;
using Plugin.BurnIn.Util;
using Plugin.TsSupport;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
 
namespace Plugin.BurnIn
{
    /// <summary>
    /// ViewControl.xaml 的交互逻辑
    /// </summary>
    public partial class BurnInUI : PluginMaskControl, IAlarmHandler
    {
 
        private System.Timers.Timer timer;
 
        public static ILog Logger { get; private set; }
 
 
        private bool _mesStatus;
 
        public bool mesStatus
        {
            get => _mesStatus;
            set => Set(ref _mesStatus, value);
        }
 
        private string _produceStatus = "INIT";
 
        public string produceStatus
        {
            get => _produceStatus;
            set => Set(ref _produceStatus, value);
        }
 
        private string _fileName;
 
        public string FileName
        {
            get => _fileName;
            set => Set(ref _fileName, value);
        }
 
        private bool enableManualDebug;
        public bool EnableManualDebug
        {
            get => enableManualDebug;
            set
            {
                if (IsRunning)
                {
                    MsgBoxHelper2.Warn("请先结束自动测试");
                    return;
                }
                testResultView.inManualDebugMode = value;
                Set(ref enableManualDebug, value);
            }
        }
 
        public override void SetLogger(ILog logger)
        {
            base.SetLogger(logger);
            Logger = logger;
        }
 
        private bool isRunning = false;
        public bool IsRunning
        {
            get => isRunning;
            set
            {
                Set(ref isRunning, value);
                testResultView.IsRunning = value;
                this.modelSelect.IsEnabled = !value;
                this.btnStop.IsEnabled = value;
                stdEnableMes.CbEnabled = !value;
            }
        }
 
        private bool AutoExecuteSeq = true;
 
        #region TS相关
 
        /// <summary>
        /// 测试序列操作句柄
        /// </summary>
        private SequenceContext SequenceContext = null;
        #endregion
 
        public BurnInUI()
        {
            S7Context.Init(SystemSetting.Instance.PlcIp, SystemSetting.Instance.PlcPort);
            DataContext = this;
            timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.Elapsed += Timer_Elapsed;
            InitializeComponent();
 
 
            //testResultView.testApp.ExitApplication += new EventHandler(this.axApplicationMgr_ExitApplication);
            //testResultView.testApp.UIMessageEvent += new _ApplicationMgrEvents_UIMessageEventEventHandler(this.axApplicationMgr_UIMessageEvent);
            //testResultView.testApp.ExecutionClosed += new _ApplicationMgrEvents_ExecutionClosedEventHandler(this.axApplicationMgr_ExecutionClosed);
        }
 
        private void HandleUIMessage(int EventCase, int MethodCode, string strData, object xData)
        {
            try
            {
                try
                {
                    log.Debug($"EventCase: {EventCase}, MethodCode: {MethodCode}, StrData: {strData}");
                }
                catch
                {
 
                }
 
                if (EventCase == 8)
                {
                    IsRunning = false;
                    return;
                }
 
                if (EventCase != 10014) return;
 
                if (MethodCode == 0)
                {
                    /// 设置句柄
                    this.SequenceContext = (SequenceContext)xData;
                    return;
                }
 
 
                if (MethodCode == 8)
                {
                    /// 更新MES状态
                    mesStatus = strData == "1";
                    return;
                }
 
                if (MethodCode == 9)
                {
                    /// 更新生产状态
                    produceStatus = strData;
                    return;
                }
            }
            catch
            { }
        }
 
        private void ExecutionWrapper_UIMessageEvent(object sender, UIMessageEvent e)
        {
            HandleUIMessage(e.EventCode, Convert.ToInt16(e.NumberData), e.StrData, e.Data);
        }
 
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            testResultView.RefreshCooler();
        }
 
        public TestResultView View
        {
            get => testResultView;
        }
        public static string SannerIniFile { get; private set; }
 
        public override void InitFinish()
        {
            base.InitFinish();
            string path = Path.Combine(BaseFolder, "Count.ini");
            testResultView.SetCountIniPath(path);
            testResultView.InitMainGrid();
 
            path = Path.Combine(BaseFolder, "Scanner.ini");
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }
            SannerIniFile = path;
            LoadProduct();
            var api = S7Context.Get(RunTimeVariablePool.DEFAULT_PLC_NAME);
            log.Debug($"PLC {api.IpAddress}:{api.Port}");
            try
            {
                var value = ParameterManager.GetCommonParameterByName("AutoExecuteSeq");
                AutoExecuteSeq = bool.Parse(value.Value);
            }
            catch
            {
                AutoExecuteSeq = true;
            }
 
            try
            {
                var value = ParameterManager.GetCommonParameterByName("BurnInMainSeq");
                testResultView.testSeqFile = value.Value;
                FileName = Path.GetFileName(value.Value);
            }
            catch
            {
                testResultView.testSeqFile = string.Empty;
                FileName = string.Empty;
            }
            string type = Path.GetExtension(FileName);
            bool isTap = string.Equals(".tapplan", type, StringComparison.OrdinalIgnoreCase);
 
            testResultView.InitTestStandEngine(isTap);
            testResultView.executionWrapper.UIMessageEvent += ExecutionWrapper_UIMessageEvent;
 
            testResultView.SetOvenName();
 
            RefreshUIConfig();
        }
 
        /// <summary>
        /// 刷新UI配置
        /// </summary>
        private void RefreshUIConfig()
        {
            try
            {
                /// 运行中就不管
                if (IsRunning)
                {
                    return;
                }
                bool enableManualDebug = ParameterManager.GetCommonParameterByName("EnableManualDebug", false);
                if (enableManualDebug)
                {
                    FgEnableManualDebug.Visibility = Visibility.Visible;
                }
                else
                {
                    FgEnableManualDebug.Visibility = Visibility.Collapsed;
                    EnableManualDebug = false;
                }
            }
            catch (Exception ex)
            {
                log.Error("RefreshUIConfig Error.", ex);
            }
        }
 
        private bool isLoaded;
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            AlarmShowHelper.AddHandler(this);
            if (AutoExecuteSeq)
            {
                ShowMask(() =>
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        Start_Click(null, null);
                    }), System.Windows.Threading.DispatcherPriority.Background);
                }, (ex) =>
                {
                    ToastHelper.Error("Loaded Failed.");
                    log.Error("Loaded Failed.", ex);
                }, "请稍后", LangUtil.Get("Ts.SequenceIsStarting"));
            }
            else
            {
                IsRunning = false;
            }
            Loaded -= UserControl_Loaded;
        }
 
        public void LoadProduct()
        {
            List<ProductData> products = ProductManager.GetProducts<List<ProductData>>()
                ?? new List<ProductData>();
            this.modelSelect.Items.Clear();
            List<string> productSource = new List<string>();
            foreach (var prd in products)
            {
                this.modelSelect.Items.Add(prd.Name);
                productSource.Add(prd.Name);
            }
            testResultView.SetProductSource(productSource);
            testResultView.SetCurrentProduct(null);
 
            //string model = testResultView.executionWrapper.GetStationGlobalValue<string>("ProductModel", 1);
            ////testResultView.engine.Globals.GetValString("ProductModel", 1);
            //if (!string.IsNullOrEmpty(model))
            //{
            //    this.modelSelect.SelectedItem = model;
            //    testResultView.SetCurrentProduct(model);
            //}
            //else if (products.Count > 0)
            //{
            //    this.modelSelect.SelectedIndex = 0;
            //    testResultView.SetCurrentProduct(products[0].Name);
            //}
        }
 
        private void modelSelect_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                string currentModel = this.modelSelect.SelectedItem.ToString();
                List<ParameterData> parameters = ProductManager.GetParametersByProductName(currentModel);
 
                testResultView.executionWrapper.SetStationGlobalValue<string>("ProductModel", 0, currentModel);
                testResultView.executionWrapper.CommitToDisk(false);
 
                //testResultView.engine.Globals.SetValString("ProductModel", 0, currentModel);
                //testResultView.engine.CommitGlobalsToDisk(promptOnSaveConflicts: false);
            }
            catch (Exception ex)
            {
                MessageBox.Show("切换产品型号失败!" + ex.Message + ex.StackTrace);
            }
        }
 
        private void Start_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(testResultView.testSeqFile))
                {
                    MsgBoxHelper2.Warn("请先设置BurnInMainSeq属性!");
                    IsRunning = false;
                    return;
                }
                LogHelper.Info("UI", "总启动按钮按下", out _);
                log.Info("总启动按钮按下");
                ShowMask(() =>
                {
                    testResultView.StartTestSequence();
                    Dispatcher.Invoke(() =>
                    {
                        IsRunning = true;
                    });
                }, (ex) =>
                {
                    log.Error("StartTestSequence Error.", ex);
                    Dispatcher.Invoke(() =>
                    {
                        MsgBoxHelper.Error(Window.GetWindow(this), $"{this.lang("Ts.StartTestSequenceFailed")}: {ex.Message}");
                    });
                }, null, "请稍后...");
            }
            catch (Exception ex)
            {
                log.Error("Start_Click Failed.", ex);
                MsgBoxHelper.Error(Window.GetWindow(this),
                    $"{this.lang("Ts.StartTestSequenceFailed")}: {ex.Message}");
            }
        }
 
        private void Stop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                bool breakStop = false;
                foreach (var oven in TestResultView.tables)
                {
                    if (oven.IsTesting)
                    {
                        breakStop = true;
                        break;
                    }
                }
                if (breakStop)
                {
                    MsgBoxHelper2.Warn(this.lang("Tr.OvenIsTesting"));
                    return;
                }
 
                if (MsgBoxHelper2.WarnChoose(this.lang("Tr.MakeSureStopAllTest")) != MessageBoxResult.OK)
                {
                    return;
                }
 
                LogHelper.Info("UI", "总停止按钮按下", out _);
                log.Info("总停止按钮按下");
                testResultView.StopTest();
                /// 已经加了WaitForExit,这里可以改为false
                IsRunning = false;
            }
            catch (Exception ex)
            {
                log.Error("Stop_Click Failed.", ex);
                MsgBoxHelper.Error(Window.GetWindow(this),
                    $"{this.lang("Ts.StopTestSequenceFailed")}: {ex.Message}");
            }
        }
 
        private void testResultView_Loaded(object sender, RoutedEventArgs e)
        {
        }
 
        /// <summary>
        /// 计数清零按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClear_Click(object sender, RoutedEventArgs e)
        {
            testResultView.ClearNumber();
        }
 
        private void ScannerSetting_Click(object sender, RoutedEventArgs e)
        {
            ScannerSetting setting = new ScannerSetting()
            {
                Owner = Window.GetWindow(this)
            };
            setting.Open(false, "Config");
        }
 
        private void StdEnableMes_ValueChanged(object sender, StdUIEventArg e)
        {
            testResultView.executionWrapper.SetStationGlobalValue<bool>($"SystemSetting.{e.StringValue}", 1, e.BoolValue);
            //testResultView.SequenceContext?.StationGlobals.SetValBoolean($"SystemSetting.{e.StringValue}", 1, e.BoolValue);
        }
 
        public void HandleAlarm(AlarmText alarm)
        {
            if (alarm.Level >= 4 && TestResultView.tables != null)
            {
                log.Info($"4级报警触发: [{alarm.AlarmInfo}],将停止所有炉体测试");
                foreach (var oven in TestResultView.tables)
                {
                    testResultView.SetStartFlag(oven.index, false);
                }
                return;
            }
 
            DataTable targetOven = null;
            foreach (var oven in TestResultView.tables)
            {
                if (alarm.AlarmInfo?.StartsWith(oven.title) == true)
                {
                    targetOven = oven;
                    break;
                }
            }
            if (targetOven == null)
            {
                return;
            }
            if (alarm.Level >= 3)
            {
                /// 3级以上的报警会停止测试
                log.Info($"3级报警触发: [{alarm.AlarmInfo}],将停止老化炉[{targetOven.title}]测试");
                testResultView.SetStartFlag(targetOven.index, false);
            }
        }
 
        public override void Active()
        {
            base.Active();
            LoadProduct();
            RefreshUIConfig();
        }
 
        public override void OnClose(object sender, CancelEventArgs e)
        {
            if (IsRunning)
            {
                MsgBoxHelper2.Warn("请先停止老化测试!");
                e.Cancel = true;
            }
        }
 
        public override void DoClose(object sender, EventArgs e)
        {
            try
            {
                timer?.Stop();
                testResultView.ReleaseResource();
            }
            catch
            {
            }
        }
    }
}