完成从TIA导入变量

This commit is contained in:
2025-08-23 09:09:07 +08:00
parent 7e2e01e3cd
commit 32ade95742
10 changed files with 243 additions and 112 deletions

View File

@@ -36,4 +36,11 @@ public interface IVariableAppService
/// 异步批量导入变量。
/// </summary>
Task<bool> BatchImportVariablesAsync(List<VariableDto> variables);
/// <summary>
/// 检测一组变量是否已存在。
/// </summary>
/// <param name="variablesToCheck">要检查的变量列表。</param>
/// <returns>返回输入列表中已存在的变量。</returns>
Task<List<VariableDto>> FindExistingVariablesAsync(IEnumerable<VariableDto> variablesToCheck);
}

View File

@@ -3,6 +3,8 @@ using DMS.Core.Interfaces;
using DMS.Core.Models;
using DMS.Application.DTOs;
using DMS.Application.Interfaces;
using System.Collections.Generic;
using System.Linq;
namespace DMS.Application.Services;
@@ -138,4 +140,40 @@ public class VariableAppService : IVariableAppService
throw new ApplicationException($"批量导入变量时发生错误,错误信息:{ex.Message}", ex);
}
}
public async Task<List<VariableDto>> FindExistingVariablesAsync(IEnumerable<VariableDto> variablesToCheck)
{
if (variablesToCheck == null || !variablesToCheck.Any())
{
return new List<VariableDto>();
}
var names = variablesToCheck.Select(v => v.Name).Where(n => !string.IsNullOrEmpty(n)).Distinct().ToList();
var s7Addresses = variablesToCheck.Select(v => v.S7Address).Where(a => !string.IsNullOrEmpty(a)).Distinct().ToList();
var opcUaNodeIds = variablesToCheck.Select(v => v.OpcUaNodeId).Where(id => !string.IsNullOrEmpty(id)).Distinct().ToList();
var allVariables = await _repoManager.Variables.GetAllAsync();
var existingVariablesFromDb = allVariables.Where(v =>
(names.Any() && !string.IsNullOrEmpty(v.Name) && names.Contains(v.Name)) ||
(s7Addresses.Any() && !string.IsNullOrEmpty(v.S7Address) && s7Addresses.Contains(v.S7Address)) ||
(opcUaNodeIds.Any() && !string.IsNullOrEmpty(v.OpcUaNodeId) && opcUaNodeIds.Contains(v.OpcUaNodeId)))
.ToList();
if (existingVariablesFromDb == null || !existingVariablesFromDb.Any())
{
return new List<VariableDto>();
}
var existingNames = new HashSet<string>(existingVariablesFromDb.Select(v => v.Name).Where(n => !string.IsNullOrEmpty(n)));
var existingS7Addresses = new HashSet<string>(existingVariablesFromDb.Select(v => v.S7Address).Where(a => !string.IsNullOrEmpty(a)));
var existingOpcUaNodeIds = new HashSet<string>(existingVariablesFromDb.Select(v => v.OpcUaNodeId).Where(id => !string.IsNullOrEmpty(id)));
var result = variablesToCheck.Where(v =>
(!string.IsNullOrEmpty(v.Name) && existingNames.Contains(v.Name)) ||
(!string.IsNullOrEmpty(v.S7Address) && existingS7Addresses.Contains(v.S7Address)) ||
(!string.IsNullOrEmpty(v.OpcUaNodeId) && existingOpcUaNodeIds.Contains(v.OpcUaNodeId)))
.ToList();
return result;
}
}

View File

@@ -5,37 +5,146 @@ using CSharpDataType = SqlSugar.CSharpDataType;
namespace DMS.Infrastructure.Entities;
/// <summary>
/// 代表数据库中的变量实体,与 'variable' 表对应。
/// </summary>
public class DbVariable
{
/// <summary>
/// 主键ID自增长。
/// </summary>
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 变量名称。
/// </summary>
public string Name { get; set; }
/// <summary>
/// 变量的描述信息,可以为空。
/// </summary>
[SugarColumn(IsNullable = true)]
public string Description { get; set; }
/// <summary>
/// 变量的信号类型(例如:状态、控制、报警等)。
/// </summary>
[SugarColumn(ColumnDataType="varchar(20)",SqlParameterDbType=typeof(EnumToStringConvert))]
public SignalType SignalType { get; set; } // 对应 SignalType 枚举
public SignalType SignalType { get; set; }
/// <summary>
/// 变量的轮询级别,决定数据采集频率。
/// </summary>
[SugarColumn(ColumnDataType="varchar(20)",SqlParameterDbType=typeof(EnumToStringConvert))]
public PollLevelType PollLevel { get; set; } // 对应 PollLevelType 枚举
public PollLevelType PollLevel { get; set; }
/// <summary>
/// 指示此变量是否处于激活状态。
/// </summary>
public bool IsActive { get; set; }
/// <summary>
/// 所属变量表的ID (外键)。
/// </summary>
public int VariableTableId { get; set; }
/// <summary>
/// 从设备读取到的原始值。
/// </summary>
[SugarColumn(IsNullable = true)]
public string DataValue { get; set; }
/// <summary>
/// 经过转换公式计算后的显示值。
/// </summary>
[SugarColumn(IsNullable = true)]
public string DisplayValue { get; set; }
/// <summary>
/// S7协议中的地址 (例如: DB1.DBD0, M100.0),可以为空。
/// </summary>
[SugarColumn(IsNullable = true)]
public string S7Address { get; set; }
/// <summary>
/// OPC UA协议中的NodeId可以为空。
/// </summary>
[SugarColumn(IsNullable = true)]
public string OpcUaNodeId { get; set; }
/// <summary>
/// 是否启用历史数据记录。
/// </summary>
public bool IsHistoryEnabled { get; set; }
/// <summary>
/// 历史数据记录的死区值,变化量超过该值时才记录。
/// </summary>
public double HistoryDeadband { get; set; }
/// <summary>
/// 是否启用报警功能。
/// </summary>
public bool IsAlarmEnabled { get; set; }
/// <summary>
/// 报警下限值。
/// </summary>
public double AlarmMinValue { get; set; }
/// <summary>
/// 报警上限值。
/// </summary>
public double AlarmMaxValue { get; set; }
/// <summary>
/// 报警死区值,变化量超过该值时才触发报警。
/// </summary>
public double AlarmDeadband { get; set; }
/// <summary>
/// 变量使用的通讯协议类型。
/// </summary>
[SugarColumn(ColumnDataType="varchar(20)",SqlParameterDbType=typeof(EnumToStringConvert))]
public ProtocolType Protocol { get; set; } // 对应 ProtocolType 枚举
public ProtocolType Protocol { get; set; }
/// <summary>
/// 变量的数据类型。
/// </summary>
[SugarColumn(ColumnDataType="varchar(20)",SqlParameterDbType=typeof(EnumToStringConvert))]
public CSharpDataType CSharpDataType { get; set; } // 对应 CSharpDataType 枚举
public CSharpDataType CSharpDataType { get; set; }
/// <summary>
/// 数值转换公式 (例如: "+3*5"),可以为空。
/// </summary>
[SugarColumn(IsNullable = true)]
public string ConversionFormula { get; set; }
/// <summary>
/// 记录创建时间。
/// </summary>
public DateTime CreatedAt { get; set; }
/// <summary>
/// 记录最后更新时间。
/// </summary>
public DateTime UpdatedAt { get; set; }
/// <summary>
/// 最后更新记录的用户名或系统进程名。
/// </summary>
[SugarColumn(IsNullable = true)]
public string UpdatedBy { get; set; }
/// <summary>
/// 标记该记录是否被修改,用于同步。
/// </summary>
public bool IsModified { get; set; }
/// <summary>
/// OPC UA的更新类型例如轮询、订阅
/// </summary>
[SugarColumn(ColumnDataType="varchar(20)",SqlParameterDbType=typeof(EnumToStringConvert))]
public OpcUaUpdateType OpcUaUpdateType { get; set; }
}

View File

@@ -125,13 +125,10 @@ public partial class DeviceDetailViewModel : ViewModelBase, INavigatable
return;
}
ConfrimDialogViewModel viewModel = new ConfrimDialogViewModel();
viewModel.Message = $"确认要删除变量表名为:{SelectedVariableTable.Name} \n\n此操作将同时删除该变量表下的所有变量数据且无法恢复";
viewModel.Title = "删除变量表";
viewModel.PrimaryButContent = "删除";
var resViewModel = await _dialogService.ShowDialogAsync(viewModel);
if (resViewModel.IsPrimaryButton)
string message = $"确认要删除变量表名为:{SelectedVariableTable.Name} \n\n此操作将同时删除该变量表下的所有变量数据且无法恢复";
ConfrimDialogViewModel viewModel = new ConfrimDialogViewModel("删除变量表",message,"删除");
var res = await _dialogService.ShowDialogAsync(viewModel);
if (res)
{
var isDel = await _variableTableAppService.DeleteVariableTableAsync(SelectedVariableTable.Id);
if (isDel)

View File

@@ -155,13 +155,8 @@ public partial class DevicesViewModel : ViewModelBase, INavigatable
return;
}
ConfrimDialogViewModel viewModel = new ConfrimDialogViewModel();
viewModel.Message = $"确认要删除设备名为:{SelectedDevice.Name}";
viewModel.Title = "删除设备";
viewModel.PrimaryButContent = "删除";
var resViewModel = await _dialogService.ShowDialogAsync(viewModel);
if (resViewModel.IsPrimaryButton)
if (await _dialogService.ShowDialogAsync(new ConfrimDialogViewModel("删除设备",$"确认要删除设备名为:{SelectedDevice.Name}","删除设备")))
{
var isDel = await _deviceAppService.DeleteDeviceByIdAsync(SelectedDevice.Id);
if (isDel)

View File

@@ -3,25 +3,28 @@ using CommunityToolkit.Mvvm.Input;
namespace DMS.WPF.ViewModels.Dialogs;
public partial class ConfrimDialogViewModel : DialogViewModelBase<ConfrimDialogViewModel>
public partial class ConfrimDialogViewModel : DialogViewModelBase<Boolean>
{
public bool IsPrimaryButton { get; set; }
[ObservableProperty]
private string message;
private string _message;
public ConfrimDialogViewModel(string title,string message,string primaryButText)
{
Message = message;
Title = title;
PrimaryButContent = primaryButText;
}
[RelayCommand]
public void ParimaryButton()
private void PrimaryButton()
{
IsPrimaryButton=true;
Close(this);
Close(true);
}
[RelayCommand]
public void CancleButton()
private void CancleButton()
{
IsPrimaryButton=false;
Close(this);
Close(false);
}
}

View File

@@ -13,6 +13,7 @@ namespace DMS.WPF.ViewModels.Dialogs;
public partial class ImportExcelDialogViewModel : DialogViewModelBase<List<Variable>>
{
private readonly IMapper _mapper;
private readonly IExcelService _excelService;
[ObservableProperty]
@@ -21,12 +22,17 @@ public partial class ImportExcelDialogViewModel : DialogViewModelBase<List<Varia
[ObservableProperty]
private List<Variable> _variables = new();
[ObservableProperty]
private ObservableCollection<VariableItemViewModel> _variableItemViewModels ;
[ObservableProperty]
private IList _selectedVariables = new ArrayList();
public ImportExcelDialogViewModel(IExcelService excelService)
public ImportExcelDialogViewModel(IMapper mapper,IExcelService excelService)
{
_mapper = mapper;
_excelService = excelService;
VariableItemViewModels = new();
}
partial void OnFilePathChanged(string? value)
@@ -39,6 +45,7 @@ public partial class ImportExcelDialogViewModel : DialogViewModelBase<List<Varia
try
{
Variables = _excelService.ImprotFromTiaVariableTable(value);
VariableItemViewModels=new ObservableCollection<VariableItemViewModel>(_mapper.Map<List<VariableItemViewModel>>(Variables));
}
catch (System.Exception ex)
{
@@ -55,8 +62,8 @@ public partial class ImportExcelDialogViewModel : DialogViewModelBase<List<Varia
[RelayCommand]
private void ImportSelected()
{
var selected = SelectedVariables.Cast<Variable>().ToList();
Close(selected);
var selected = SelectedVariables.Cast<VariableItemViewModel>().ToList();
Close(_mapper.Map<List<Variable>>(selected));
}
[RelayCommand]

View File

@@ -10,11 +10,14 @@ using DMS.WPF.ViewModels.Items;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;
using DMS.Application.DTOs;
using DMS.Application.Interfaces;
using DMS.Application.Services;
using DMS.Helper;
using Microsoft.Extensions.DependencyInjection;
namespace DMS.WPF.ViewModels;
partial class VariableTableViewModel : ViewModelBase, INavigatable
{
private readonly IMapper _mapper;
@@ -24,6 +27,8 @@ partial class VariableTableViewModel : ViewModelBase, INavigatable
/// </summary>
private readonly IDialogService _dialogService;
private readonly IVariableAppService _variableAppService;
/// <summary>
/// 当前正在操作的变量表实体。
/// 通过 ObservableProperty 自动生成 VariableTable 属性和 OnVariableTableChanged 方法。
@@ -91,10 +96,12 @@ partial class VariableTableViewModel : ViewModelBase, INavigatable
/// <param name="dialogService">对话服务接口的实例。</param>
private readonly DataServices _dataServices;
public VariableTableViewModel(IMapper mapper, IDialogService dialogService, DataServices dataServices)
public VariableTableViewModel(IMapper mapper, IDialogService dialogService, IVariableAppService variableAppService,
DataServices dataServices)
{
_mapper = mapper;
_dialogService = dialogService;
_variableAppService = variableAppService;
_dataServices = dataServices;
IsLoadCompletion = false; // 初始设置为 false表示未完成加载
_variables = new ObservableCollection<VariableItemViewModel>(); // 初始化集合
@@ -294,83 +301,51 @@ partial class VariableTableViewModel : ViewModelBase, INavigatable
[RelayCommand]
private async void ImprotFromTiaVarTable()
{
ImportExcelDialogViewModel viewModel = App.Current.Services.GetRequiredService<ImportExcelDialogViewModel>();
try
{
ImportExcelDialogViewModel
viewModel = App.Current.Services.GetRequiredService<ImportExcelDialogViewModel>();
List<Variable> improtVariable = await _dialogService.ShowDialogAsync(viewModel);
if (improtVariable == null || improtVariable.Count == 0) return;
var improtVariableDtos = _mapper.Map<List<VariableDto>>(improtVariable);
foreach (var variableDto in improtVariableDtos)
{
variableDto.CreatedAt = DateTime.Now;
variableDto.UpdatedAt = DateTime.Now;
}
var existList = await _variableAppService.FindExistingVariablesAsync(improtVariableDtos);
if (existList.Count > 0)
{
// // 拼接要删除的变量名称,用于确认提示
var existNames = string.Join("、", existList.Select(v => v.Name));
var confrimDialogViewModel
= new ConfrimDialogViewModel("存在已经添加的变量", $"变量名称:{existNames},已经存在,是否跳过继续添加其他的变量。取消则不添加任何变量", "继续");
var res = await _dialogService.ShowDialogAsync(confrimDialogViewModel);
if (!res) return;
// 从导入列表中删除已经存在的变量
improtVariableDtos.RemoveAll(variableDto => existList.Contains(variableDto));
}
// ContentDialog processingDialog = null; // 用于显示处理中的对话框
// try
// {
// // 让用户选择要导入的Excel文件路径
// var filePath = await _dialogService.ShowImportExcelDialog();
// if (string.IsNullOrEmpty(filePath))
// return; // 如果用户取消选择,则返回
//
// // 读取Excel文件并将其内容转换为 Variable 列表
// var importVarDataList = DMS.Infrastructure.Helper.ExcelHelper.ImprotFromTiaVariableTable(filePath);
// if (importVarDataList.Count == 0)
// return; // 如果没有读取到数据,则返回
//
// // 显示处理中的对话框
// processingDialog = _dialogService.ShowProcessingDialog("正在处理...", "正在导入变量,请稍等片刻....");
//
// List<Variable> newVariables = new List<Variable>();
// List<string> importedVariableNames = new List<string>();
// List<string> existingVariableNames = new List<string>();
//
// foreach (var variableData in importVarDataList)
// {
// // 判断是否存在重复变量
// // 判断是否存在重复变量,仅在当前 VariableTable 的 Variables 中查找
// bool isDuplicate = Variables.Any(existingVar =>
// (existingVar.Name == variableData.Name) ||
// (!string.IsNullOrEmpty(variableData.NodeId) &&
// existingVar.NodeId == variableData.NodeId) ||
// (!string.IsNullOrEmpty(variableData.S7Address) &&
// existingVar.S7Address == variableData.S7Address)
// );
//
// if (isDuplicate)
// {
// existingVariableNames.Add(variableData.Name);
// }
// else
// {
// variableData.CreateTime = DateTime.Now;
// variableData.IsActive = true;
// variableData.VariableTableId = VariableTable.Id;
// newVariables.Add(variableData);
// importedVariableNames.Add(variableData.Name);
// }
// }
//
// if (newVariables.Any())
// {
// // 批量插入新变量数据到数据库
// var resVarDataCount = await _varDataRepository.AddAsync(newVariables);
// NlogHelper.Info($"成功导入变量:{resVarDataCount}个。");
// }
//
// // 更新界面显示的数据:重新从数据库加载所有变量数据
// await RefreshDataView();
//
// processingDialog?.Hide(); // 隐藏处理中的对话框
//
// // 显示导入结果对话框
// await _dialogService.ShowImportResultDialog(importedVariableNames, existingVariableNames);
// }
// catch (Exception e)
// {
// // 捕获并显示错误通知
// NotificationHelper.ShowError($"从TIA导入变量的过程中发生了不可预期的错误{e.Message}", e);
// }
// finally
// {
// processingDialog?.Hide(); // 确保在任何情况下都隐藏对话框
// }
if (improtVariableDtos.Count != 0)
{
var isSuccess = await _variableAppService.BatchImportVariablesAsync(improtVariableDtos);
if (isSuccess)
{
NotificationHelper.ShowSuccess($"从Excel导入变量成功共导入变量{improtVariableDtos.Count}个");
}
}
else
{
NotificationHelper.ShowSuccess($"列表中没有要添加的变量了。 ");
}
}
catch (Exception e)
{
NotificationHelper.ShowError($"从TIA导入变量的过程中发生了不可预期的错误{e.Message}", e);
}
}
/// <summary>
@@ -904,8 +879,6 @@ partial class VariableTableViewModel : ViewModelBase, INavigatable
{
IsOpcUaProtocolSelected = true;
}
}
}
}
}

View File

@@ -18,7 +18,7 @@
mc:Ignorable="d">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PrimaryButtonClick">
<i:InvokeCommandAction Command="{Binding ParimaryButtonCommand}" />
<i:InvokeCommandAction Command="{Binding PrimaryButtonCommand}" />
</i:EventTrigger>
<i:EventTrigger EventName="CloseButtonClick">
<i:InvokeCommandAction Command="{Binding CancleButtonCommand}" />

View File

@@ -56,7 +56,7 @@
<DataGrid Grid.Row="1"
Margin="0,10,0,0"
ItemsSource="{Binding Variables}"
ItemsSource="{Binding VariableItemViewModels}"
AutoGenerateColumns="False"
CanUserAddRows="False">
<i:Interaction.Behaviors>
@@ -66,7 +66,7 @@
<Style BasedOn="{StaticResource {x:Type DataGrid}}"
TargetType="DataGrid">
<Style.Triggers>
<DataTrigger Binding="{Binding Variables.Count}"
<DataTrigger Binding="{Binding VariableItemViewModels.Count}"
Value="0">
<Setter Property="Visibility"
Value="Collapsed" />
@@ -77,6 +77,8 @@
<DataGrid.Columns>
<DataGridTextColumn Header="名称"
Binding="{Binding Name}" />
<DataGridTextColumn Header="描述"
Binding="{Binding Description}" />
<DataGridTextColumn Header="数据类型"
Binding="{Binding CSharpDataType}" />
<DataGridTextColumn Header="S7地址"