75 lines
2.5 KiB
C#
75 lines
2.5 KiB
C#
using MembranePoreTester.Communication;
|
|
using MembranePoreTester.Models;
|
|
using MembranePoreTester.Views;
|
|
using Microsoft.Extensions.Configuration;
|
|
using OfficeOpenXml;
|
|
using System;
|
|
using System.IO;
|
|
using System.Windows;
|
|
|
|
namespace MembranePoreTester
|
|
{
|
|
public partial class App : Application
|
|
{
|
|
public static UserRole CurrentUserRole { get; set; } = UserRole.Operator;
|
|
|
|
public static IPlcService PlcService { get; private set; }
|
|
public static PlcConfiguration PlcConfig { get; private set; }
|
|
|
|
protected override async void OnStartup(StartupEventArgs e)
|
|
{
|
|
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
|
|
|
|
base.OnStartup(e);
|
|
|
|
// 防止在登录窗口关闭时应用程序因没有窗口而自动退出
|
|
ShutdownMode = ShutdownMode.OnExplicitShutdown;
|
|
|
|
// 显示登录窗口,验证用户身份
|
|
var loginWindow = new LoginWindow();
|
|
if (loginWindow.ShowDialog() != true)
|
|
{
|
|
Shutdown();
|
|
return;
|
|
}
|
|
|
|
// 登录成功后初始化数据库和PLC连接
|
|
using var db = new AppDbContext();
|
|
db.Database.EnsureCreated();
|
|
|
|
var builder = new ConfigurationBuilder()
|
|
.SetBasePath(Directory.GetCurrentDirectory())
|
|
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
|
|
|
|
var configuration = builder.Build();
|
|
PlcConfig = configuration.GetSection("PlcSettings").Get<PlcConfiguration>();
|
|
|
|
if (PlcConfig == null)
|
|
throw new InvalidOperationException("PLC settings missing in appsettings.json");
|
|
|
|
PlcService = new ModbusTcpPlcService(PlcConfig);
|
|
|
|
var plcService = App.PlcService as ModbusTcpPlcService;
|
|
try
|
|
{
|
|
await plcService.EnsureConnectedAsync();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
MessageBox.Show($"PLC 连接失败:{ex.Message}");
|
|
}
|
|
|
|
// 启动主窗口,设置为应用程序的主窗口并恢复默认的退出模式
|
|
var mainWindow = new MainWindow();
|
|
MainWindow = mainWindow;
|
|
ShutdownMode = ShutdownMode.OnMainWindowClose;
|
|
mainWindow.Show();
|
|
}
|
|
|
|
protected override void OnExit(ExitEventArgs e)
|
|
{
|
|
(PlcService as IDisposable)?.Dispose();
|
|
base.OnExit(e);
|
|
}
|
|
}
|
|
} |