通过S7后台服务从PLC读取值

This commit is contained in:
2025-07-05 02:22:36 +08:00
parent 404501cc17
commit 4f4922e07c
2 changed files with 94 additions and 68 deletions

View File

@@ -12,6 +12,7 @@ using PMSWPF.Helper;
using PMSWPF.Services; using PMSWPF.Services;
using PMSWPF.ViewModels; using PMSWPF.ViewModels;
using PMSWPF.Views; using PMSWPF.Views;
using Microsoft.Extensions.Hosting;
using SqlSugar; using SqlSugar;
using LogLevel = Microsoft.Extensions.Logging.LogLevel; using LogLevel = Microsoft.Extensions.Logging.LogLevel;
@@ -22,72 +23,71 @@ namespace PMSWPF;
/// </summary> /// </summary>
public partial class App : Application public partial class App : Application
{ {
public IServiceProvider Services { get; }
public App() public App()
{ {
Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
.ConfigureServices((context, services) => { ConfigureServices(services); })
.ConfigureLogging(loggingBuilder => { ConfigureLogging(loggingBuilder); })
.Build();
Services = Host.Services;
} }
public new static App Current => (App)Application.Current; public new static App Current => (App)Application.Current;
public IServiceProvider Services { get; set; } public IHost Host { get; }
protected override void OnStartup(StartupEventArgs e) protected override async void OnStartup(StartupEventArgs e)
{ {
base.OnStartup(e); base.OnStartup(e);
InitializeLog(); await Host.StartAsync();
InitializeServices();
InitializeDataBase(); InitializeDataBase();
InitializeMenu().Await((e) => { NotificationHelper.ShowMessage($"初始化主菜单失败:{e.Message}"); }, InitializeMenu()
.Await((e) => { NotificationHelper.ShowMessage($"初始化主菜单失败:{e.Message}"); },
() => { MessageHelper.SendLoadMessage(LoadTypes.Menu); }); () => { MessageHelper.SendLoadMessage(LoadTypes.Menu); });
MainWindow = Services.GetRequiredService<MainView>(); MainWindow = Host.Services.GetRequiredService<MainView>();
MainWindow.Show(); MainWindow.Show();
} }
protected override void OnExit(ExitEventArgs e) protected override async void OnExit(ExitEventArgs e)
{ {
// 应用程序退出时,确保 NLog 缓冲区被清空 await Host.StopAsync();
Host.Dispose();
LogManager.Shutdown(); LogManager.Shutdown();
base.OnExit(e); base.OnExit(e);
} }
private void InitializeServices() private void ConfigureServices(IServiceCollection services)
{ {
var container = new ServiceCollection(); services.AddSingleton<DataServices>();
container.AddLogging(loggingBuilder => services.AddSingleton<NavgatorServices>();
services.AddSingleton<IDialogService, DialogService>();
services.AddSingleton<GrowlNotificationService>();
services.AddHostedService<S7BackgroundService>(); // Register as HostedService
services.AddSingleton<MainViewModel>();
services.AddSingleton<HomeViewModel>();
services.AddSingleton<DevicesViewModel>();
services.AddSingleton<DataTransformViewModel>();
services.AddSingleton<SettingViewModel>();
services.AddSingleton<SettingView>();
services.AddSingleton<MainView>();
services.AddSingleton<HomeView>();
services.AddSingleton<DevicesView>();
services.AddSingleton<DataTransformViewModel>();
services.AddTransient<VariableTableViewModel>();
services.AddSingleton<VariableTableView>();
services.AddScoped<DeviceDetailViewModel>();
services.AddScoped<DeviceDetailView>();
services.AddScoped<MqttsViewModel>();
services.AddScoped<MqttsView>();
}
private void ConfigureLogging(ILoggingBuilder loggingBuilder)
{ {
loggingBuilder.ClearProviders(); loggingBuilder.ClearProviders();
loggingBuilder.SetMinimumLevel(LogLevel.Trace); loggingBuilder.SetMinimumLevel(LogLevel.Trace);
loggingBuilder.AddNLog(); loggingBuilder.AddNLog();
});
container.AddSingleton<DataServices>();
container.AddSingleton<NavgatorServices>();
container.AddSingleton<IDialogService, DialogService>();
container.AddSingleton<GrowlNotificationService>();
container.AddSingleton<MainViewModel>();
container.AddSingleton<HomeViewModel>();
container.AddSingleton<DevicesViewModel>();
container.AddSingleton<DataTransformViewModel>();
container.AddSingleton<SettingViewModel>();
container.AddSingleton<SettingView>();
container.AddSingleton<MainView>();
container.AddSingleton<HomeView>();
container.AddSingleton<DevicesView>();
container.AddSingleton<DataTransformViewModel>();
container.AddTransient<VariableTableViewModel>();
container.AddSingleton<VariableTableView>();
container.AddScoped<DeviceDetailViewModel>();
container.AddScoped<DeviceDetailView>();
container.AddScoped<MqttsViewModel>();
container.AddScoped<MqttsView>();
Services = container.BuildServiceProvider();
// 启动服务
Services.GetRequiredService<GrowlNotificationService>();
}
private void InitializeLog()
{
LogManager.Setup().LoadConfigurationFromFile("Config/nlog.config").GetCurrentClassLogger();
// 捕获未处理的异常并记录 // 捕获未处理的异常并记录
AppDomain.CurrentDomain.UnhandledException += (sender, args) => AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
@@ -96,14 +96,16 @@ public partial class App : Application
if (ex != null) if (ex != null)
{ {
// 可以使用一个专用的 Logger 来记录未处理异常 // 可以使用一个专用的 Logger 来记录未处理异常
LogManager.GetLogger("UnhandledExceptionLogger").Fatal($"应用程序发生未处理的异常:{ex}"); LogManager.GetLogger("UnhandledExceptionLogger")
.Fatal($"应用程序发生未处理的异常:{ex}");
} }
}; };
// 捕获 Dispatcher 线程上的未处理异常 (UI 线程) // 捕获 Dispatcher 线程上的未处理异常 (UI 线程)
this.DispatcherUnhandledException += (sender, args) => this.DispatcherUnhandledException += (sender, args) =>
{ {
LogManager.GetLogger("DispatcherExceptionLogger").Fatal( $"UI 线程发生未处理的异常:{args.Exception}"); LogManager.GetLogger("DispatcherExceptionLogger")
.Fatal($"UI 线程发生未处理的异常:{args.Exception}");
// 标记为已处理,防止应用程序崩溃 (生产环境慎用,可能掩盖问题) // 标记为已处理,防止应用程序崩溃 (生产环境慎用,可能掩盖问题)
// args.Handled = true; // args.Handled = true;
}; };
@@ -112,11 +114,10 @@ public partial class App : Application
// 可以通过以下方式捕获 Task 中的异常。 // 可以通过以下方式捕获 Task 中的异常。
TaskScheduler.UnobservedTaskException += (sender, args) => TaskScheduler.UnobservedTaskException += (sender, args) =>
{ {
LogManager.GetLogger("UnobservedTaskExceptionLogger").Fatal( $"异步任务发生未观察到的异常:{args.Exception}"); LogManager.GetLogger("UnobservedTaskExceptionLogger")
.Fatal($"异步任务发生未观察到的异常:{args.Exception}");
// args.SetObserved(); // 标记为已观察,防止进程终止 // args.SetObserved(); // 标记为已观察,防止进程终止
}; };
} }
/// <summary> /// <summary>
@@ -130,14 +131,26 @@ public partial class App : Application
{ Name = "主页", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Home.Glyph, ParentId = 0 }; { Name = "主页", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Home.Glyph, ParentId = 0 };
var deviceMenu = new DbMenu() var deviceMenu = new DbMenu()
{ Name = "设备", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Devices3.Glyph, ParentId = 0 }; {
Name = "设备", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Devices3.Glyph,
ParentId = 0
};
var dataTransfromMenu = new DbMenu() var dataTransfromMenu = new DbMenu()
{ Name = "数据转换", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.ChromeSwitch.Glyph, ParentId = 0 }; {
Name = "数据转换", Type = MenuType.MainMenu,
Icon = SegoeFluentIcons.ChromeSwitch.Glyph, ParentId = 0
};
var mqttMenu = new DbMenu() var mqttMenu = new DbMenu()
{ Name = "Mqtt服务器", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Cloud.Glyph, ParentId = 0 }; {
Name = "Mqtt服务器", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Cloud.Glyph,
ParentId = 0
};
var settingMenu = new DbMenu() var settingMenu = new DbMenu()
{ Name = "设置", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Settings.Glyph, ParentId = 0 }; {
Name = "设置", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Settings.Glyph,
ParentId = 0
};
var aboutMenu = new DbMenu() var aboutMenu = new DbMenu()
{ Name = "关于", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Info.Glyph, ParentId = 0 }; { Name = "关于", Type = MenuType.MainMenu, Icon = SegoeFluentIcons.Info.Glyph, ParentId = 0 };
await CheckMainMenuExist(db, homeMenu); await CheckMainMenuExist(db, homeMenu);
@@ -151,10 +164,12 @@ public partial class App : Application
private static async Task CheckMainMenuExist(SqlSugarClient db, DbMenu menu) private static async Task CheckMainMenuExist(SqlSugarClient db, DbMenu menu)
{ {
var homeMenuExist = await db.Queryable<DbMenu>().FirstAsync(dm => dm.Name == menu.Name); var homeMenuExist = await db.Queryable<DbMenu>()
.FirstAsync(dm => dm.Name == menu.Name);
if (homeMenuExist == null) if (homeMenuExist == null)
{ {
await db.Insertable<DbMenu>(menu).ExecuteCommandAsync(); await db.Insertable<DbMenu>(menu)
.ExecuteCommandAsync();
} }
} }

View File

@@ -18,6 +18,7 @@ namespace PMSWPF.Services
private readonly DataServices _dataServices; private readonly DataServices _dataServices;
private readonly Dictionary<int, Plc> _s7PlcClients = new Dictionary<int, Plc>(); private readonly Dictionary<int, Plc> _s7PlcClients = new Dictionary<int, Plc>();
private readonly TimeSpan _pollingInterval = TimeSpan.FromSeconds(1); // 轮询间隔 private readonly TimeSpan _pollingInterval = TimeSpan.FromSeconds(1); // 轮询间隔
private List<Device>? _s7Devices;
public S7BackgroundService(ILogger<S7BackgroundService> logger, DataServices dataServices) public S7BackgroundService(ILogger<S7BackgroundService> logger, DataServices dataServices)
{ {
@@ -28,6 +29,8 @@ namespace PMSWPF.Services
private void HandleDeviceListChanged(List<Device> devices) private void HandleDeviceListChanged(List<Device> devices)
{ {
_s7Devices = devices.Where(d => d.ProtocolType == ProtocolType.S7 && d.IsActive)
.ToList();
// 当设备列表变化时更新PLC客户端 // 当设备列表变化时更新PLC客户端
// 这里需要更复杂的逻辑来处理连接的关闭和新连接的建立 // 这里需要更复杂的逻辑来处理连接的关闭和新连接的建立
// 简单起见,这里只做日志记录 // 简单起见,这里只做日志记录
@@ -40,6 +43,9 @@ namespace PMSWPF.Services
stoppingToken.Register(() => _logger.LogInformation("S7 Background Service is stopping.")); stoppingToken.Register(() => _logger.LogInformation("S7 Background Service is stopping."));
_s7Devices = _dataServices.Devices?.Where(d => d.ProtocolType == ProtocolType.S7 && d.IsActive)
.ToList();
while (!stoppingToken.IsCancellationRequested) while (!stoppingToken.IsCancellationRequested)
{ {
_logger.LogDebug("S7 Background Service is doing background work."); _logger.LogDebug("S7 Background Service is doing background work.");
@@ -62,15 +68,13 @@ namespace PMSWPF.Services
private async Task PollS7Devices(CancellationToken stoppingToken) private async Task PollS7Devices(CancellationToken stoppingToken)
{ {
var s7Devices = _dataServices.Devices?.Where(d => d.ProtocolType == ProtocolType.S7 && d.IsActive).ToList(); if (_s7Devices == null || !_s7Devices.Any())
if (s7Devices == null || !s7Devices.Any())
{ {
_logger.LogDebug("No active S7 devices found to poll."); _logger.LogDebug("No active S7 devices found to poll.");
return; return;
} }
foreach (var device in s7Devices) foreach (var device in _s7Devices)
{ {
if (stoppingToken.IsCancellationRequested) return; if (stoppingToken.IsCancellationRequested) return;
@@ -107,11 +111,15 @@ namespace PMSWPF.Services
} }
// Filter variables for the current device and S7 protocol // Filter variables for the current device and S7 protocol
var s7Variables = device.VariableTables var s7VariablesTemp = device
?.SelectMany(vt => vt.DataVariables) .VariableTables.Where(vd => vd.ProtocolType == ProtocolType.S7 && vd.IsActive)
.Where(vd => vd.ProtocolType == ProtocolType.S7 && vd.IsActive)
.ToList(); .ToList();
var s7Variables = s7VariablesTemp.SelectMany(vt => vt.DataVariables)
.ToList();
// ?.SelectMany(vt => vt.DataVariables)
if (s7Variables == null || !s7Variables.Any()) if (s7Variables == null || !s7Variables.Any())
{ {
_logger.LogDebug($"No active S7 variables found for device: {device.Name}"); _logger.LogDebug($"No active S7 variables found for device: {device.Name}");
@@ -119,7 +127,8 @@ namespace PMSWPF.Services
} }
// Batch read variables // Batch read variables
var addressesToRead = s7Variables.Select(vd => vd.S7Address).ToList(); var addressesToRead = s7Variables.Select(vd => vd.S7Address)
.ToList();
if (!addressesToRead.Any()) continue; if (!addressesToRead.Any()) continue;
try try
@@ -146,7 +155,8 @@ namespace PMSWPF.Services
{ {
// Update the variable's DataValue and DisplayValue // Update the variable's DataValue and DisplayValue
variable.DataValue = value.ToString(); variable.DataValue = value.ToString();
variable.DisplayValue = SiemensHelper.ConvertS7Value(value, variable.DataType, variable.Converstion); variable.DisplayValue
= SiemensHelper.ConvertS7Value(value, variable.DataType, variable.Converstion);
_logger.LogDebug($"Read {variable.Name}: {variable.DataValue}"); _logger.LogDebug($"Read {variable.Name}: {variable.DataValue}");
} }
} }
@@ -176,6 +186,7 @@ namespace PMSWPF.Services
_logger.LogInformation($"Closed S7 PLC connection: {plcClient.IP}"); _logger.LogInformation($"Closed S7 PLC connection: {plcClient.IP}");
} }
} }
_s7PlcClients.Clear(); _s7PlcClients.Clear();
await base.StopAsync(stoppingToken); await base.StopAsync(stoppingToken);