Files
ASTM-D7896-19TransientHot-W…/ViewModels/ConfigViewModel.cs

90 lines
3.3 KiB
C#
Raw Normal View History

2026-05-15 20:39:11 +08:00
using ASTM_D7896_Tester.Models;
using ASTM_D7896_Tester.Services;
using ASTM_D7896_Tester.Views;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Threading.Tasks;
using System.Windows;
using static ASTM_D7896_Tester.Models.TestParameters;
namespace ASTM_D7896_Tester.ViewModels;
public partial class ConfigViewModel : ObservableObject
{
[ObservableProperty]
private float _pressureCoefficient;
[ObservableProperty]
private float _pressureProtection;
[ObservableProperty]
private float _temperatureCoefficient;
[ObservableProperty]
private float _resistanceCoefficient;
private readonly IPlcService _plcService;
private readonly AppConfig _coefficientAddresses;
public ConfigViewModel()
{
// 从 App 静态属性获取 PLC 服务和系数寄存器地址
_plcService = ASTM_D7896_Tester.App.PlcService;
_coefficientAddresses = ASTM_D7896_Tester.App.PlcConfig;
// 窗口打开时加载一次
LoadFromPlc();
}
private async void LoadFromPlc()
{
try
{
PressureCoefficient = await _plcService.ReadFloatAsync(_coefficientAddresses.TestParameters.CalibrationCoefficients.PressureCoefficient);
PressureProtection = await _plcService.ReadFloatAsync(_coefficientAddresses.TestParameters.CalibrationCoefficients.PressureProtection);
TemperatureCoefficient = await _plcService.ReadFloatAsync(_coefficientAddresses.TestParameters.CalibrationCoefficients.TemperatureCoefficient);
ResistanceCoefficient = await _plcService.ReadFloatAsync(_coefficientAddresses.TestParameters.CalibrationCoefficients.ResistanceCoefficient);
}
catch (Exception ex)
{
MessageBox.Show($"从 PLC 读取系数失败:{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
2026-05-27 14:04:14 +08:00
//public IAsyncRelayCommand SaveCommand => new AsyncRelayCommand(Save);
2026-05-15 20:39:11 +08:00
[RelayCommand]
private async Task Save()
{
try
{
// 写入 PLC使用 WriteMultipleRegistersAsync该方法支持 float
await _plcService.WriteMultipleRegistersAsync(_coefficientAddresses.TestParameters.CalibrationCoefficients.PressureCoefficient, PressureCoefficient);
await _plcService.WriteMultipleRegistersAsync(_coefficientAddresses.TestParameters.CalibrationCoefficients.PressureProtection, PressureProtection);
await _plcService.WriteMultipleRegistersAsync(_coefficientAddresses.TestParameters.CalibrationCoefficients.TemperatureCoefficient, TemperatureCoefficient);
await _plcService.WriteMultipleRegistersAsync(_coefficientAddresses.TestParameters.CalibrationCoefficients.ResistanceCoefficient, ResistanceCoefficient);
MessageBox.Show("系数已保存到 PLC。", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
CloseWindow();
}
catch (Exception ex)
{
MessageBox.Show($"保存失败:{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
[RelayCommand]
private void Cancel()
{
CloseWindow();
}
private void CloseWindow()
{
Application.Current.Windows.OfType<ConfigWindow>().FirstOrDefault()?.Close();
}
}