From 595139fb024cd7b3191038bdfc48e27a55a7d40c Mon Sep 17 00:00:00 2001 From: "David P.G" Date: Sat, 18 Oct 2025 17:18:09 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=E5=B0=86AppDataCenterService=E6=94=B9?= =?UTF-8?q?=E4=B8=BAAppCenterService,=E5=B0=86AppDataStorageService?= =?UTF-8?q?=E6=94=B9=E4=B8=BAAppStorageService,=E5=B0=86=E8=A7=A6=E5=8F=91?= =?UTF-8?q?=E5=99=A8=E7=9A=84=E5=A2=9E=E5=88=A0=E6=94=B9=E6=88=90=E5=90=88?= =?UTF-8?q?=E5=B9=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DMS.Application/DTOs/TriggerDefinitionDto.cs | 89 ------- .../Events/TriggerVariableChangedEventArgs.cs | 16 ++ .../Interfaces/Database/ITriggerAppService.cs | 53 +++++ .../Database/ITriggerVariableAppService.cs | 43 ++++ ...aCenterService.cs => IAppCenterService.cs} | 2 +- ...torageService.cs => IAppStorageService.cs} | 10 +- DMS.Application/Interfaces/IEventService.cs | 16 ++ .../Management/ITriggerManagementService.cs | 11 +- .../ITriggerVariableManagementService.cs | 41 ++++ DMS.Application/Profiles/MappingProfile.cs | 6 +- ...taCenterService.cs => AppCenterService.cs} | 6 +- ...StorageService.cs => AppStorageService.cs} | 10 +- DMS.Application/Services/DataLoaderService.cs | 42 ++-- .../Services/Database/MqttAliasAppService.cs | 6 +- .../Services/Database/TriggerAppService.cs | 201 ++++++++++++++++ .../Database/TriggerVariableAppService.cs | 66 ++++++ DMS.Application/Services/EventService.cs | 25 +- .../Management/DeviceManagementService.cs | 22 +- .../Management/LogManagementService.cs | 12 +- .../Management/MenuManagementService.cs | 24 +- .../Management/MqttAliasManagementService.cs | 4 +- .../Management/MqttManagementService.cs | 20 +- .../Management/TriggerManagementService.cs | 75 +++--- .../TriggerVariableManagementService.cs | 125 ++++++++++ .../Management/VariableManagementService.cs | 24 +- .../VariableTableManagementService.cs | 18 +- .../Monitoring/DeviceMonitoringService.cs | 16 +- .../Triggers/Impl/TriggerEvaluationService.cs | 4 +- .../Services/Triggers/TriggerContext.cs | 3 +- DMS.Core/Interfaces/IRepositoryManager.cs | 9 +- ...sRepository.cs => IMqttAliasRepository.cs} | 2 +- .../ITriggerVariableRepository.cs | 15 ++ .../Triggers/ITriggerRepository.cs | 43 +--- .../Services/IMqttServiceManager.cs | 2 +- DMS.Core/Models/Triggers/TriggerDefinition.cs | 2 +- DMS.Core/Models/Triggers/TriggerVariable.cs | 25 ++ ...{DbVariableMqttAlias.cs => DbMqttAlias.cs} | 2 +- DMS.Infrastructure/Profiles/MappingProfile.cs | 14 +- .../Repositories/InitializeRepository.cs | 2 +- ...asRepository.cs => MqttAliasRepository.cs} | 24 +- .../Repositories/RepositoryManager.cs | 21 +- .../Repositories/TriggerRepository.cs | 223 ++++++------------ .../Repositories/TriggerVariableRepository.cs | 113 +++++++++ .../Services/Mqtt/MqttBackgroundService.cs | 14 +- .../Services/Mqtt/MqttDeviceContext.cs | 4 +- .../Services/Mqtt/MqttServiceManager.cs | 14 +- .../Services/OpcUa/OpcUaServiceManager.cs | 8 +- .../OpcUa/OptimizedOpcUaBackgroundService.cs | 16 +- .../S7/OptimizedS7BackgroundService.cs | 20 +- .../Services/S7/S7ServiceManager.cs | 16 +- DMS.WPF/App.xaml.cs | 7 +- DMS.WPF/Services/DataEventService.cs | 8 +- DMS.WPF/Services/DeviceDataService.cs | 24 +- DMS.WPF/Services/LogDataService.cs | 10 +- DMS.WPF/Services/MenuDataService.cs | 10 +- DMS.WPF/Services/MqttAliasDataService.cs | 10 +- DMS.WPF/Services/MqttDataService.cs | 8 +- DMS.WPF/Services/TriggerDataService.cs | 29 +-- DMS.WPF/Services/VariableDataService.cs | 14 +- DMS.WPF/Services/VariableTableDataService.cs | 12 +- DMS.WPF/Services/WPFDataService.cs | 6 +- DMS.WPF/ViewModels/LogHistoryViewModel.cs | 10 +- DMS.WPF/ViewModels/SplashViewModel.cs | 8 +- DMS.WPF/ViewModels/TriggersViewModel.cs | 23 +- 64 files changed, 1159 insertions(+), 599 deletions(-) delete mode 100644 DMS.Application/DTOs/TriggerDefinitionDto.cs create mode 100644 DMS.Application/Events/TriggerVariableChangedEventArgs.cs create mode 100644 DMS.Application/Interfaces/Database/ITriggerAppService.cs create mode 100644 DMS.Application/Interfaces/Database/ITriggerVariableAppService.cs rename DMS.Application/Interfaces/{IAppDataCenterService.cs => IAppCenterService.cs} (96%) rename DMS.Application/Interfaces/{IAppDataStorageService.cs => IAppStorageService.cs} (82%) create mode 100644 DMS.Application/Interfaces/Management/ITriggerVariableManagementService.cs rename DMS.Application/Services/{AppDataCenterService.cs => AppCenterService.cs} (96%) rename DMS.Application/Services/{AppDataStorageService.cs => AppStorageService.cs} (83%) create mode 100644 DMS.Application/Services/Database/TriggerAppService.cs create mode 100644 DMS.Application/Services/Database/TriggerVariableAppService.cs create mode 100644 DMS.Application/Services/Management/TriggerVariableManagementService.cs rename DMS.Core/Interfaces/Repositories/{IVariableMqttAliasRepository.cs => IMqttAliasRepository.cs} (82%) create mode 100644 DMS.Core/Interfaces/Repositories/ITriggerVariableRepository.cs create mode 100644 DMS.Core/Models/Triggers/TriggerVariable.cs rename DMS.Infrastructure/Entities/{DbVariableMqttAlias.cs => DbMqttAlias.cs} (95%) rename DMS.Infrastructure/Repositories/{VariableMqttAliasRepository.cs => MqttAliasRepository.cs} (79%) create mode 100644 DMS.Infrastructure/Repositories/TriggerVariableRepository.cs diff --git a/DMS.Application/DTOs/TriggerDefinitionDto.cs b/DMS.Application/DTOs/TriggerDefinitionDto.cs deleted file mode 100644 index 16e6225..0000000 --- a/DMS.Application/DTOs/TriggerDefinitionDto.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.Collections.Generic; -using DMS.Core.Models.Triggers; - -// 引入枚举 - -namespace DMS.Application.DTOs -{ - /// - /// 触发器定义 DTO (用于应用层与表示层之间的数据传输) - /// - public class TriggerDefinitionDto - { - /// - /// 触发器唯一标识符 - /// - public int Id { get; set; } - - /// - /// 关联的变量 ID 列表 - /// - public List VariableIds { get; set; } = new List(); - - /// - /// 触发器是否处于激活状态 - /// - public bool IsActive { get; set; } - - // --- 条件部分 --- - - /// - /// 触发条件类型 - /// - public ConditionType Condition { get; set; } - - /// - /// 阈值 (用于 GreaterThan, LessThan, EqualTo, NotEqualTo) - /// - public double? Threshold { get; set; } - - /// - /// 下限 (用于 InRange, OutOfRange) - /// - public double? LowerBound { get; set; } - - /// - /// 上限 (用于 InRange, OutOfRange) - /// - public double? UpperBound { get; set; } - - // --- 动作部分 --- - - /// - /// 动作类型 - /// - public ActionType Action { get; set; } - - /// - /// 动作配置 JSON 字符串 - /// - public string ActionConfigurationJson { get; set; } - - // --- 抑制与状态部分 --- - - /// - /// 抑制持续时间 - /// - public TimeSpan? SuppressionDuration { get; set; } - - /// - /// 上次触发的时间 - /// - public DateTime? LastTriggeredAt { get; set; } - - /// - /// 触发器描述 - /// - public string Description { get; set; } - - /// - /// 创建时间 - /// - public DateTime CreatedAt { get; set; } - - /// - /// 最后更新时间 - /// - public DateTime UpdatedAt { get; set; } - } -} \ No newline at end of file diff --git a/DMS.Application/Events/TriggerVariableChangedEventArgs.cs b/DMS.Application/Events/TriggerVariableChangedEventArgs.cs new file mode 100644 index 0000000..c3d53ee --- /dev/null +++ b/DMS.Application/Events/TriggerVariableChangedEventArgs.cs @@ -0,0 +1,16 @@ +using DMS.Core.Enums; +using DMS.Core.Models.Triggers; + +namespace DMS.Application.Events; + +public class TriggerVariableChangedEventArgs : EventArgs +{ + public ActionChangeType ChangeType { get; } + public TriggerVariable TriggerVariable { get; } + + public TriggerVariableChangedEventArgs(ActionChangeType changeType, TriggerVariable triggerVariable) + { + ChangeType = changeType; + TriggerVariable = triggerVariable; + } +} \ No newline at end of file diff --git a/DMS.Application/Interfaces/Database/ITriggerAppService.cs b/DMS.Application/Interfaces/Database/ITriggerAppService.cs new file mode 100644 index 0000000..77296a2 --- /dev/null +++ b/DMS.Application/Interfaces/Database/ITriggerAppService.cs @@ -0,0 +1,53 @@ +using DMS.Core.Models.Triggers; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace DMS.Application.Interfaces.Database +{ + /// + /// 触发器应用服务接口,负责处理触发器相关的业务逻辑。 + /// + public interface ITriggerAppService + { + /// + /// 异步根据ID获取触发器定义。 + /// + /// 触发器ID。 + /// 触发器定义实体。 + Task GetTriggerByIdAsync(int id); + + /// + /// 异步获取所有触发器定义。 + /// + /// 触发器定义实体列表。 + Task> GetAllTriggersAsync(); + + /// + /// 异步创建一个新触发器定义及其关联的变量ID。 + /// + /// 要创建的触发器定义。 + /// 新创建的触发器定义。 + Task CreateTriggerAsync(TriggerDefinition trigger); + + /// + /// 异步更新一个已存在的触发器定义及其关联的变量ID。 + /// + /// 要更新的触发器定义。 + /// 受影响的行数。 + Task UpdateTriggerAsync(TriggerDefinition trigger); + + /// + /// 异步删除一个触发器定义及其关联的变量关系。 + /// + /// 要删除的触发器ID。 + /// 如果删除成功则为 true,否则为 false。 + Task DeleteTriggerByIdAsync(int id); + + /// + /// 异步获取指定变量ID关联的所有触发器定义。 + /// + /// 变量ID。 + /// 与指定变量关联的触发器定义实体列表。 + Task> GetTriggersByVariableIdAsync(int variableId); + } +} \ No newline at end of file diff --git a/DMS.Application/Interfaces/Database/ITriggerVariableAppService.cs b/DMS.Application/Interfaces/Database/ITriggerVariableAppService.cs new file mode 100644 index 0000000..0815ccd --- /dev/null +++ b/DMS.Application/Interfaces/Database/ITriggerVariableAppService.cs @@ -0,0 +1,43 @@ +using DMS.Core.Models.Triggers; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace DMS.Application.Interfaces.Database; + +/// +/// 定义了触发器与变量关联管理相关的应用服务操作。 +/// +public interface ITriggerVariableAppService +{ + + /// + /// 异步为触发器分配或更新一个变量关联。 + /// + /// + Task AssignTriggerVariableAsync(TriggerVariable triggerVariable); + + /// + /// 异步更新一个已存在的触发器与变量关联。 + /// + /// 要更新的触发器与变量关联对象。 + Task UpdateTriggerVariableAsync(TriggerVariable triggerVariable); + + /// + /// 异步移除一个触发器与变量关联。 + /// + /// 要移除的关联的ID。 + Task RemoveTriggerVariableAsync(int triggerVariableId); + + /// + /// 异步获取所有触发器与变量关联。 + /// + Task> GetAllAsync(); + + /// + /// 批量添加触发器与变量的关联关系 + /// + /// 触发器与变量的关联列表 + /// 异步操作任务 + Task> AddTriggerVariablesAsync(List triggerVariables); + +} \ No newline at end of file diff --git a/DMS.Application/Interfaces/IAppDataCenterService.cs b/DMS.Application/Interfaces/IAppCenterService.cs similarity index 96% rename from DMS.Application/Interfaces/IAppDataCenterService.cs rename to DMS.Application/Interfaces/IAppCenterService.cs index f8ae948..d909a55 100644 --- a/DMS.Application/Interfaces/IAppDataCenterService.cs +++ b/DMS.Application/Interfaces/IAppCenterService.cs @@ -10,7 +10,7 @@ namespace DMS.Application.Interfaces; /// /// 定义数据管理相关的应用服务操作,负责管理所有的数据,包括设备、变量表和变量。 /// -public interface IAppDataCenterService +public interface IAppCenterService { ILogManagementService LogManagementService { get; set; } IMqttManagementService MqttManagementService { get; set; } diff --git a/DMS.Application/Interfaces/IAppDataStorageService.cs b/DMS.Application/Interfaces/IAppStorageService.cs similarity index 82% rename from DMS.Application/Interfaces/IAppDataStorageService.cs rename to DMS.Application/Interfaces/IAppStorageService.cs index b255a96..2c1e9af 100644 --- a/DMS.Application/Interfaces/IAppDataStorageService.cs +++ b/DMS.Application/Interfaces/IAppStorageService.cs @@ -1,10 +1,11 @@ using System.Collections.Concurrent; using DMS.Application.DTOs; using DMS.Core.Models; +using DMS.Core.Models.Triggers; namespace DMS.Application.Interfaces; -public interface IAppDataStorageService +public interface IAppStorageService { /// /// 安全字典,用于存储所有设备数据 @@ -48,5 +49,10 @@ public interface IAppDataStorageService /// /// 安全字典,用于存储所有触发器定义数据 /// - ConcurrentDictionary Triggers { get; } + ConcurrentDictionary Triggers { get; } + + /// + /// 安全字典,用于存储所有触发器与变量关联数据 + /// + ConcurrentDictionary TriggerVariables { get; } } \ No newline at end of file diff --git a/DMS.Application/Interfaces/IEventService.cs b/DMS.Application/Interfaces/IEventService.cs index 8799036..a2eeba2 100644 --- a/DMS.Application/Interfaces/IEventService.cs +++ b/DMS.Application/Interfaces/IEventService.cs @@ -148,4 +148,20 @@ public interface IEventService void RaiseMenuChanged(object sender, MenuChangedEventArgs e); #endregion + + #region 触发器变量事件 + + /// + /// 触发器与变量关联改变事件 + /// + event EventHandler OnTriggerVariableChanged; + + /// + /// 触发触发器与变量关联改变事件 + /// + /// 事件发送者 + /// 触发器与变量关联改变事件参数 + void RaiseTriggerVariableChanged(object sender, TriggerVariableChangedEventArgs e); + + #endregion } \ No newline at end of file diff --git a/DMS.Application/Interfaces/Management/ITriggerManagementService.cs b/DMS.Application/Interfaces/Management/ITriggerManagementService.cs index 7535cba..57dd286 100644 --- a/DMS.Application/Interfaces/Management/ITriggerManagementService.cs +++ b/DMS.Application/Interfaces/Management/ITriggerManagementService.cs @@ -1,4 +1,5 @@ using DMS.Application.DTOs; +using DMS.Core.Models.Triggers; namespace DMS.Application.Interfaces.Management { @@ -11,21 +12,21 @@ namespace DMS.Application.Interfaces.Management /// 获取所有触发器定义 /// /// 触发器定义列表 - Task> GetAllTriggersAsync(); + List GetAllTriggersAsync(); /// /// 根据 ID 获取触发器定义 /// /// 触发器 ID /// 触发器定义 DTO,如果未找到则返回 null - Task GetTriggerByIdAsync(int id); + Task GetTriggerByIdAsync(int id); /// /// 创建一个新的触发器定义 /// /// 要创建的触发器定义 DTO /// 创建成功的触发器定义 DTO - Task CreateTriggerAsync(TriggerDefinitionDto triggerDto); + Task CreateTriggerAsync(TriggerDefinition triggerDto); /// /// 更新一个已存在的触发器定义 @@ -33,7 +34,7 @@ namespace DMS.Application.Interfaces.Management /// 要更新的触发器 ID /// 包含更新信息的触发器定义 DTO /// 更新后的触发器定义 DTO,如果未找到则返回 null - Task UpdateTriggerAsync(int id, TriggerDefinitionDto triggerDto); + Task UpdateTriggerAsync(int id, TriggerDefinition triggerDto); /// /// 删除一个触发器定义 @@ -47,6 +48,6 @@ namespace DMS.Application.Interfaces.Management /// /// 变量 ID /// 该变量关联的触发器定义列表 - Task> GetTriggersForVariableAsync(int variableId); + Task> GetTriggersForVariableAsync(int variableId); } } \ No newline at end of file diff --git a/DMS.Application/Interfaces/Management/ITriggerVariableManagementService.cs b/DMS.Application/Interfaces/Management/ITriggerVariableManagementService.cs new file mode 100644 index 0000000..aac004f --- /dev/null +++ b/DMS.Application/Interfaces/Management/ITriggerVariableManagementService.cs @@ -0,0 +1,41 @@ +using DMS.Core.Models.Triggers; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace DMS.Application.Interfaces.Management; + +public interface ITriggerVariableManagementService +{ + Task AssignTriggerVariableAsync(TriggerVariable triggerVariable); + Task UpdateAsync(TriggerVariable triggerVariable); + Task DeleteAsync(int id); + Task> LoadAllTriggerVariablesAsync(); + + // /// + // /// 根据触发器ID获取关联的变量ID列表 + // /// + // /// 触发器ID + // /// 变量ID列表 + // Task> GetVariableIdsByTriggerIdAsync(int triggerId); + // + // /// + // /// 根据变量ID获取关联的触发器ID列表 + // /// + // /// 变量ID + // /// 触发器ID列表 + // Task> GetTriggerIdsByVariableIdAsync(int variableId); + + /// + /// 批量添加触发器与变量的关联关系 + /// + /// 触发器与变量的关联列表 + /// 异步操作任务 + Task> AddTriggerVariablesAsync(List triggerVariables); + + /// + /// 根据触发器ID删除关联关系 + /// + /// 触发器ID + /// 异步操作任务 + Task DeleteByTriggerIdAsync(int triggerId); +} \ No newline at end of file diff --git a/DMS.Application/Profiles/MappingProfile.cs b/DMS.Application/Profiles/MappingProfile.cs index 243a437..a0b966c 100644 --- a/DMS.Application/Profiles/MappingProfile.cs +++ b/DMS.Application/Profiles/MappingProfile.cs @@ -6,7 +6,7 @@ using DMS.Core.Models.Triggers; namespace DMS.Application.Profiles; /// -/// 配置AutoMapper的映射规则?/// +/// 配置AutoMapper的映射规则�?/// public class MappingProfile : Profile { public MappingProfile() @@ -39,9 +39,5 @@ public class MappingProfile : Profile CreateMap().ReverseMap(); CreateMap().ReverseMap(); - CreateMap() - .ForMember(dest => dest.VariableIds, opt => opt.MapFrom(src => src.VariableIds)) - .ReverseMap() - .ForMember(dest => dest.VariableIds, opt => opt.MapFrom(src => src.VariableIds)); } } diff --git a/DMS.Application/Services/AppDataCenterService.cs b/DMS.Application/Services/AppCenterService.cs similarity index 96% rename from DMS.Application/Services/AppDataCenterService.cs rename to DMS.Application/Services/AppCenterService.cs index 4ac2b60..73f5820 100644 --- a/DMS.Application/Services/AppDataCenterService.cs +++ b/DMS.Application/Services/AppCenterService.cs @@ -19,9 +19,9 @@ namespace DMS.Application.Services; /// /// 数据中心服务,负责管理所有的数据,包括设备、变量表、变量、菜单和日志。 -/// 实现 接口。 +/// 实现 接口。 /// -public class AppDataCenterService : IAppDataCenterService +public class AppCenterService : IAppCenterService { private readonly IMapper _mapper; private readonly IRepositoryManager _repositoryManager; @@ -69,7 +69,7 @@ public class AppDataCenterService : IAppDataCenterService #endregion - public AppDataCenterService( + public AppCenterService( IRepositoryManager repositoryManager, IMapper mapper, IDataLoaderService dataLoaderService, diff --git a/DMS.Application/Services/AppDataStorageService.cs b/DMS.Application/Services/AppStorageService.cs similarity index 83% rename from DMS.Application/Services/AppDataStorageService.cs rename to DMS.Application/Services/AppStorageService.cs index 589dda4..0164e41 100644 --- a/DMS.Application/Services/AppDataStorageService.cs +++ b/DMS.Application/Services/AppStorageService.cs @@ -2,10 +2,11 @@ using System.Collections.Concurrent; using DMS.Application.DTOs; using DMS.Application.Interfaces; using DMS.Core.Models; +using DMS.Core.Models.Triggers; namespace DMS.Application.Services; -public class AppDataStorageService : IAppDataStorageService +public class AppStorageService : IAppStorageService { /// /// 安全字典,用于存储所有设备数据 @@ -57,5 +58,10 @@ public class AppDataStorageService : IAppDataStorageService /// /// 安全字典,用于存储所有触发器定义数据 /// - public ConcurrentDictionary Triggers { get; } = new(); + public ConcurrentDictionary Triggers { get; } = new(); + + /// + /// 安全字典,用于存储所有触发器与变量关联数据 + /// + public ConcurrentDictionary TriggerVariables { get; } = new(); } \ No newline at end of file diff --git a/DMS.Application/Services/DataLoaderService.cs b/DMS.Application/Services/DataLoaderService.cs index 8b3eb2d..50b81c9 100644 --- a/DMS.Application/Services/DataLoaderService.cs +++ b/DMS.Application/Services/DataLoaderService.cs @@ -19,7 +19,7 @@ public class DataLoaderService : IDataLoaderService { private readonly IRepositoryManager _repositoryManager; private readonly IMapper _mapper; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IDeviceAppService _deviceAppService; private readonly IVariableTableAppService _variableTableAppService; private readonly IVariableAppService _variableAppService; @@ -36,7 +36,7 @@ public class DataLoaderService : IDataLoaderService public DataLoaderService( IRepositoryManager repositoryManager, IMapper mapper, - IAppDataStorageService appDataStorageService, + IAppStorageService appStorageService, IDeviceAppService deviceAppService, IVariableTableAppService variableTableAppService, IVariableAppService variableAppService, @@ -49,7 +49,7 @@ public class DataLoaderService : IDataLoaderService { _repositoryManager = repositoryManager; _mapper = mapper; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _deviceAppService = deviceAppService; _variableTableAppService = variableTableAppService; _variableAppService = variableAppService; @@ -96,12 +96,12 @@ public class DataLoaderService : IDataLoaderService /// public async Task LoadAllTriggersAsync() { - _appDataStorageService.Triggers.Clear(); - var triggers = await _triggerManagementService.GetAllTriggersAsync(); + _appStorageService.Triggers.Clear(); + var triggers = _triggerManagementService.GetAllTriggersAsync(); // 加载触发器数据到内存 foreach (var trigger in triggers) { - _appDataStorageService.Triggers.TryAdd(trigger.Id, trigger); + _appStorageService.Triggers.TryAdd(trigger.Id, trigger); } } @@ -112,7 +112,7 @@ public class DataLoaderService : IDataLoaderService /// public async Task LoadAllDevicesAsync() { - _appDataStorageService.Devices.Clear(); + _appStorageService.Devices.Clear(); var devices = await _repositoryManager.Devices.GetAllAsync(); var devicesDtos = _mapper.Map>(devices); @@ -120,7 +120,7 @@ public class DataLoaderService : IDataLoaderService foreach (var deviceDto in devicesDtos) { // 将设备添加到安全字典 - _appDataStorageService.Devices.TryAdd(deviceDto.Id, deviceDto); + _appStorageService.Devices.TryAdd(deviceDto.Id, deviceDto); } } @@ -129,20 +129,20 @@ public class DataLoaderService : IDataLoaderService /// public async Task LoadAllVariableTablesAsync() { - _appDataStorageService.VariableTables.Clear(); + _appStorageService.VariableTables.Clear(); var variableTables = await _repositoryManager.VariableTables.GetAllAsync(); var variableTableDtos = _mapper.Map>(variableTables); // 建立变量表与变量的关联 foreach (var variableTableDto in variableTableDtos) { - if (_appDataStorageService.Devices.TryGetValue(variableTableDto.DeviceId, out var deviceDto)) + if (_appStorageService.Devices.TryGetValue(variableTableDto.DeviceId, out var deviceDto)) { variableTableDto.Device = deviceDto; variableTableDto.Device.VariableTables.Add(variableTableDto); } // 将变量表添加到安全字典 - _appDataStorageService.VariableTables.TryAdd(variableTableDto.Id, variableTableDto); + _appStorageService.VariableTables.TryAdd(variableTableDto.Id, variableTableDto); } } @@ -151,21 +151,21 @@ public class DataLoaderService : IDataLoaderService /// public async Task LoadAllVariablesAsync() { - _appDataStorageService.Variables.Clear(); + _appStorageService.Variables.Clear(); var variables = await _repositoryManager.Variables.GetAllAsync(); var variableDtos = _mapper.Map>(variables); // 将变量添加到安全字典 foreach (var variableDto in variableDtos) { - if (_appDataStorageService.VariableTables.TryGetValue(variableDto.VariableTableId, + if (_appStorageService.VariableTables.TryGetValue(variableDto.VariableTableId, out var variableTableDto)) { variableDto.VariableTable = variableTableDto; variableDto.VariableTable.Variables.Add(variableDto); } - _appDataStorageService.Variables.TryAdd(variableDto.Id, variableDto); + _appStorageService.Variables.TryAdd(variableDto.Id, variableDto); } } @@ -174,13 +174,13 @@ public class DataLoaderService : IDataLoaderService /// public async Task LoadAllMenusAsync() { - _appDataStorageService.Menus.Clear(); - _appDataStorageService.MenuTrees.Clear(); + _appStorageService.Menus.Clear(); + _appStorageService.MenuTrees.Clear(); var menus = await _repositoryManager.Menus.GetAllAsync(); // 将菜单添加到安全字典 foreach (var menuBean in menus) { - _appDataStorageService.Menus.TryAdd(menuBean.Id, menuBean); + _appStorageService.Menus.TryAdd(menuBean.Id, menuBean); } } @@ -190,12 +190,12 @@ public class DataLoaderService : IDataLoaderService /// public async Task LoadAllMqttServersAsync() { - _appDataStorageService.MqttServers.Clear(); + _appStorageService.MqttServers.Clear(); var mqttServers =await _mqttAppService.GetAllMqttServersAsync(); // 加载MQTT服务器数据到内存 foreach (var mqttServer in mqttServers) { - _appDataStorageService.MqttServers.TryAdd(mqttServer.Id, mqttServer); + _appStorageService.MqttServers.TryAdd(mqttServer.Id, mqttServer); } } @@ -204,12 +204,12 @@ public class DataLoaderService : IDataLoaderService /// public async Task LoadAllNlogsAsync(int count) { - _appDataStorageService.Nlogs.Clear(); + _appStorageService.Nlogs.Clear(); var nlogDtos =await _nlogAppService.GetLatestLogsAsync(count); // 加载日志数据到内存 foreach (var nlogDto in nlogDtos) { - _appDataStorageService.Nlogs.TryAdd(nlogDto.Id, nlogDto); + _appStorageService.Nlogs.TryAdd(nlogDto.Id, nlogDto); } } diff --git a/DMS.Application/Services/Database/MqttAliasAppService.cs b/DMS.Application/Services/Database/MqttAliasAppService.cs index 4cb8c2a..a02e3cc 100644 --- a/DMS.Application/Services/Database/MqttAliasAppService.cs +++ b/DMS.Application/Services/Database/MqttAliasAppService.cs @@ -12,16 +12,16 @@ namespace DMS.Application.Services.Database; public class MqttAliasAppService : IMqttAliasAppService { private readonly IRepositoryManager _repoManager; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IMapper _mapper; /// /// 构造函数。 /// - public MqttAliasAppService(IRepositoryManager repoManager,IAppDataStorageService appDataStorageService, IMapper mapper) + public MqttAliasAppService(IRepositoryManager repoManager,IAppStorageService appStorageService, IMapper mapper) { _repoManager = repoManager; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _mapper = mapper; } diff --git a/DMS.Application/Services/Database/TriggerAppService.cs b/DMS.Application/Services/Database/TriggerAppService.cs new file mode 100644 index 0000000..2ebe138 --- /dev/null +++ b/DMS.Application/Services/Database/TriggerAppService.cs @@ -0,0 +1,201 @@ +using AutoMapper; +using DMS.Application.Interfaces.Database; +using DMS.Core.Interfaces; +using DMS.Core.Models.Triggers; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Linq; +using System.Diagnostics; +using DMS.Application.Interfaces; + +namespace DMS.Application.Services.Database +{ + /// + /// 触发器应用服务,负责处理触发器相关的业务逻辑。 + /// 实现 接口。 + /// + public class TriggerAppService : ITriggerAppService + { + private readonly IRepositoryManager _repositoryManager; + + /// + /// 构造函数,通过依赖注入获取仓储管理器和AutoMapper实例。 + /// + /// 仓储管理器实例。 + /// AutoMapper 实例。 + public TriggerAppService(IRepositoryManager repositoryManager) + { + _repositoryManager = repositoryManager; + } + + /// + /// 异步根据ID获取触发器定义。 + /// + /// 触发器ID。 + /// 触发器定义实体。 + public async Task GetTriggerByIdAsync(int id) + { + var dbTrigger = await _repositoryManager.Triggers.GetByIdAsync(id); + return dbTrigger; + } + + /// + /// 异步获取所有触发器定义。 + /// + /// 触发器定义实体列表。 + public async Task> GetAllTriggersAsync() + { + var triggers = await _repositoryManager.Triggers.GetAllAsync(); + var triggerVariables = await _repositoryManager.TriggerVariables.GetAllAsync(); + foreach (var trigger in triggers) + { + // 加载关联的变量ID + var variables = triggerVariables.Where(t=>t.TriggerDefinitionId==trigger.Id).ToList(); + // trigger.Variables = variables; + } + + return triggers; + } + + /// + /// 异步创建一个新触发器定义及其关联的变量ID。 + /// + /// 要创建的触发器定义。 + /// 新创建的触发器定义。 + public async Task CreateTriggerAsync(TriggerDefinition trigger) + { + try + { + await _repositoryManager.BeginTranAsync(); + + // 添加触发器定义 + var addedTrigger = await _repositoryManager.Triggers.AddAsync(trigger); + + // // 添加关联的变量ID + // if (trigger.Variables != null && trigger.Variables.Any()) + // { + // var triggerVariables = trigger.Variables.Select(variableId => new DbTriggerVariable + // { + // TriggerDefinitionId = addedTrigger.Id, + // VariableId = variableId + // }) + // .ToList(); + // + // await _repositoryManager.AddTriggerVariablesAsync(triggerVariables); + // } + + await _repositoryManager.CommitAsync(); + return addedTrigger; + } + catch + { + await _repositoryManager.RollbackAsync(); + throw; + } + } + + /// + /// 异步更新一个已存在的触发器定义及其关联的变量ID。 + /// + /// 要更新的触发器定义。 + /// 受影响的行数。 + public async Task UpdateTriggerAsync(TriggerDefinition trigger) + { + try + { + await _repositoryManager.BeginTranAsync(); + + // 更新触发器定义 + var rowsAffected = await _repositoryManager.Triggers.UpdateAsync(trigger); + + // if (rowsAffected > 0) + // { + // // 删除旧的关联关系 + // await _repositoryManager.DeleteTriggerVariablesByTriggerIdAsync(trigger.Id); + // + // // 插入新的关联关系 + // if (trigger.Variables != null && trigger.Variables.Any()) + // { + // var triggerVariables = trigger.Variables.Select(variableId => new DbTriggerVariable + // { + // TriggerDefinitionId = trigger.Id, + // VariableId = variableId + // }) + // .ToList(); + // + // await _repositoryManager.AddTriggerVariablesAsync(triggerVariables); + // } + // } + + await _repositoryManager.CommitAsync(); + return rowsAffected; + } + catch + { + await _repositoryManager.RollbackAsync(); + throw; + } + } + + /// + /// 异步删除一个触发器定义及其关联的变量关系。 + /// + /// 要删除的触发器ID。 + /// 如果删除成功则为 true,否则为 false。 + public async Task DeleteTriggerByIdAsync(int id) + { + try + { + await _repositoryManager.BeginTranAsync(); + + // // 删除关联的变量关系 + // await _repositoryManager.DeleteTriggerVariablesByTriggerIdAsync(id); + + // 删除触发器本身 + var rowsAffected = await _repositoryManager.Triggers.DeleteByIdAsync(id); + + await _repositoryManager.CommitAsync(); + return rowsAffected > 0; + } + catch + { + await _repositoryManager.RollbackAsync(); + throw; + } + } + + /// + /// 异步获取指定变量ID关联的所有触发器定义。 + /// + /// 变量ID。 + /// 与指定变量关联的触发器定义实体列表。 + public async Task> GetTriggersByVariableIdAsync(int variableId) + { + var stopwatch = new Stopwatch(); + stopwatch.Start(); + // + // // 获取关联的触发器ID列表 + // var triggerIds = await _repositoryManager.GetTriggerIdsByVariableIdAsync(variableId); + + // var triggers = new List(); + // if (triggerIds.Any()) + // { + // // 获取所有关联的触发器 + // foreach (var triggerId in triggerIds) + // { + // var trigger = await GetTriggerByIdAsync(triggerId); + // if (trigger != null) + // { + // triggers.Add(trigger); + // } + // } + // } + + stopwatch.Stop(); + // 可选:记录日志 + // _logger.LogInformation($"GetTriggersByVariableId for VariableId={variableId},耗时:{stopwatch.ElapsedMilliseconds}ms"); + + return null; + } + } +} \ No newline at end of file diff --git a/DMS.Application/Services/Database/TriggerVariableAppService.cs b/DMS.Application/Services/Database/TriggerVariableAppService.cs new file mode 100644 index 0000000..8dc4075 --- /dev/null +++ b/DMS.Application/Services/Database/TriggerVariableAppService.cs @@ -0,0 +1,66 @@ +using AutoMapper; +using DMS.Application.Interfaces; +using DMS.Application.Interfaces.Database; +using DMS.Core.Interfaces; +using DMS.Core.Models.Triggers; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace DMS.Application.Services.Database; + +/// +/// ITriggerVariableAppService 的实现,负责管理触发器与变量的关联关系。 +/// +public class TriggerVariableAppService : ITriggerVariableAppService +{ + private readonly IRepositoryManager _repositoryManager; + + /// + /// 构造函数。 + /// + public TriggerVariableAppService(IRepositoryManager repositoryManager) + { + _repositoryManager = repositoryManager; + } + + /// + /// 异步为触发器分配或更新一个变量关联。 + /// + public async Task AssignTriggerVariableAsync(TriggerVariable triggerVariable) + { + return await _repositoryManager.TriggerVariables.AddAsync(triggerVariable); + } + + /// + /// 异步更新一个已存在的触发器与变量关联。 + /// + public async Task UpdateTriggerVariableAsync(TriggerVariable triggerVariable) + { + return await _repositoryManager.TriggerVariables.UpdateAsync(triggerVariable); + } + + /// + /// 异步移除一个触发器与变量关联。 + /// + public async Task RemoveTriggerVariableAsync(int triggerVariableId) + { + return await _repositoryManager.TriggerVariables.DeleteByIdAsync(triggerVariableId); + } + + public async Task> GetAllAsync() + { + var triggerVariables = await _repositoryManager.TriggerVariables.GetAllAsync(); + + return triggerVariables; + } + + + /// + /// 批量添加触发器与变量的关联关系 + /// + public async Task> AddTriggerVariablesAsync(List triggerVariables) + { + return await _repositoryManager.TriggerVariables.AddBatchAsync(triggerVariables); + } + +} \ No newline at end of file diff --git a/DMS.Application/Services/EventService.cs b/DMS.Application/Services/EventService.cs index 3b7f56d..3d7a544 100644 --- a/DMS.Application/Services/EventService.cs +++ b/DMS.Application/Services/EventService.cs @@ -9,11 +9,11 @@ namespace DMS.Application.Services; /// public class EventService : IEventService { - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; - public EventService(IAppDataStorageService appDataStorageService) + public EventService(IAppStorageService appStorageService) { - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; } #region 设备事件 @@ -188,4 +188,23 @@ public class EventService : IEventService } #endregion + + #region 触发器变量事件 + + /// + /// 触发器与变量关联改变事件 + /// + public event EventHandler OnTriggerVariableChanged; + + /// + /// 触发触发器与变量关联改变事件 + /// + /// 事件发送者 + /// 触发器与变量关联改变事件参数 + public void RaiseTriggerVariableChanged(object sender, TriggerVariableChangedEventArgs e) + { + OnTriggerVariableChanged?.Invoke(sender, e); + } + + #endregion } \ No newline at end of file diff --git a/DMS.Application/Services/Management/DeviceManagementService.cs b/DMS.Application/Services/Management/DeviceManagementService.cs index 6576be1..0f96621 100644 --- a/DMS.Application/Services/Management/DeviceManagementService.cs +++ b/DMS.Application/Services/Management/DeviceManagementService.cs @@ -14,13 +14,13 @@ namespace DMS.Application.Services.Management; public class DeviceManagementService : IDeviceManagementService { private readonly IDeviceAppService _deviceAppService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IEventService _eventService; - public DeviceManagementService(IDeviceAppService deviceAppService, IAppDataStorageService appDataStorageService, IEventService eventService) + public DeviceManagementService(IDeviceAppService deviceAppService, IAppStorageService appStorageService, IEventService eventService) { _deviceAppService = deviceAppService; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _eventService = eventService; } @@ -50,11 +50,11 @@ public class DeviceManagementService : IDeviceManagementService // 创建成功后,将设备添加到内存中 if (result?.Device != null) { - if (_appDataStorageService.Devices.TryAdd(result.Device.Id, result.Device)) + if (_appStorageService.Devices.TryAdd(result.Device.Id, result.Device)) { _eventService.RaiseDeviceChanged(this, new DeviceChangedEventArgs(DataChangeType.Added, result.Device)); } - if (_appDataStorageService.VariableTables.TryAdd(result.VariableTable.Id, result.VariableTable)) + if (_appStorageService.VariableTables.TryAdd(result.VariableTable.Id, result.VariableTable)) { _eventService.RaiseVariableTableChanged(this, new VariableTableChangedEventArgs(DataChangeType.Added, result.VariableTable)); } @@ -73,7 +73,7 @@ public class DeviceManagementService : IDeviceManagementService // 更新成功后,更新内存中的设备 if (result > 0 && device != null) { - _appDataStorageService.Devices.AddOrUpdate(device.Id, device, (key, oldValue) => device); + _appStorageService.Devices.AddOrUpdate(device.Id, device, (key, oldValue) => device); _eventService.RaiseDeviceChanged(this, new DeviceChangedEventArgs(DataChangeType.Updated, device)); } @@ -91,19 +91,19 @@ public class DeviceManagementService : IDeviceManagementService // 删除成功后,从内存中移除设备 if (result && device != null) { - if (_appDataStorageService.Devices.TryGetValue(deviceId, out var deviceInStorage)) + if (_appStorageService.Devices.TryGetValue(deviceId, out var deviceInStorage)) { foreach (var variableTable in deviceInStorage.VariableTables) { foreach (var variable in variableTable.Variables) { - _appDataStorageService.Variables.TryRemove(variable.Id, out _); + _appStorageService.Variables.TryRemove(variable.Id, out _); } - _appDataStorageService.VariableTables.TryRemove(variableTable.Id, out _); + _appStorageService.VariableTables.TryRemove(variableTable.Id, out _); } - _appDataStorageService.Devices.TryRemove(deviceId, out _); + _appStorageService.Devices.TryRemove(deviceId, out _); _eventService.RaiseDeviceChanged(this, new DeviceChangedEventArgs(DataChangeType.Deleted, deviceInStorage)); } @@ -123,7 +123,7 @@ public class DeviceManagementService : IDeviceManagementService var device = await _deviceAppService.GetDeviceByIdAsync(id); if (device != null) { - _appDataStorageService.Devices.AddOrUpdate(device.Id, device, (key, oldValue) => device); + _appStorageService.Devices.AddOrUpdate(device.Id, device, (key, oldValue) => device); _eventService.RaiseDeviceChanged(this, new DeviceChangedEventArgs(DataChangeType.Updated, device)); } } diff --git a/DMS.Application/Services/Management/LogManagementService.cs b/DMS.Application/Services/Management/LogManagementService.cs index 9c88c8c..9e7fc28 100644 --- a/DMS.Application/Services/Management/LogManagementService.cs +++ b/DMS.Application/Services/Management/LogManagementService.cs @@ -13,17 +13,17 @@ namespace DMS.Application.Services.Management; public class LogManagementService : ILogManagementService { private readonly INlogAppService _nlogAppService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; /// /// 当日志数据发生变化时触发 /// public event EventHandler OnLogChanged; - public LogManagementService(INlogAppService nlogAppService,IAppDataStorageService appDataStorageService) + public LogManagementService(INlogAppService nlogAppService,IAppStorageService appStorageService) { _nlogAppService = nlogAppService; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; } /// @@ -63,7 +63,7 @@ public class LogManagementService : ILogManagementService /// public void AddNlogToMemory(NlogDto nlogDto) { - if (_appDataStorageService.Nlogs.TryAdd(nlogDto.Id, nlogDto)) + if (_appStorageService.Nlogs.TryAdd(nlogDto.Id, nlogDto)) { OnLogChanged?.Invoke(this,new NlogChangedEventArgs(DataChangeType.Added, nlogDto)); } @@ -74,7 +74,7 @@ public class LogManagementService : ILogManagementService /// public void UpdateNlogInMemory(NlogDto nlogDto) { - _appDataStorageService.Nlogs.AddOrUpdate(nlogDto.Id, nlogDto, (key, oldValue) => nlogDto); + _appStorageService.Nlogs.AddOrUpdate(nlogDto.Id, nlogDto, (key, oldValue) => nlogDto); OnLogChanged?.Invoke(this,new NlogChangedEventArgs(DataChangeType.Updated, nlogDto)); } @@ -83,7 +83,7 @@ public class LogManagementService : ILogManagementService /// public void RemoveNlogFromMemory(int nlogId) { - if (_appDataStorageService.Nlogs.TryRemove(nlogId, out var nlogDto)) + if (_appStorageService.Nlogs.TryRemove(nlogId, out var nlogDto)) { OnLogChanged?.Invoke(this,new NlogChangedEventArgs(DataChangeType.Deleted, nlogDto)); } diff --git a/DMS.Application/Services/Management/MenuManagementService.cs b/DMS.Application/Services/Management/MenuManagementService.cs index c14a691..09355af 100644 --- a/DMS.Application/Services/Management/MenuManagementService.cs +++ b/DMS.Application/Services/Management/MenuManagementService.cs @@ -12,7 +12,7 @@ namespace DMS.Application.Services.Management; public class MenuManagementService : IMenuManagementService { private readonly IMenuAppService _menuService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IEventService _eventService; /// @@ -20,10 +20,10 @@ public class MenuManagementService : IMenuManagementService /// public event EventHandler MenuChanged; - public MenuManagementService(IMenuAppService menuService, IAppDataStorageService appDataStorageService, IEventService eventService) + public MenuManagementService(IMenuAppService menuService, IAppStorageService appStorageService, IEventService eventService) { _menuService = menuService; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _eventService = eventService; } @@ -54,10 +54,10 @@ public class MenuManagementService : IMenuManagementService if (result > 0) { menu.Id = result; // 假设返回的ID是新创建的 - if (_appDataStorageService.Menus.TryAdd(menu.Id, menu)) + if (_appStorageService.Menus.TryAdd(menu.Id, menu)) { MenuBean parentMenu = null; - if (menu.ParentId > 0 && _appDataStorageService.Menus.TryGetValue(menu.ParentId.Value, out var parent)) + if (menu.ParentId > 0 && _appStorageService.Menus.TryGetValue(menu.ParentId.Value, out var parent)) { parentMenu = parent; parent.Children.Add(menu); @@ -80,7 +80,7 @@ public class MenuManagementService : IMenuManagementService // 更新成功后,更新内存中的菜单 if (result > 0 && menu != null) { - _appDataStorageService.Menus.AddOrUpdate(menu.Id, menu, (key, oldValue) => menu); + _appStorageService.Menus.AddOrUpdate(menu.Id, menu, (key, oldValue) => menu); _eventService.RaiseMenuChanged(this, new MenuChangedEventArgs(DataChangeType.Updated, menu)); @@ -100,10 +100,10 @@ public class MenuManagementService : IMenuManagementService // 删除成功后,从内存中移除菜单 if (result && menu != null) { - if (_appDataStorageService.Menus.TryRemove(id, out var menuData)) + if (_appStorageService.Menus.TryRemove(id, out var menuData)) { // 从父菜单中移除子菜单 - if (menuData.ParentId > 0 && _appDataStorageService.Menus.TryGetValue(menuData.ParentId.Value, out var parentMenu)) + if (menuData.ParentId > 0 && _appStorageService.Menus.TryGetValue(menuData.ParentId.Value, out var parentMenu)) { parentMenu.Children.Remove(menuData); } @@ -120,7 +120,7 @@ public class MenuManagementService : IMenuManagementService /// public List GetRootMenus() { - return _appDataStorageService.Menus.Values.Where(m => m.ParentId == 0) + return _appStorageService.Menus.Values.Where(m => m.ParentId == 0) .ToList(); } @@ -131,7 +131,7 @@ public class MenuManagementService : IMenuManagementService /// 子菜单列表 public List GetChildMenus(int parentId) { - return _appDataStorageService.Menus.Values.Where(m => m.ParentId == parentId) + return _appStorageService.Menus.Values.Where(m => m.ParentId == parentId) .ToList(); } @@ -141,7 +141,7 @@ public class MenuManagementService : IMenuManagementService public void BuildMenuTree() { // 清空现有菜单树 - _appDataStorageService.MenuTrees.Clear(); + _appStorageService.MenuTrees.Clear(); // 获取所有根菜单 var rootMenus = GetRootMenus(); @@ -149,7 +149,7 @@ public class MenuManagementService : IMenuManagementService // 将根菜单添加到菜单树中 foreach (var rootMenu in rootMenus) { - _appDataStorageService.MenuTrees.TryAdd(rootMenu.Id, rootMenu); + _appStorageService.MenuTrees.TryAdd(rootMenu.Id, rootMenu); } } diff --git a/DMS.Application/Services/Management/MqttAliasManagementService.cs b/DMS.Application/Services/Management/MqttAliasManagementService.cs index c39616a..94c4225 100644 --- a/DMS.Application/Services/Management/MqttAliasManagementService.cs +++ b/DMS.Application/Services/Management/MqttAliasManagementService.cs @@ -12,11 +12,11 @@ public class MqttAliasManagementService : IMqttAliasManagementService { private readonly IMqttAliasAppService _appService; private readonly IEventService _eventService; - private readonly IAppDataStorageService _storageService; + private readonly IAppStorageService _storageService; private readonly IMapper _mapper; public MqttAliasManagementService(IMqttAliasAppService appService, IEventService eventService, - IAppDataStorageService storageService, IMapper mapper) + IAppStorageService storageService, IMapper mapper) { _appService = appService; _eventService = eventService; diff --git a/DMS.Application/Services/Management/MqttManagementService.cs b/DMS.Application/Services/Management/MqttManagementService.cs index 027eb2f..36ce157 100644 --- a/DMS.Application/Services/Management/MqttManagementService.cs +++ b/DMS.Application/Services/Management/MqttManagementService.cs @@ -15,15 +15,15 @@ namespace DMS.Application.Services.Management; public class MqttManagementService : IMqttManagementService { private readonly IMqttAppService _mqttAppService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IEventService _eventService; public MqttManagementService(IMqttAppService mqttAppService, - IAppDataStorageService appDataStorageService, + IAppStorageService appStorageService, IEventService eventService) { _mqttAppService = mqttAppService; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _eventService = eventService; } @@ -32,7 +32,7 @@ public class MqttManagementService : IMqttManagementService /// public async Task GetMqttServerByIdAsync(int id) { - if (_appDataStorageService.MqttServers.TryGetValue(id,out var mqttServer)) + if (_appStorageService.MqttServers.TryGetValue(id,out var mqttServer)) { return mqttServer; } @@ -44,7 +44,7 @@ public class MqttManagementService : IMqttManagementService /// public async Task> GetAllMqttServersAsync() { - return _appDataStorageService.MqttServers.Values.ToList(); + return _appStorageService.MqttServers.Values.ToList(); } /// @@ -67,7 +67,7 @@ public class MqttManagementService : IMqttManagementService { foreach (var mqttServer in mqttServers) { - if (_appDataStorageService.MqttServers.TryGetValue(mqttServer.Id, out var mMqttServer)) + if (_appStorageService.MqttServers.TryGetValue(mqttServer.Id, out var mMqttServer)) { // 比较旧值和新值,确定哪个属性发生了变化 var changedProperties = GetChangedProperties(mMqttServer, mqttServer); @@ -99,7 +99,7 @@ public class MqttManagementService : IMqttManagementService else { // 如果内存中不存在该MQTT服务器,则直接添加 - _appDataStorageService.MqttServers.TryAdd(mqttServer.Id, mqttServer); + _appStorageService.MqttServers.TryAdd(mqttServer.Id, mqttServer); _eventService.RaiseMqttServerChanged( this, new MqttServerChangedEventArgs(ActionChangeType.Added, mqttServer, MqttServerPropertyType.All)); } @@ -120,7 +120,7 @@ public class MqttManagementService : IMqttManagementService // 删除成功后,从内存中移除MQTT服务器 if (result && mqttServer != null) { - if (_appDataStorageService.MqttServers.TryRemove(id, out var mqttServerFromCache)) + if (_appStorageService.MqttServers.TryRemove(id, out var mqttServerFromCache)) { _eventService.RaiseMqttServerChanged( this, new MqttServerChangedEventArgs(ActionChangeType.Deleted, mqttServerFromCache)); @@ -142,7 +142,7 @@ public class MqttManagementService : IMqttManagementService { foreach (var id in ids) { - if (_appDataStorageService.MqttServers.TryRemove(id, out var mqttServer)) + if (_appStorageService.MqttServers.TryRemove(id, out var mqttServer)) { _eventService.RaiseMqttServerChanged( this, new MqttServerChangedEventArgs(ActionChangeType.Deleted, mqttServer)); @@ -167,7 +167,7 @@ public class MqttManagementService : IMqttManagementService // 将MQTT服务器添加到内存中 - if (_appDataStorageService.MqttServers.TryAdd(mqttServer.Id, mqttServer)) + if (_appStorageService.MqttServers.TryAdd(mqttServer.Id, mqttServer)) { _eventService.RaiseMqttServerChanged( this, new MqttServerChangedEventArgs(ActionChangeType.Added, mqttServer)); diff --git a/DMS.Application/Services/Management/TriggerManagementService.cs b/DMS.Application/Services/Management/TriggerManagementService.cs index fbe1b2f..c3c0956 100644 --- a/DMS.Application/Services/Management/TriggerManagementService.cs +++ b/DMS.Application/Services/Management/TriggerManagementService.cs @@ -13,39 +13,39 @@ namespace DMS.Application.Services.Management /// public class TriggerManagementService : ITriggerManagementService { + private readonly IAppStorageService _appStorageService; private readonly IRepositoryManager _repositoryManager; private readonly IMapper _mapper; - private readonly IAppDataStorageService _appDataStorageService; - public TriggerManagementService(IRepositoryManager repositoryManager, IMapper mapper, IAppDataStorageService appDataStorageService) + public TriggerManagementService(IAppStorageService appStorageService,IRepositoryManager repositoryManager, IMapper mapper) { - _repositoryManager = repositoryManager ?? throw new ArgumentNullException(nameof(repositoryManager)); + _appStorageService = appStorageService; + _repositoryManager = repositoryManager; _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); - _appDataStorageService = appDataStorageService ?? throw new ArgumentNullException(nameof(appDataStorageService)); } /// /// 获取所有触发器定义 /// - public async Task> GetAllTriggersAsync() + public List GetAllTriggersAsync() { - var triggers = await _repositoryManager.Triggers.GetAllAsync(); - return _mapper.Map>(triggers); + var triggers = _appStorageService.Triggers.Values.ToList(); + return _mapper.Map>(triggers); } /// /// 根据 ID 获取触发器定义 /// - public async Task GetTriggerByIdAsync(int id) + public async Task GetTriggerByIdAsync(int id) { - var trigger = await _repositoryManager.Triggers.GetByIdAsync(id); - return trigger != null ? _mapper.Map(trigger) : null; + _appStorageService.Triggers.TryGetValue(id, out var trigger); + return trigger; } /// /// 创建一个新的触发器定义 /// - public async Task CreateTriggerAsync(TriggerDefinitionDto triggerDto) + public async Task CreateTriggerAsync(TriggerDefinition triggerDto) { // 1. 验证 DTO (可以在应用层或领域层做) ValidateTriggerDto(triggerDto); @@ -59,10 +59,10 @@ namespace DMS.Application.Services.Management var createdTrigger = await _repositoryManager.Triggers.AddAsync(triggerEntity); // 4. 转换回 DTO 并返回 - var result = _mapper.Map(createdTrigger); + var result = _mapper.Map(createdTrigger); // 5. 同步更新AppDataStorageService中的Triggers字典 - _appDataStorageService.Triggers[result.Id] = result; + _appStorageService.Triggers[result.Id] = result; return result; } @@ -70,7 +70,7 @@ namespace DMS.Application.Services.Management /// /// 更新一个已存在的触发器定义 /// - public async Task UpdateTriggerAsync(int id, TriggerDefinitionDto triggerDto) + public async Task UpdateTriggerAsync(int id, TriggerDefinition triggerDto) { // 1. 获取现有实体 var existingTrigger = await _repositoryManager.Triggers.GetByIdAsync(id); @@ -90,10 +90,10 @@ namespace DMS.Application.Services.Management return null; // 5. 转换回 DTO 并返回 - var result = _mapper.Map(updatedTrigger); + var result = _mapper.Map(updatedTrigger); // 6. 同步更新AppDataStorageService中的Triggers字典 - _appDataStorageService.Triggers[result.Id] = result; + _appStorageService.Triggers[result.Id] = result; return result; } @@ -103,33 +103,46 @@ namespace DMS.Application.Services.Management /// public async Task DeleteTriggerAsync(int id) { - var result = await _repositoryManager.Triggers.DeleteAsync(id); - - // 如果删除成功,也从AppDataStorageService中的Triggers字典中移除 - if (result) - { - _appDataStorageService.Triggers.TryRemove(id, out _); - } - - return result; + // var result = await _repositoryManager.Triggers.DeleteAsync(id); + // + // // 如果删除成功,也从AppDataStorageService中的Triggers字典中移除 + // if (result) + // { + // _appStorageService.Triggers.TryRemove(id, out _); + // } + // + // return result; + return false; } /// /// 获取与指定变量关联的所有触发器定义 /// - public async Task> GetTriggersForVariableAsync(int variableId) + public async Task> GetTriggersForVariableAsync(int variableId) { - var triggers = await _repositoryManager.Triggers.GetByVariableIdAsync(variableId); - return _mapper.Map>(triggers); + // var triggers = await _repositoryManager.Triggers.GetByVariableIdAsync(variableId); + // return _mapper.Map>(triggers); + return null; + } + + public async Task LoadAllTriggersAsync() + { + _appStorageService.Triggers.Clear(); + var triggerDefinitions = await _repositoryManager.Triggers.GetAllAsync(); + foreach (var triggerDefinition in triggerDefinitions) + { + _appStorageService.Triggers.TryAdd(triggerDefinition.Id, triggerDefinition); + } + } /// - /// 内部方法:验证 TriggerDefinitionDto 的有效性 + /// 内部方法:验证 TriggerDefinition 的有效性 /// - private void ValidateTriggerDto(TriggerDefinitionDto dto) + private void ValidateTriggerDto(TriggerDefinition dto) { // 检查是否至少关联了一个变量 - if (dto.VariableIds == null || !dto.VariableIds.Any()) + if (dto.Variables == null || !dto.Variables.Any()) throw new ArgumentException("触发器必须至少关联一个变量。"); // 添加必要的验证逻辑 diff --git a/DMS.Application/Services/Management/TriggerVariableManagementService.cs b/DMS.Application/Services/Management/TriggerVariableManagementService.cs new file mode 100644 index 0000000..eb232cb --- /dev/null +++ b/DMS.Application/Services/Management/TriggerVariableManagementService.cs @@ -0,0 +1,125 @@ +using DMS.Application.Events; +using DMS.Application.Interfaces; +using DMS.Application.Interfaces.Database; +using DMS.Application.Interfaces.Management; +using DMS.Core.Enums; +using DMS.Core.Models.Triggers; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace DMS.Application.Services.Management; + +public class TriggerVariableManagementService : ITriggerVariableManagementService +{ + private readonly ITriggerVariableAppService _triggerVariableAppService; + private readonly IAppStorageService _appStorageService; + private readonly IEventService _eventService; + + public TriggerVariableManagementService(ITriggerVariableAppService triggerVariableAppService,IAppStorageService appStorageService,IEventService eventService) + { + _triggerVariableAppService = triggerVariableAppService; + _appStorageService = appStorageService; + _eventService = eventService; + } + + public async Task AssignTriggerVariableAsync(TriggerVariable triggerVariable) + { + var newTriggerVariable = await _triggerVariableAppService.AssignTriggerVariableAsync(triggerVariable); + if (newTriggerVariable != null) + { + // Add to cache + _appStorageService.TriggerVariables.TryAdd(newTriggerVariable.Id, newTriggerVariable); + + _eventService.RaiseTriggerVariableChanged(this, new TriggerVariableChangedEventArgs(ActionChangeType.Added, newTriggerVariable)); + } + + return newTriggerVariable; + } + + public async Task> LoadAllTriggerVariablesAsync() + { + var triggerVariables = await _triggerVariableAppService.GetAllAsync(); + foreach (var triggerVariable in triggerVariables) + { + // Add to cache + _appStorageService.TriggerVariables.TryAdd(triggerVariable.Id, triggerVariable); + + + if (_appStorageService.Triggers.TryGetValue(triggerVariable.TriggerDefinitionId, out var trigger)) + { + if (_appStorageService.Variables.TryGetValue(triggerVariable.VariableId, out var variable)) + { + trigger.Variables.Add(variable); + + } + } + + + _eventService.RaiseTriggerVariableChanged(this, new TriggerVariableChangedEventArgs(ActionChangeType.Added, triggerVariable)); + } + + return triggerVariables; + } + + public async Task UpdateAsync(TriggerVariable triggerVariable) + { + int res = await _triggerVariableAppService.UpdateTriggerVariableAsync(triggerVariable); + if (res > 0) + { + // Update cache + if (_appStorageService.TriggerVariables.TryGetValue(triggerVariable.Id, out var existingTriggerVariable)) + { + existingTriggerVariable.TriggerDefinitionId = triggerVariable.TriggerDefinitionId; + existingTriggerVariable.VariableId = triggerVariable.VariableId; + } + } + return res; + } + + public async Task DeleteAsync(int id) + { + var result = await _triggerVariableAppService.RemoveTriggerVariableAsync(id); + if (result == 0) return false; + + if (_appStorageService.TriggerVariables.TryGetValue(id, out var triggerVariable)) + { + _appStorageService.TriggerVariables.TryRemove(triggerVariable.Id, out _); + _eventService.RaiseTriggerVariableChanged( + this, new TriggerVariableChangedEventArgs(ActionChangeType.Deleted, triggerVariable)); + } + return true; + } + + // public async Task> GetVariableIdsByTriggerIdAsync(int triggerId) + // { + // return await _triggerVariableAppService.GetVariableIdsByTriggerIdAsync(triggerId); + // } + + // public async Task> GetTriggerIdsByVariableIdAsync(int variableId) + // { + // return await _triggerVariableAppService.GetTriggerIdsByVariableIdAsync(variableId); + // } + + public async Task> AddTriggerVariablesAsync(List triggerVariables) + { + var addedTriggerVariables = await _triggerVariableAppService.AddTriggerVariablesAsync(triggerVariables); + foreach (var triggerVariable in addedTriggerVariables) + { + // Add to cache + _appStorageService.TriggerVariables.TryAdd(triggerVariable.Id, triggerVariable); + _eventService.RaiseTriggerVariableChanged(this, new TriggerVariableChangedEventArgs(ActionChangeType.Added, triggerVariable)); + } + + return addedTriggerVariables; + } + + public async Task DeleteByTriggerIdAsync(int triggerId) + { + // var result = await _triggerVariableAppService.RemoveTriggerVariablesByTriggerIdAsync(triggerId); + // 注意:这里可能需要额外的缓存管理逻辑,因为删除的是多个条目 + // 可能需要根据triggerId获取这些变量ID并从缓存中移除 + // 为简化实现,我们先不处理缓存中的逐个删除,而依赖于后续的重新加载 + // return result != null; + return false; + } +} \ No newline at end of file diff --git a/DMS.Application/Services/Management/VariableManagementService.cs b/DMS.Application/Services/Management/VariableManagementService.cs index 8cfc4aa..f9df09e 100644 --- a/DMS.Application/Services/Management/VariableManagementService.cs +++ b/DMS.Application/Services/Management/VariableManagementService.cs @@ -18,20 +18,20 @@ public class VariableManagementService : IVariableManagementService private readonly IVariableAppService _variableAppService; private readonly IEventService _eventService; private readonly IMapper _mapper; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IDataProcessingService _dataProcessingService; public VariableManagementService(IVariableAppService variableAppService, IEventService eventService, IMapper mapper, - IAppDataStorageService appDataStorageService, + IAppStorageService appStorageService, IDataProcessingService dataProcessingService) { _variableAppService = variableAppService; _eventService = eventService; _mapper = mapper; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _dataProcessingService = dataProcessingService; } @@ -61,13 +61,13 @@ public class VariableManagementService : IVariableManagementService // 创建成功后,将变量添加到内存中 if (result != null) { - if (_appDataStorageService.VariableTables.TryGetValue(result.VariableTableId, out var variableTable)) + if (_appStorageService.VariableTables.TryGetValue(result.VariableTableId, out var variableTable)) { result.VariableTable = variableTable; variableTable.Variables.Add(result); } - if (_appDataStorageService.Variables.TryAdd(result.Id, result)) + if (_appStorageService.Variables.TryAdd(result.Id, result)) { _eventService.RaiseVariableChanged( this, new VariableChangedEventArgs(ActionChangeType.Added, result)); @@ -97,7 +97,7 @@ public class VariableManagementService : IVariableManagementService { foreach (var variable in variables) { - if (_appDataStorageService.Variables.TryGetValue(variable.Id, out var mVariable)) + if (_appStorageService.Variables.TryGetValue(variable.Id, out var mVariable)) { // 比较旧值和新值,确定哪个属性发生了变化 var changedProperties = GetChangedProperties(mVariable, variable); @@ -122,7 +122,7 @@ public class VariableManagementService : IVariableManagementService else { // 如果内存中不存在该变量,则直接添加 - _appDataStorageService.Variables.TryAdd(variable.Id, variable); + _appStorageService.Variables.TryAdd(variable.Id, variable); _eventService.RaiseVariableChanged( this, new VariableChangedEventArgs(ActionChangeType.Added, variable, VariablePropertyType.All)); } @@ -142,9 +142,9 @@ public class VariableManagementService : IVariableManagementService // 删除成功后,从内存中移除变量 if (result) { - if (_appDataStorageService.Variables.TryRemove(id, out var variable)) + if (_appStorageService.Variables.TryRemove(id, out var variable)) { - if (variable != null && _appDataStorageService.VariableTables.TryGetValue(variable.VariableTableId, out var variableTable)) + if (variable != null && _appStorageService.VariableTables.TryGetValue(variable.VariableTableId, out var variableTable)) { variableTable.Variables.Remove(variable); @@ -166,7 +166,7 @@ public class VariableManagementService : IVariableManagementService var result = await _variableAppService.BatchImportVariablesAsync(variables); foreach (var variable in result) { - if (_appDataStorageService.VariableTables.TryGetValue(variable.VariableTableId ,out var variableTable)) + if (_appStorageService.VariableTables.TryGetValue(variable.VariableTableId ,out var variableTable)) { variable.VariableTable = variableTable; } @@ -258,9 +258,9 @@ public class VariableManagementService : IVariableManagementService { foreach (var id in ids) { - if (_appDataStorageService.Variables.TryRemove(id, out var variable)) + if (_appStorageService.Variables.TryRemove(id, out var variable)) { - if (variable != null && _appDataStorageService.VariableTables.TryGetValue(variable.VariableTableId, out var variableTable)) + if (variable != null && _appStorageService.VariableTables.TryGetValue(variable.VariableTableId, out var variableTable)) { variableTable.Variables.Remove(variable); } diff --git a/DMS.Application/Services/Management/VariableTableManagementService.cs b/DMS.Application/Services/Management/VariableTableManagementService.cs index b780659..93c866e 100644 --- a/DMS.Application/Services/Management/VariableTableManagementService.cs +++ b/DMS.Application/Services/Management/VariableTableManagementService.cs @@ -14,7 +14,7 @@ namespace DMS.Application.Services.Management; public class VariableTableManagementService : IVariableTableManagementService { private readonly IVariableTableAppService _variableTableAppService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IEventService _eventService; /// @@ -23,11 +23,11 @@ public class VariableTableManagementService : IVariableTableManagementService public event EventHandler OnVariableTableChanged; public VariableTableManagementService(IVariableTableAppService variableTableAppService, - IAppDataStorageService appDataStorageService, + IAppStorageService appStorageService, IEventService eventService) { _variableTableAppService = variableTableAppService; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _eventService = eventService; } @@ -58,8 +58,8 @@ public class VariableTableManagementService : IVariableTableManagementService if (result?.VariableTable != null) { // 添加null检查 - if (_appDataStorageService.Devices != null && - _appDataStorageService.Devices.TryGetValue(result.VariableTable.DeviceId, out var device)) + if (_appStorageService.Devices != null && + _appStorageService.Devices.TryGetValue(result.VariableTable.DeviceId, out var device)) { // 确保VariableTables不为null if (device.VariableTables == null) @@ -73,7 +73,7 @@ public class VariableTableManagementService : IVariableTableManagementService } // 确保_variableTables和result.VariableTable不为null - if (_appDataStorageService.VariableTables.TryAdd(result.VariableTable.Id, result.VariableTable)) + if (_appStorageService.VariableTables.TryAdd(result.VariableTable.Id, result.VariableTable)) { _eventService.RaiseVariableTableChanged(this, new VariableTableChangedEventArgs( DataChangeType.Added, @@ -94,7 +94,7 @@ public class VariableTableManagementService : IVariableTableManagementService // 更新成功后,更新内存中的变量表 if (result > 0 && variableTable != null) { - _appDataStorageService.VariableTables.AddOrUpdate(variableTable.Id, variableTable, (key, oldValue) => variableTable); + _appStorageService.VariableTables.AddOrUpdate(variableTable.Id, variableTable, (key, oldValue) => variableTable); _eventService.RaiseVariableTableChanged(this, new VariableTableChangedEventArgs( DataChangeType.Updated, variableTable)); @@ -113,9 +113,9 @@ public class VariableTableManagementService : IVariableTableManagementService // 删除成功后,从内存中移除变量表 if (result ) { - if (_appDataStorageService.VariableTables.TryRemove(id, out var variableTable)) + if (_appStorageService.VariableTables.TryRemove(id, out var variableTable)) { - if (variableTable != null && _appDataStorageService.Devices.TryGetValue(variableTable.DeviceId, out var device)) + if (variableTable != null && _appStorageService.Devices.TryGetValue(variableTable.DeviceId, out var device)) { if (device.VariableTables != null) device.VariableTables.Remove(variableTable); diff --git a/DMS.Application/Services/Monitoring/DeviceMonitoringService.cs b/DMS.Application/Services/Monitoring/DeviceMonitoringService.cs index 466593f..e64b1c4 100644 --- a/DMS.Application/Services/Monitoring/DeviceMonitoringService.cs +++ b/DMS.Application/Services/Monitoring/DeviceMonitoringService.cs @@ -17,8 +17,8 @@ public class DeviceMonitoringService : IDeviceMonitoringService, IDisposable { private readonly ILogger _logger; private readonly IEventService _eventService; - private readonly IAppDataStorageService _appDataStorageService; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppStorageService _appStorageService; + private readonly IAppCenterService _appCenterService; /// @@ -27,13 +27,13 @@ public class DeviceMonitoringService : IDeviceMonitoringService, IDisposable /// 日志记录器 /// 设备应用服务 public DeviceMonitoringService(ILogger logger, IEventService eventService, - IAppDataStorageService appDataStorageService, - IAppDataCenterService appDataCenterService) + IAppStorageService appStorageService, + IAppCenterService appCenterService) { _logger = logger; _eventService = eventService; - _appDataStorageService = appDataStorageService; - _appDataCenterService = appDataCenterService; + _appStorageService = appStorageService; + _appCenterService = appCenterService; _eventService.OnDeviceStateChanged += OnDeviceStateChanged; } @@ -42,12 +42,12 @@ public class DeviceMonitoringService : IDeviceMonitoringService, IDisposable // 只处理激活状态变化事件 if (e.StateType == Core.Enums.DeviceStateType.Active) { - if (_appDataStorageService.Devices.TryGetValue(e.DeviceId, out var device)) + if (_appStorageService.Devices.TryGetValue(e.DeviceId, out var device)) { // 更新设备激活状态 - 同时更新数据库和内存 _ = Task.Run(async () => { - await _appDataCenterService.DeviceManagementService.UpdateDeviceAsync(device); + await _appCenterService.DeviceManagementService.UpdateDeviceAsync(device); }); } } diff --git a/DMS.Application/Services/Triggers/Impl/TriggerEvaluationService.cs b/DMS.Application/Services/Triggers/Impl/TriggerEvaluationService.cs index d7ac7e2..13011b1 100644 --- a/DMS.Application/Services/Triggers/Impl/TriggerEvaluationService.cs +++ b/DMS.Application/Services/Triggers/Impl/TriggerEvaluationService.cs @@ -101,7 +101,7 @@ namespace DMS.Application.Services.Triggers.Impl /// /// 内部方法:评估单个触发器的条件 /// - private bool EvaluateCondition(TriggerDefinitionDto trigger, object currentValueObj) + private bool EvaluateCondition(TriggerDefinition trigger, object currentValueObj) { if (currentValueObj == null) { @@ -139,7 +139,7 @@ namespace DMS.Application.Services.Triggers.Impl /// /// 内部方法:检查触发器是否处于抑制窗口期内 /// - private bool IsWithinSuppressionWindow(TriggerDefinitionDto trigger) + private bool IsWithinSuppressionWindow(TriggerDefinition trigger) { if (!trigger.SuppressionDuration.HasValue || !trigger.LastTriggeredAt.HasValue) return false; diff --git a/DMS.Application/Services/Triggers/TriggerContext.cs b/DMS.Application/Services/Triggers/TriggerContext.cs index 683284a..cc5f084 100644 --- a/DMS.Application/Services/Triggers/TriggerContext.cs +++ b/DMS.Application/Services/Triggers/TriggerContext.cs @@ -1,6 +1,7 @@ using DMS.Application.DTOs; using DMS.Core.Models; using System; +using DMS.Core.Models.Triggers; namespace DMS.Application.Services.Triggers { @@ -10,5 +11,5 @@ namespace DMS.Application.Services.Triggers /// 被触发的触发器定义 /// 触发时变量的当前值 /// 关联的变量信息 - public record TriggerContext(TriggerDefinitionDto Trigger, object CurrentValue, Variable Variable); + public record TriggerContext(TriggerDefinition Trigger, object CurrentValue, Variable Variable); } \ No newline at end of file diff --git a/DMS.Core/Interfaces/IRepositoryManager.cs b/DMS.Core/Interfaces/IRepositoryManager.cs index abd2261..39d7458 100644 --- a/DMS.Core/Interfaces/IRepositoryManager.cs +++ b/DMS.Core/Interfaces/IRepositoryManager.cs @@ -33,7 +33,7 @@ public interface IRepositoryManager : IDisposable /// /// 获取变量MQTT别名仓储的实例。 /// - IVariableMqttAliasRepository MqttAliases { get; set; } + IMqttAliasRepository MqttAliases { get; set; } /// /// 获取菜单仓储的实例。 @@ -60,6 +60,11 @@ public interface IRepositoryManager : IDisposable /// ITriggerRepository Triggers { get; set; } + /// + /// 获取触发器与变量关联仓储的实例。 + /// + ITriggerVariableRepository TriggerVariables { get; set; } + /// /// 初始化数据库 /// @@ -81,4 +86,6 @@ public interface IRepositoryManager : IDisposable /// /// 一个表示异步操作的任务。 Task RollbackAsync(); + + } \ No newline at end of file diff --git a/DMS.Core/Interfaces/Repositories/IVariableMqttAliasRepository.cs b/DMS.Core/Interfaces/Repositories/IMqttAliasRepository.cs similarity index 82% rename from DMS.Core/Interfaces/Repositories/IVariableMqttAliasRepository.cs rename to DMS.Core/Interfaces/Repositories/IMqttAliasRepository.cs index 8565faf..26b6145 100644 --- a/DMS.Core/Interfaces/Repositories/IVariableMqttAliasRepository.cs +++ b/DMS.Core/Interfaces/Repositories/IMqttAliasRepository.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; namespace DMS.Core.Interfaces.Repositories { - public interface IVariableMqttAliasRepository : IBaseRepository + public interface IMqttAliasRepository : IBaseRepository { /// diff --git a/DMS.Core/Interfaces/Repositories/ITriggerVariableRepository.cs b/DMS.Core/Interfaces/Repositories/ITriggerVariableRepository.cs new file mode 100644 index 0000000..51e9a08 --- /dev/null +++ b/DMS.Core/Interfaces/Repositories/ITriggerVariableRepository.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using DMS.Core.Models.Triggers; + +namespace DMS.Core.Interfaces.Repositories +{ + public interface ITriggerVariableRepository : IBaseRepository + { + /// + /// 异步获取所有触发器与变量关联。 + /// + /// 包含所有触发器与变量关联实体的列表。 + Task> GetAllAsync(); + } +} \ No newline at end of file diff --git a/DMS.Core/Interfaces/Repositories/Triggers/ITriggerRepository.cs b/DMS.Core/Interfaces/Repositories/Triggers/ITriggerRepository.cs index 71699df..0304336 100644 --- a/DMS.Core/Interfaces/Repositories/Triggers/ITriggerRepository.cs +++ b/DMS.Core/Interfaces/Repositories/Triggers/ITriggerRepository.cs @@ -2,53 +2,14 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; using DMS.Core.Models.Triggers; +using DMS.Core.Interfaces.Repositories; namespace DMS.Core.Interfaces.Repositories.Triggers { /// /// 触发器仓储接口 (定义对 TriggerDefinition 实体的数据访问方法) /// - public interface ITriggerRepository + public interface ITriggerRepository : IBaseRepository { - /// - /// 获取所有触发器定义 - /// - /// 触发器定义实体列表 - Task> GetAllAsync(); - - /// - /// 根据 ID 获取触发器定义 - /// - /// 触发器 ID - /// 触发器定义实体,如果未找到则返回 null - Task GetByIdAsync(int id); - - /// - /// 添加一个新的触发器定义 - /// - /// 要添加的触发器定义实体 - /// 添加成功的触发器定义实体(通常会填充生成的 ID) - Task AddAsync(TriggerDefinition trigger); - - /// - /// 更新一个已存在的触发器定义 - /// - /// 包含更新信息的触发器定义实体 - /// 更新后的触发器定义实体,如果未找到则返回 null - Task UpdateAsync(TriggerDefinition trigger); - - /// - /// 删除一个触发器定义 - /// - /// 要删除的触发器 ID - /// 删除成功返回 true,否则返回 false - Task DeleteAsync(int id); - - /// - /// 获取与指定变量关联的所有触发器定义 - /// - /// 变量 ID - /// 该变量关联的触发器定义实体列表 - Task> GetByVariableIdAsync(int variableId); } } \ No newline at end of file diff --git a/DMS.Core/Interfaces/Services/IMqttServiceManager.cs b/DMS.Core/Interfaces/Services/IMqttServiceManager.cs index 6907a17..e7f537c 100644 --- a/DMS.Core/Interfaces/Services/IMqttServiceManager.cs +++ b/DMS.Core/Interfaces/Services/IMqttServiceManager.cs @@ -25,7 +25,7 @@ namespace DMS.Core.Interfaces.Services /// /// 更新MQTT服务器变量别名 /// - void UpdateVariableMqttAliases(int mqttServerId, List variableMqttAliases); + void UpdateMqttAliases(int mqttServerId, List mqttAliases); /// /// 获取MQTT服务器连接状态 diff --git a/DMS.Core/Models/Triggers/TriggerDefinition.cs b/DMS.Core/Models/Triggers/TriggerDefinition.cs index bf7aa54..5b32941 100644 --- a/DMS.Core/Models/Triggers/TriggerDefinition.cs +++ b/DMS.Core/Models/Triggers/TriggerDefinition.cs @@ -40,7 +40,7 @@ namespace DMS.Core.Models.Triggers /// /// 关联的变量列表 /// - public List VariableIds { get; set; } = new List(); + public List Variables { get; set; } = new List(); /// /// 触发器是否处于激活状态 diff --git a/DMS.Core/Models/Triggers/TriggerVariable.cs b/DMS.Core/Models/Triggers/TriggerVariable.cs new file mode 100644 index 0000000..7f7ffee --- /dev/null +++ b/DMS.Core/Models/Triggers/TriggerVariable.cs @@ -0,0 +1,25 @@ +using System; + +namespace DMS.Core.Models.Triggers +{ + /// + /// 触发器与变量关联领域模型 + /// + public class TriggerVariable + { + /// + /// 触发器与变量关联唯一标识符 + /// + public int Id { get; set; } + + /// + /// 外键,指向触发器定义的 Id + /// + public int TriggerDefinitionId { get; set; } + + /// + /// 外键,指向变量的 Id + /// + public int VariableId { get; set; } + } +} \ No newline at end of file diff --git a/DMS.Infrastructure/Entities/DbVariableMqttAlias.cs b/DMS.Infrastructure/Entities/DbMqttAlias.cs similarity index 95% rename from DMS.Infrastructure/Entities/DbVariableMqttAlias.cs rename to DMS.Infrastructure/Entities/DbMqttAlias.cs index bc2590a..df3a590 100644 --- a/DMS.Infrastructure/Entities/DbVariableMqttAlias.cs +++ b/DMS.Infrastructure/Entities/DbMqttAlias.cs @@ -5,7 +5,7 @@ namespace DMS.Infrastructure.Entities; /// /// 数据库实体:对应数据库中的 MqttAliases 表。 /// -public class DbVariableMqttAlias +public class DbMqttAlias { [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public int Id { get; set; } diff --git a/DMS.Infrastructure/Profiles/MappingProfile.cs b/DMS.Infrastructure/Profiles/MappingProfile.cs index 665292c..fb5a958 100644 --- a/DMS.Infrastructure/Profiles/MappingProfile.cs +++ b/DMS.Infrastructure/Profiles/MappingProfile.cs @@ -30,7 +30,7 @@ public class MappingProfile : Profile CreateMap() .ForMember(dest => dest.VariableAliases, opt => opt.Ignore()) .ReverseMap(); - CreateMap() + CreateMap() .ReverseMap(); CreateMap().ReverseMap(); @@ -46,16 +46,6 @@ public class MappingProfile : Profile // --- 触发器映射 --- CreateMap() - .ForMember(dest => dest.SuppressionDuration, - opt => opt.MapFrom(src => src.SuppressionDurationTicks.HasValue ? - TimeSpan.FromTicks(src.SuppressionDurationTicks.Value) : - (TimeSpan?)null)) - .ForMember(dest => dest.VariableIds, opt => opt.MapFrom(src => src.VariableIds)) - .ReverseMap() - .ForMember(dest => dest.SuppressionDurationTicks, - opt => opt.MapFrom(src => src.SuppressionDuration.HasValue ? - src.SuppressionDuration.Value.Ticks : - (long?)null)) - .ForMember(dest => dest.VariableIds, opt => opt.MapFrom(src => src.VariableIds)); + .ReverseMap(); } } diff --git a/DMS.Infrastructure/Repositories/InitializeRepository.cs b/DMS.Infrastructure/Repositories/InitializeRepository.cs index 21d5898..e881278 100644 --- a/DMS.Infrastructure/Repositories/InitializeRepository.cs +++ b/DMS.Infrastructure/Repositories/InitializeRepository.cs @@ -43,7 +43,7 @@ public class InitializeRepository : IInitializeRepository _db.CodeFirst.InitTables(); _db.CodeFirst.InitTables(); _db.CodeFirst.InitTables(); - _db.CodeFirst.InitTables(); + _db.CodeFirst.InitTables(); _db.CodeFirst.InitTables(); _db.CodeFirst.InitTables(); _db.CodeFirst.InitTables(); diff --git a/DMS.Infrastructure/Repositories/VariableMqttAliasRepository.cs b/DMS.Infrastructure/Repositories/MqttAliasRepository.cs similarity index 79% rename from DMS.Infrastructure/Repositories/VariableMqttAliasRepository.cs rename to DMS.Infrastructure/Repositories/MqttAliasRepository.cs index 11c1acc..f6ef1d4 100644 --- a/DMS.Infrastructure/Repositories/VariableMqttAliasRepository.cs +++ b/DMS.Infrastructure/Repositories/MqttAliasRepository.cs @@ -13,9 +13,9 @@ namespace DMS.Infrastructure.Repositories; /// /// 变量与MQTT别名关联仓储实现类,负责变量与MQTT别名关联数据的持久化操作。 -/// 继承自 并实现 接口。 +/// 继承自 并实现 接口。 /// -public class VariableMqttAliasRepository : BaseRepository, IVariableMqttAliasRepository +public class MqttAliasRepository : BaseRepository, IMqttAliasRepository { private readonly IMapper _mapper; @@ -25,7 +25,7 @@ public class VariableMqttAliasRepository : BaseRepository, /// AutoMapper 实例,用于实体模型和数据库模型之间的映射。 /// SqlSugar 数据库上下文,用于数据库操作。 /// 日志记录器实例。 - public VariableMqttAliasRepository(IMapper mapper, SqlSugarDbContext dbContext, ILogger logger) + public MqttAliasRepository(IMapper mapper, SqlSugarDbContext dbContext, ILogger logger) : base(dbContext, logger) { _mapper = mapper; @@ -38,8 +38,8 @@ public class VariableMqttAliasRepository : BaseRepository, /// 对应的变量与MQTT别名关联实体,如果不存在则为null。 public async Task GetByIdAsync(int id) { - var dbVariableMqttAlias = await base.GetByIdAsync(id); - return _mapper.Map(dbVariableMqttAlias); + var dbMqttAlias = await base.GetByIdAsync(id); + return _mapper.Map(dbMqttAlias); } /// @@ -59,8 +59,8 @@ public class VariableMqttAliasRepository : BaseRepository, /// 添加成功后的变量与MQTT别名关联实体(包含数据库生成的ID等信息)。 public async Task AddAsync(MqttAlias entity) { - var dbVariableMqttAlias = await base.AddAsync(_mapper.Map(entity)); - return _mapper.Map(dbVariableMqttAlias, entity); + var dbMqttAlias = await base.AddAsync(_mapper.Map(entity)); + return _mapper.Map(dbMqttAlias, entity); } /// @@ -68,14 +68,14 @@ public class VariableMqttAliasRepository : BaseRepository, /// /// 要更新的变量与MQTT别名关联实体。 /// 受影响的行数。 - public async Task UpdateAsync(MqttAlias entity) => await base.UpdateAsync(_mapper.Map(entity)); + public async Task UpdateAsync(MqttAlias entity) => await base.UpdateAsync(_mapper.Map(entity)); /// /// 异步删除变量与MQTT别名关联。 /// /// 要删除的变量与MQTT别名关联实体。 /// 受影响的行数。 - public async Task DeleteAsync(MqttAlias entity) => await base.DeleteAsync(_mapper.Map(entity)); + public async Task DeleteAsync(MqttAlias entity) => await base.DeleteAsync(_mapper.Map(entity)); /// /// 异步根据ID删除变量与MQTT别名关联。 @@ -86,10 +86,10 @@ public class VariableMqttAliasRepository : BaseRepository, { var stopwatch = new Stopwatch(); stopwatch.Start(); - var result = await _dbContext.GetInstance().Deleteable(new DbVariableMqttAlias() { Id = id }) + var result = await _dbContext.GetInstance().Deleteable(new DbMqttAlias() { Id = id }) .ExecuteCommandAsync(); stopwatch.Stop(); - _logger.LogInformation($"Delete {typeof(DbVariableMqttAlias)},ID={id},耗时:{stopwatch.ElapsedMilliseconds}ms"); + _logger.LogInformation($"Delete {typeof(DbMqttAlias)},ID={id},耗时:{stopwatch.ElapsedMilliseconds}ms"); return result; } @@ -107,7 +107,7 @@ public class VariableMqttAliasRepository : BaseRepository, public async Task> AddBatchAsync(List entities) { - var dbEntities = _mapper.Map>(entities); + var dbEntities = _mapper.Map>(entities); var addedEntities = await base.AddBatchAsync(dbEntities); return _mapper.Map>(addedEntities); } diff --git a/DMS.Infrastructure/Repositories/RepositoryManager.cs b/DMS.Infrastructure/Repositories/RepositoryManager.cs index 558d5d8..8af9e2c 100644 --- a/DMS.Infrastructure/Repositories/RepositoryManager.cs +++ b/DMS.Infrastructure/Repositories/RepositoryManager.cs @@ -3,7 +3,10 @@ using DMS.Core.Interfaces; using DMS.Core.Interfaces.Repositories; using DMS.Core.Interfaces.Repositories.Triggers; // 引入新的接口 using DMS.Infrastructure.Data; +using DMS.Infrastructure.Entities; using SqlSugar; +using System.Collections.Generic; +using System.Threading.Tasks; namespace DMS.Infrastructure.Repositories; @@ -24,24 +27,26 @@ public class RepositoryManager : IRepositoryManager /// 变量表仓储实例。 /// 变量仓储实例。 /// MQTT服务器仓储实例。 - /// 变量MQTT别名仓储实例。 + /// 变量MQTT别名仓储实例。 /// 菜单仓储实例。 /// 变量历史仓储实例。 /// 用户仓储实例。 /// Nlog日志仓储实例。 /// 触发器仓储实例。 + /// 触发器与变量关联仓储实例。 public RepositoryManager( SqlSugarDbContext dbContext, IInitializeRepository initializeRepository, IDeviceRepository devices, IVariableTableRepository variableTables, IVariableRepository variables, IMqttServerRepository mqttServers, - IVariableMqttAliasRepository variableMqttAliases, + IMqttAliasRepository mqttAliases, IMenuRepository menus, IVariableHistoryRepository variableHistories, IUserRepository users, INlogRepository nlogs, - ITriggerRepository triggers) // 新增参数 + ITriggerRepository triggers, + ITriggerVariableRepository triggerVariables) // 新增参数 { _dbContext = dbContext; InitializeRepository = initializeRepository; @@ -49,12 +54,13 @@ public class RepositoryManager : IRepositoryManager VariableTables = variableTables; Variables = variables; MqttServers = mqttServers; - MqttAliases = variableMqttAliases; + MqttAliases = mqttAliases; Menus = menus; VariableHistories = variableHistories; Users = users; Nlogs = nlogs; Triggers = triggers; // 赋值 + TriggerVariables = triggerVariables; // 赋值 _db = dbContext.GetInstance(); } @@ -86,7 +92,7 @@ public class RepositoryManager : IRepositoryManager /// /// 获取变量MQTT别名仓储实例。 /// - public IVariableMqttAliasRepository MqttAliases { get; set; } + public IMqttAliasRepository MqttAliases { get; set; } /// /// 获取菜单仓储实例。 /// @@ -108,6 +114,10 @@ public class RepositoryManager : IRepositoryManager /// public ITriggerRepository Triggers { get; set; } /// + /// 获取触发器与变量关联仓储实例。 + /// + public ITriggerVariableRepository TriggerVariables { get; set; } + /// /// 获取初始化仓储实例。 /// public IInitializeRepository InitializeRepository { get; set; } @@ -141,4 +151,5 @@ public class RepositoryManager : IRepositoryManager if (_db != null) await _db.RollbackTranAsync(); } + } \ No newline at end of file diff --git a/DMS.Infrastructure/Repositories/TriggerRepository.cs b/DMS.Infrastructure/Repositories/TriggerRepository.cs index cd1c199..5750e6c 100644 --- a/DMS.Infrastructure/Repositories/TriggerRepository.cs +++ b/DMS.Infrastructure/Repositories/TriggerRepository.cs @@ -5,6 +5,9 @@ using DMS.Core.Models.Triggers; using DMS.Infrastructure.Data; using DMS.Infrastructure.Entities; using Microsoft.Extensions.Logging; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Linq; namespace DMS.Infrastructure.Repositories { @@ -29,161 +32,91 @@ namespace DMS.Infrastructure.Repositories } /// - /// 获取所有触发器定义 + /// 异步根据ID获取单个触发器定义。 /// - public async Task> GetAllAsync() - { - var dbList = await base.GetAllAsync(); - // 加载关联的变量ID - foreach (var dbTrigger in dbList) - { - var variableIds = await _dbContext.GetInstance() - .Queryable() - .Where(tv => tv.TriggerDefinitionId == dbTrigger.Id) - .Select(tv => tv.VariableId) - .ToListAsync(); - dbTrigger.VariableIds = variableIds; - } - return _mapper.Map>(dbList); - } - - /// - /// 根据 ID 获取触发器定义 - /// - public async Task GetByIdAsync(int id) + /// 触发器定义的唯一标识符。 + /// 对应的触发器定义实体,如果不存在则为null。 + public async Task GetByIdAsync(int id) { var dbTrigger = await base.GetByIdAsync(id); - if (dbTrigger != null) - { - // 加载关联的变量ID - var variableIds = await _dbContext.GetInstance() - .Queryable() - .Where(tv => tv.TriggerDefinitionId == dbTrigger.Id) - .Select(tv => tv.VariableId) - .ToListAsync(); - dbTrigger.VariableIds = variableIds; - } return _mapper.Map(dbTrigger); } /// - /// 添加一个新的触发器定义 + /// 异步获取所有触发器定义。 /// - public async Task AddAsync(TriggerDefinition trigger) + /// 包含所有触发器定义实体的列表。 + public async Task> GetAllAsync() { - var dbTrigger = _mapper.Map(trigger); - dbTrigger = await base.AddAsync(dbTrigger); - - // 保存关联的变量ID - if (trigger.VariableIds != null && trigger.VariableIds.Any()) - { - var triggerVariables = trigger.VariableIds.Select(variableId => new DbTriggerVariable - { - TriggerDefinitionId = dbTrigger.Id, - VariableId = variableId - }).ToList(); - - await _dbContext.GetInstance().Insertable(triggerVariables).ExecuteCommandAsync(); - } - - return _mapper.Map(dbTrigger, trigger); - } - - /// - /// 更新一个已存在的触发器定义 - /// - public async Task UpdateAsync(TriggerDefinition trigger) - { - var dbTrigger = _mapper.Map(trigger); - var rowsAffected = await base.UpdateAsync(dbTrigger); - - if (rowsAffected > 0) - { - // 删除旧的关联关系 - await _dbContext.GetInstance() - .Deleteable() - .Where(tv => tv.TriggerDefinitionId == dbTrigger.Id) - .ExecuteCommandAsync(); - - // 插入新的关联关系 - if (trigger.VariableIds != null && trigger.VariableIds.Any()) - { - var triggerVariables = trigger.VariableIds.Select(variableId => new DbTriggerVariable - { - TriggerDefinitionId = dbTrigger.Id, - VariableId = variableId - }).ToList(); - - await _dbContext.GetInstance().Insertable(triggerVariables).ExecuteCommandAsync(); - } - - return trigger; - } - - return null; - } - - /// - /// 删除一个触发器定义 - /// - public async Task DeleteAsync(int id) - { - var stopwatch = new Stopwatch(); - stopwatch.Start(); - - // 先删除关联的变量关系 - await _dbContext.GetInstance() - .Deleteable() - .Where(tv => tv.TriggerDefinitionId == id) - .ExecuteCommandAsync(); - - // 再删除触发器本身 - var rowsAffected = await _dbContext.GetInstance().Deleteable() - .In(id) - .ExecuteCommandAsync(); - stopwatch.Stop(); - _logger.LogInformation($"Delete {typeof(DbTriggerDefinition).Name},ID={id},耗时:{stopwatch.ElapsedMilliseconds}ms"); - return rowsAffected > 0; - } - - /// - /// 获取与指定变量关联的所有触发器定义 - /// - public async Task> GetByVariableIdAsync(int variableId) - { - var stopwatch = new Stopwatch(); - stopwatch.Start(); - - // 先查询关联表获取触发器ID - var triggerIds = await _dbContext.GetInstance() - .Queryable() - .Where(tv => tv.VariableId == variableId) - .Select(tv => tv.TriggerDefinitionId) - .ToListAsync(); - - // 再查询触发器定义 - var dbList = new List(); - if (triggerIds.Any()) - { - dbList = await _dbContext.GetInstance().Queryable() - .In(it => it.Id, triggerIds) - .ToListAsync(); - - // 加载每个触发器的变量ID列表 - foreach (var dbTrigger in dbList) - { - var variableIds = await _dbContext.GetInstance() - .Queryable() - .Where(tv => tv.TriggerDefinitionId == dbTrigger.Id) - .Select(tv => tv.VariableId) - .ToListAsync(); - dbTrigger.VariableIds = variableIds; - } - } - - stopwatch.Stop(); - _logger.LogInformation($"GetByVariableId {typeof(DbTriggerDefinition).Name},VariableId={variableId},耗时:{stopwatch.ElapsedMilliseconds}ms"); + var dbList = await base.GetAllAsync(); return _mapper.Map>(dbList); } + + /// + /// 异步添加新触发器定义。 + /// + /// 要添加的触发器定义实体。 + /// 添加成功后的触发器定义实体(包含数据库生成的ID等信息)。 + public async Task AddAsync(TriggerDefinition entity) + { + var dbTrigger = _mapper.Map(entity); + var addedDbTrigger = await base.AddAsync(dbTrigger); + return _mapper.Map(addedDbTrigger, entity); + } + + /// + /// 异步更新现有触发器定义。 + /// + /// 要更新的触发器定义实体。 + /// 受影响的行数。 + public async Task UpdateAsync(TriggerDefinition entity) + { + var dbTrigger = _mapper.Map(entity); + return await base.UpdateAsync(dbTrigger); + } + + /// + /// 异步删除触发器定义。 + /// + /// 要删除的触发器定义实体。 + /// 受影响的行数。 + public async Task DeleteAsync(TriggerDefinition entity) + { + return await base.DeleteAsync(_mapper.Map(entity)); + } + + /// + /// 异步根据ID删除触发器定义。 + /// + /// 要删除触发器定义的唯一标识符。 + /// 受影响的行数。 + public async Task DeleteByIdAsync(int id) + { + var stopwatch = new Stopwatch(); + stopwatch.Start(); + var result = await _dbContext.GetInstance().Deleteable(new DbTriggerDefinition() { Id = id }) + .ExecuteCommandAsync(); + stopwatch.Stop(); + _logger.LogInformation($"Delete {typeof(DbTriggerDefinition)},ID={id},耗时:{stopwatch.ElapsedMilliseconds}ms"); + return result; + } + + /// + /// 异步获取指定数量的触发器定义。 + /// + /// 要获取的触发器定义数量。 + /// 包含指定数量触发器定义实体的列表。 + public new async Task> TakeAsync(int number) + { + var dbList = await base.TakeAsync(number); + return _mapper.Map>(dbList); + } + + public async Task> AddBatchAsync(List entities) + { + var dbEntities = _mapper.Map>(entities); + var addedEntities = await base.AddBatchAsync(dbEntities); + return _mapper.Map>(addedEntities); + } } } \ No newline at end of file diff --git a/DMS.Infrastructure/Repositories/TriggerVariableRepository.cs b/DMS.Infrastructure/Repositories/TriggerVariableRepository.cs new file mode 100644 index 0000000..0377824 --- /dev/null +++ b/DMS.Infrastructure/Repositories/TriggerVariableRepository.cs @@ -0,0 +1,113 @@ +using System.Diagnostics; +using DMS.Core.Interfaces.Repositories; +using DMS.Infrastructure.Data; +using DMS.Infrastructure.Entities; +using AutoMapper; +using Microsoft.Extensions.Logging; +using DMS.Core.Models.Triggers; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Linq; + +namespace DMS.Infrastructure.Repositories; + +/// +/// 触发器与变量关联仓储实现类,负责触发器与变量关联数据的持久化操作。 +/// 继承自 并实现 接口。 +/// +public class TriggerVariableRepository : BaseRepository, ITriggerVariableRepository +{ + private readonly IMapper _mapper; + + /// + /// 构造函数,注入 AutoMapper 和 SqlSugarDbContext。 + /// + /// AutoMapper 实例,用于实体模型和数据库模型之间的映射。 + /// SqlSugar 数据库上下文,用于数据库操作。 + /// 日志记录器实例。 + public TriggerVariableRepository(IMapper mapper, SqlSugarDbContext dbContext, ILogger logger) + : base(dbContext, logger) + { + _mapper = mapper; + } + + /// + /// 异步根据ID获取单个触发器与变量关联。 + /// + /// 触发器与变量关联的唯一标识符。 + /// 对应的触发器与变量关联实体,如果不存在则为null。 + public async Task GetByIdAsync(int id) + { + var dbTriggerVariable = await base.GetByIdAsync(id); + return _mapper.Map(dbTriggerVariable); + } + + /// + /// 异步获取所有触发器与变量关联。 + /// + /// 包含所有触发器与变量关联实体的列表。 + public async Task> GetAllAsync() + { + var dbList = await base.GetAllAsync(); + return _mapper.Map>(dbList); + } + + /// + /// 异步添加新触发器与变量关联。 + /// + /// 要添加的触发器与变量关联实体。 + /// 添加成功后的触发器与变量关联实体(包含数据库生成的ID等信息)。 + public async Task AddAsync(TriggerVariable entity) + { + var dbTriggerVariable = await base.AddAsync(_mapper.Map(entity)); + return _mapper.Map(dbTriggerVariable, entity); + } + + /// + /// 异步更新现有触发器与变量关联。 + /// + /// 要更新的触发器与变量关联实体。 + /// 受影响的行数。 + public async Task UpdateAsync(TriggerVariable entity) => await base.UpdateAsync(_mapper.Map(entity)); + + /// + /// 异步删除触发器与变量关联。 + /// + /// 要删除的触发器与变量关联实体。 + /// 受影响的行数。 + public async Task DeleteAsync(TriggerVariable entity) => await base.DeleteAsync(_mapper.Map(entity)); + + /// + /// 异步根据ID删除触发器与变量关联。 + /// + /// 要删除触发器与变量关联的唯一标识符。 + /// 受影响的行数。 + public async Task DeleteByIdAsync(int id) + { + var stopwatch = new Stopwatch(); + stopwatch.Start(); + var result = await _dbContext.GetInstance().Deleteable(new DbTriggerVariable() { Id = id }) + .ExecuteCommandAsync(); + stopwatch.Stop(); + _logger.LogInformation($"Delete {typeof(DbTriggerVariable)},ID={id},耗时:{stopwatch.ElapsedMilliseconds}ms"); + return result; + } + + /// + /// 异步获取指定数量的触发器与变量关联。 + /// + /// 要获取的触发器与变量关联数量。 + /// 包含指定数量触发器与变量关联实体的列表。 + public new async Task> TakeAsync(int number) + { + var dbList = await base.TakeAsync(number); + return _mapper.Map>(dbList); + } + + public async Task> AddBatchAsync(List entities) + { + var dbEntities = _mapper.Map>(entities); + var addedEntities = await base.AddBatchAsync(dbEntities); + return _mapper.Map>(addedEntities); + } +} \ No newline at end of file diff --git a/DMS.Infrastructure/Services/Mqtt/MqttBackgroundService.cs b/DMS.Infrastructure/Services/Mqtt/MqttBackgroundService.cs index cff9dd5..efea6cd 100644 --- a/DMS.Infrastructure/Services/Mqtt/MqttBackgroundService.cs +++ b/DMS.Infrastructure/Services/Mqtt/MqttBackgroundService.cs @@ -17,8 +17,8 @@ namespace DMS.Infrastructure.Services.Mqtt private readonly ILogger _logger; private readonly IMqttServiceManager _mqttServiceManager; private readonly IEventService _eventService; - private readonly IAppDataStorageService _appDataStorageService; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppStorageService _appStorageService; + private readonly IAppCenterService _appCenterService; private readonly ConcurrentDictionary _mqttServers; private readonly SemaphoreSlim _reloadSemaphore = new(0); @@ -26,14 +26,14 @@ namespace DMS.Infrastructure.Services.Mqtt ILogger logger, IMqttServiceManager mqttServiceManager, IEventService eventService, - IAppDataStorageService appDataStorageService, - IAppDataCenterService appDataCenterService) + IAppStorageService appStorageService, + IAppCenterService appCenterService) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _mqttServiceManager = mqttServiceManager ?? throw new ArgumentNullException(nameof(mqttServiceManager)); _eventService = eventService; - _appDataStorageService = appDataStorageService; - _appDataCenterService = appDataCenterService ?? throw new ArgumentNullException(nameof(appDataCenterService)); + _appStorageService = appStorageService; + _appCenterService = appCenterService ?? throw new ArgumentNullException(nameof(appCenterService)); _mqttServers = new ConcurrentDictionary(); _eventService.OnLoadDataCompleted += OnLoadDataCompleted; @@ -186,7 +186,7 @@ namespace DMS.Infrastructure.Services.Mqtt _mqttServers.Clear(); // 从数据服务中心获取所有激活的MQTT服务器 - var mqttServers = _appDataStorageService.MqttServers.Values.ToList(); + var mqttServers = _appStorageService.MqttServers.Values.ToList(); foreach (var mqttServer in mqttServers) { diff --git a/DMS.Infrastructure/Services/Mqtt/MqttDeviceContext.cs b/DMS.Infrastructure/Services/Mqtt/MqttDeviceContext.cs index 30c7506..fff37b5 100644 --- a/DMS.Infrastructure/Services/Mqtt/MqttDeviceContext.cs +++ b/DMS.Infrastructure/Services/Mqtt/MqttDeviceContext.cs @@ -28,14 +28,14 @@ namespace DMS.Infrastructure.Services.Mqtt /// /// 与该MQTT服务器关联的所有变量MQTT别名 /// - public ConcurrentDictionary VariableMqttAliases { get; set; } + public ConcurrentDictionary MqttAliases { get; set; } /// /// 构造函数 /// public MqttDeviceContext() { - VariableMqttAliases = new ConcurrentDictionary(); + MqttAliases = new ConcurrentDictionary(); ReconnectAttempts = 0; } } diff --git a/DMS.Infrastructure/Services/Mqtt/MqttServiceManager.cs b/DMS.Infrastructure/Services/Mqtt/MqttServiceManager.cs index c565474..c28b7e1 100644 --- a/DMS.Infrastructure/Services/Mqtt/MqttServiceManager.cs +++ b/DMS.Infrastructure/Services/Mqtt/MqttServiceManager.cs @@ -19,7 +19,7 @@ namespace DMS.Infrastructure.Services.Mqtt { private readonly ILogger _logger; private readonly IDataProcessingService _dataProcessingService; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppCenterService _appDataCenterService; private readonly IMqttServiceFactory _mqttServiceFactory; private readonly IEventService _eventService; @@ -30,7 +30,7 @@ namespace DMS.Infrastructure.Services.Mqtt public MqttServiceManager( ILogger logger, IDataProcessingService dataProcessingService, - IAppDataCenterService appDataCenterService, + IAppCenterService appDataCenterService, IMqttServiceFactory mqttServiceFactory, IEventService eventService) { @@ -91,16 +91,16 @@ namespace DMS.Infrastructure.Services.Mqtt /// /// 更新MQTT服务器变量别名 /// - public void UpdateVariableMqttAliases(int mqttServerId, List variableMqttAliases) + public void UpdateMqttAliases(int mqttServerId, List mqttAliases) { if (_mqttContexts.TryGetValue(mqttServerId, out var context)) { - context.VariableMqttAliases.Clear(); - foreach (var alias in variableMqttAliases) + context.MqttAliases.Clear(); + foreach (var alias in mqttAliases) { - context.VariableMqttAliases.AddOrUpdate(alias.Id, alias, (key, oldValue) => alias); + context.MqttAliases.AddOrUpdate(alias.Id, alias, (key, oldValue) => alias); } - _logger.LogInformation("已更新MQTT服务器 {MqttServerId} 的变量别名列表,共 {Count} 个别名", mqttServerId, variableMqttAliases.Count); + _logger.LogInformation("已更新MQTT服务器 {MqttServerId} 的变量别名列表,共 {Count} 个别名", mqttServerId, mqttAliases.Count); } } diff --git a/DMS.Infrastructure/Services/OpcUa/OpcUaServiceManager.cs b/DMS.Infrastructure/Services/OpcUa/OpcUaServiceManager.cs index eae5f89..b923f8f 100644 --- a/DMS.Infrastructure/Services/OpcUa/OpcUaServiceManager.cs +++ b/DMS.Infrastructure/Services/OpcUa/OpcUaServiceManager.cs @@ -22,7 +22,7 @@ namespace DMS.Infrastructure.Services.OpcUa { private readonly ILogger _logger; private readonly IDataProcessingService _dataProcessingService; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppCenterService _appCenterService; private readonly IEventService _eventService; private readonly OpcUaServiceOptions _options; private readonly ConcurrentDictionary _deviceContexts; @@ -33,15 +33,15 @@ namespace DMS.Infrastructure.Services.OpcUa ILogger logger, IDataProcessingService dataProcessingService, IEventService eventService, - IAppDataCenterService appDataCenterService, + IAppCenterService appCenterService, IOptions options) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _dataProcessingService = dataProcessingService ?? throw new ArgumentNullException(nameof(dataProcessingService)); _eventService = eventService; - _appDataCenterService - = appDataCenterService ?? throw new ArgumentNullException(nameof(appDataCenterService)); + _appCenterService + = appCenterService ?? throw new ArgumentNullException(nameof(appCenterService)); _options = options?.Value ?? throw new ArgumentNullException(nameof(options)); _deviceContexts = new ConcurrentDictionary(); _semaphore = new SemaphoreSlim(_options.MaxConcurrentConnections, _options.MaxConcurrentConnections); diff --git a/DMS.Infrastructure/Services/OpcUa/OptimizedOpcUaBackgroundService.cs b/DMS.Infrastructure/Services/OpcUa/OptimizedOpcUaBackgroundService.cs index e0b0fa8..b478696 100644 --- a/DMS.Infrastructure/Services/OpcUa/OptimizedOpcUaBackgroundService.cs +++ b/DMS.Infrastructure/Services/OpcUa/OptimizedOpcUaBackgroundService.cs @@ -14,22 +14,22 @@ namespace DMS.Infrastructure.Services.OpcUa /// public class OptimizedOpcUaBackgroundService : BackgroundService { - private readonly IAppDataCenterService _appDataCenterService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppCenterService _appCenterService; + private readonly IAppStorageService _appStorageService; private readonly IEventService _eventService; private readonly IOpcUaServiceManager _opcUaServiceManager; private readonly ILogger _logger; private readonly SemaphoreSlim _reloadSemaphore = new SemaphoreSlim(0); public OptimizedOpcUaBackgroundService( - IAppDataCenterService appDataCenterService, - IAppDataStorageService appDataStorageService, + IAppCenterService appCenterService, + IAppStorageService appStorageService, IEventService eventService, IOpcUaServiceManager opcUaServiceManager, ILogger logger) { - _appDataCenterService = appDataCenterService ?? throw new ArgumentNullException(nameof(appDataCenterService)); - _appDataStorageService = appDataStorageService; + _appCenterService = appCenterService ?? throw new ArgumentNullException(nameof(appCenterService)); + _appStorageService = appStorageService; _opcUaServiceManager = opcUaServiceManager ?? throw new ArgumentNullException(nameof(opcUaServiceManager)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _eventService = eventService; @@ -60,7 +60,7 @@ namespace DMS.Infrastructure.Services.OpcUa if (stoppingToken.IsCancellationRequested) break; - if (_appDataStorageService.Devices.IsEmpty) + if (_appStorageService.Devices.IsEmpty) { _logger.LogInformation("没有可用的OPC UA设备,等待设备列表更新..."); continue; @@ -96,7 +96,7 @@ namespace DMS.Infrastructure.Services.OpcUa try { // 获取所有活动的OPC UA设备 - var opcUaDevices = _appDataStorageService.Devices.Values + var opcUaDevices = _appStorageService.Devices.Values .Where(d => d.Protocol == ProtocolType.OpcUa ) .ToList(); diff --git a/DMS.Infrastructure/Services/S7/OptimizedS7BackgroundService.cs b/DMS.Infrastructure/Services/S7/OptimizedS7BackgroundService.cs index 842b2db..84150a3 100644 --- a/DMS.Infrastructure/Services/S7/OptimizedS7BackgroundService.cs +++ b/DMS.Infrastructure/Services/S7/OptimizedS7BackgroundService.cs @@ -19,8 +19,8 @@ namespace DMS.Infrastructure.Services.S7; /// public class OptimizedS7BackgroundService : BackgroundService { - private readonly IAppDataCenterService _appDataCenterService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppCenterService _appCenterService; + private readonly IAppStorageService _appStorageService; private readonly IEventService _eventService; private readonly IDataProcessingService _dataProcessingService; private readonly IS7ServiceManager _s7ServiceManager; @@ -38,15 +38,15 @@ public class OptimizedS7BackgroundService : BackgroundService /// 构造函数,注入数据服务和数据处理服务。 /// public OptimizedS7BackgroundService( - IAppDataCenterService appDataCenterService, - IAppDataStorageService appDataStorageService, + IAppCenterService appCenterService, + IAppStorageService appStorageService, IEventService eventService, IDataProcessingService dataProcessingService, IS7ServiceManager s7ServiceManager, ILogger logger) { - _appDataCenterService = appDataCenterService; - _appDataStorageService = appDataStorageService; + _appCenterService = appCenterService; + _appStorageService = appStorageService; _eventService = eventService; _dataProcessingService = dataProcessingService; _s7ServiceManager = s7ServiceManager; @@ -76,7 +76,7 @@ public class OptimizedS7BackgroundService : BackgroundService break; } - if (_appDataStorageService.Devices.IsEmpty) + if (_appStorageService.Devices.IsEmpty) { _logger.LogInformation("没有可用的S7设备,等待设备列表更新..."); continue; @@ -124,7 +124,7 @@ public class OptimizedS7BackgroundService : BackgroundService _variablesByPollingInterval.Clear(); _logger.LogInformation("开始加载S7变量...."); - var s7Devices = _appDataStorageService + var s7Devices = _appStorageService .Devices.Values.Where(d => d.Protocol == ProtocolType.S7 && d.IsActive == true) .ToList(); @@ -161,7 +161,7 @@ public class OptimizedS7BackgroundService : BackgroundService /// private async Task ConnectS7ServiceAsync(CancellationToken stoppingToken) { - var s7Devices = _appDataStorageService + var s7Devices = _appStorageService .Devices.Values.Where(d => d.Protocol == ProtocolType.S7 && d.IsActive == true) .ToList(); @@ -207,7 +207,7 @@ public class OptimizedS7BackgroundService : BackgroundService private async Task PollVariablesForDeviceAsync(S7DeviceContext context, List variables, CancellationToken stoppingToken) { - if (!_appDataStorageService.Devices.TryGetValue(context.Device.Id, out var device)) + if (!_appStorageService.Devices.TryGetValue(context.Device.Id, out var device)) { _logger.LogWarning($"轮询时没有找到设备ID:{context.Device.Id}"); return; diff --git a/DMS.Infrastructure/Services/S7/S7ServiceManager.cs b/DMS.Infrastructure/Services/S7/S7ServiceManager.cs index 95dc700..7380f81 100644 --- a/DMS.Infrastructure/Services/S7/S7ServiceManager.cs +++ b/DMS.Infrastructure/Services/S7/S7ServiceManager.cs @@ -19,8 +19,8 @@ namespace DMS.Infrastructure.Services.S7 private readonly ILogger _logger; private readonly IEventService _eventService; private readonly IDataProcessingService _dataProcessingService; - private readonly IAppDataCenterService _appDataCenterService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppCenterService _appCenterService; + private readonly IAppStorageService _appStorageService; private readonly IS7ServiceFactory _s7ServiceFactory; private readonly ConcurrentDictionary _deviceContexts; private readonly SemaphoreSlim _semaphore; @@ -30,17 +30,17 @@ namespace DMS.Infrastructure.Services.S7 ILogger logger, IEventService eventService, IDataProcessingService dataProcessingService, - IAppDataCenterService appDataCenterService, - IAppDataStorageService appDataStorageService, + IAppCenterService appCenterService, + IAppStorageService appStorageService, IS7ServiceFactory s7ServiceFactory) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _eventService = eventService; _dataProcessingService = dataProcessingService ?? throw new ArgumentNullException(nameof(dataProcessingService)); - _appDataCenterService - = appDataCenterService ?? throw new ArgumentNullException(nameof(appDataCenterService)); - _appDataStorageService = appDataStorageService; + _appCenterService + = appCenterService ?? throw new ArgumentNullException(nameof(appCenterService)); + _appStorageService = appStorageService; _s7ServiceFactory = s7ServiceFactory ?? throw new ArgumentNullException(nameof(s7ServiceFactory)); _deviceContexts = new ConcurrentDictionary(); _semaphore = new SemaphoreSlim(10, 10); // 默认最大并发连接数为10 @@ -54,7 +54,7 @@ namespace DMS.Infrastructure.Services.S7 // if (_deviceContexts.TryGetValue(e.DeviceId, out var s7DeviceContext)) // { - // var variables = _appDataStorageService.Variables.Values.Where(v => e.VariableIds.Contains(v.Id)) + // var variables = _appStorageService.Variables.Values.Where(v => e.VariableIds.Contains(v.Id)) // .ToList(); // foreach (var variable in variables) // { diff --git a/DMS.WPF/App.xaml.cs b/DMS.WPF/App.xaml.cs index 47534d0..8ce1099 100644 --- a/DMS.WPF/App.xaml.cs +++ b/DMS.WPF/App.xaml.cs @@ -229,7 +229,7 @@ public partial class App : System.Windows.Application services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -237,6 +237,7 @@ public partial class App : System.Windows.Application services.AddSingleton(); services.AddSingleton(); // 添加这行 services.AddSingleton(); // 注册触发器仓储 + services.AddSingleton(); // 注册触发器与变量关联仓储 services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -255,10 +256,10 @@ public partial class App : System.Windows.Application services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/DMS.WPF/Services/DataEventService.cs b/DMS.WPF/Services/DataEventService.cs index ebab5ef..e6e3263 100644 --- a/DMS.WPF/Services/DataEventService.cs +++ b/DMS.WPF/Services/DataEventService.cs @@ -24,7 +24,7 @@ public class DataEventService : IDataEventService private readonly IDataStorageService _dataStorageService; private readonly IEventService _eventService; private readonly INotificationService _notificationService; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppCenterService _appCenterService; private readonly IWPFDataService _wpfDataService; private readonly ILogger _logger; @@ -35,7 +35,7 @@ public class DataEventService : IDataEventService IDataStorageService dataStorageService, IEventService eventService, INotificationService notificationService, - IAppDataCenterService appDataCenterService, + IAppCenterService appCenterService, IWPFDataService wpfDataService, ILogger logger) { @@ -43,7 +43,7 @@ public class DataEventService : IDataEventService _dataStorageService = dataStorageService; _eventService = eventService; _notificationService = notificationService; - _appDataCenterService = appDataCenterService; + _appCenterService = appCenterService; _wpfDataService = wpfDataService; _logger = logger; @@ -54,7 +54,7 @@ public class DataEventService : IDataEventService _eventService.OnMqttServerChanged += OnMqttServerChanged; _eventService.OnLoadDataCompleted += OnLoadDataCompleted; // 监听日志变更事件 - // _appDataCenterService.OnLogChanged += _logDataService.OnNlogChanged; + // _appCenterService.OnLogChanged += _logDataService.OnNlogChanged; _logger?.LogInformation("DataEventService 初始化完成"); } diff --git a/DMS.WPF/Services/DeviceDataService.cs b/DMS.WPF/Services/DeviceDataService.cs index 1e82e0b..ef35f76 100644 --- a/DMS.WPF/Services/DeviceDataService.cs +++ b/DMS.WPF/Services/DeviceDataService.cs @@ -18,8 +18,8 @@ namespace DMS.WPF.Services; public class DeviceDataService : IDeviceDataService { private readonly IMapper _mapper; - private readonly IAppDataCenterService _appDataCenterService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppCenterService _appCenterService; + private readonly IAppStorageService _appStorageService; private readonly IDataStorageService _dataStorageService; private readonly IVariableTableDataService _variableTableDataService; private readonly IEventService _eventService; @@ -32,15 +32,15 @@ public class DeviceDataService : IDeviceDataService /// DeviceDataService类的构造函数。 /// /// AutoMapper 实例。 - /// 数据服务中心实例。 - public DeviceDataService(IMapper mapper, IAppDataCenterService appDataCenterService, - IAppDataStorageService appDataStorageService, IDataStorageService dataStorageService,IVariableTableDataService variableTableDataService, + /// 数据服务中心实例。 + public DeviceDataService(IMapper mapper, IAppCenterService appCenterService, + IAppStorageService appStorageService, IDataStorageService dataStorageService,IVariableTableDataService variableTableDataService, IEventService eventService, INotificationService notificationService, IMenuDataService menuDataService, IVariableDataService variableDataService) { _mapper = mapper; - _appDataCenterService = appDataCenterService; - _appDataStorageService = appDataStorageService; + _appCenterService = appCenterService; + _appStorageService = appStorageService; _dataStorageService = dataStorageService; _variableTableDataService = variableTableDataService; _eventService = eventService; @@ -82,7 +82,7 @@ public class DeviceDataService : IDeviceDataService /// public void LoadAllDevices() { - foreach (var device in _appDataStorageService.Devices.Values) + foreach (var device in _appStorageService.Devices.Values) { _dataStorageService.Devices.Add(device.Id, _mapper.Map(device)); } @@ -97,7 +97,7 @@ public class DeviceDataService : IDeviceDataService if (dto == null) return null; - var addDto = await _appDataCenterService.DeviceManagementService.CreateDeviceWithDetailsAsync(dto); + var addDto = await _appCenterService.DeviceManagementService.CreateDeviceWithDetailsAsync(dto); // 添加null检查 if (addDto == null && addDto.Device == null) @@ -142,7 +142,7 @@ public class DeviceDataService : IDeviceDataService { //从数据库和内存中删除设备相关数据 - if (!await _appDataCenterService.DeviceManagementService.DeleteDeviceByIdAsync(device.Id)) + if (!await _appCenterService.DeviceManagementService.DeleteDeviceByIdAsync(device.Id)) { return false; } @@ -171,13 +171,13 @@ public class DeviceDataService : IDeviceDataService /// public async Task UpdateDevice(DeviceItem device) { - if (!_appDataStorageService.Devices.TryGetValue(device.Id, out var existingDevice)) + if (!_appStorageService.Devices.TryGetValue(device.Id, out var existingDevice)) { return false; } _mapper.Map(device, existingDevice); - if (await _appDataCenterService.DeviceManagementService.UpdateDeviceAsync(existingDevice) > 0) + if (await _appCenterService.DeviceManagementService.UpdateDeviceAsync(existingDevice) > 0) { // 更新数据库后会自动更新内存,无需额外操作 return true; diff --git a/DMS.WPF/Services/LogDataService.cs b/DMS.WPF/Services/LogDataService.cs index 171ebd2..3326acd 100644 --- a/DMS.WPF/Services/LogDataService.cs +++ b/DMS.WPF/Services/LogDataService.cs @@ -17,7 +17,7 @@ public class LogDataService : ILogDataService { private readonly IMapper _mapper; private readonly IDataStorageService _dataStorageService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; @@ -25,18 +25,18 @@ public class LogDataService : ILogDataService /// LogDataService类的构造函数。 /// /// AutoMapper 实例。 - /// 数据服务中心实例。 - public LogDataService(IMapper mapper,IDataStorageService dataStorageService, IAppDataStorageService appDataStorageService) + /// 数据服务中心实例。 + public LogDataService(IMapper mapper,IDataStorageService dataStorageService, IAppStorageService appStorageService) { _mapper = mapper; _dataStorageService = dataStorageService; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; } public void LoadAllLog() { // 加载日志数据 - _dataStorageService.Nlogs = _mapper.Map>(_appDataStorageService.Nlogs.Values); + _dataStorageService.Nlogs = _mapper.Map>(_appStorageService.Nlogs.Values); } /// diff --git a/DMS.WPF/Services/MenuDataService.cs b/DMS.WPF/Services/MenuDataService.cs index a58066b..6c00ed0 100644 --- a/DMS.WPF/Services/MenuDataService.cs +++ b/DMS.WPF/Services/MenuDataService.cs @@ -17,7 +17,7 @@ public class MenuDataService : IMenuDataService { private readonly IMapper _mapper; private readonly IDataStorageService _dataStorageService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IMenuManagementService _menuManagementService; @@ -26,18 +26,18 @@ public class MenuDataService : IMenuDataService /// MenuDataService类的构造函数。 /// /// AutoMapper 实例。 - /// 数据服务中心实例。 - public MenuDataService(IMapper mapper,IDataStorageService dataStorageService, IAppDataStorageService appDataStorageService,IMenuManagementService menuManagementService) + /// 数据服务中心实例。 + public MenuDataService(IMapper mapper,IDataStorageService dataStorageService, IAppStorageService appStorageService,IMenuManagementService menuManagementService) { _mapper = mapper; _dataStorageService = dataStorageService; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _menuManagementService = menuManagementService; } public void LoadAllMenus() { - _dataStorageService.Menus = _mapper.Map>(_appDataStorageService.Menus.Values); + _dataStorageService.Menus = _mapper.Map>(_appStorageService.Menus.Values); BuildMenuTrees(); } diff --git a/DMS.WPF/Services/MqttAliasDataService.cs b/DMS.WPF/Services/MqttAliasDataService.cs index 27c5ce0..69881f6 100644 --- a/DMS.WPF/Services/MqttAliasDataService.cs +++ b/DMS.WPF/Services/MqttAliasDataService.cs @@ -13,7 +13,7 @@ namespace DMS.WPF.Services; public class MqttAliasDataService : IMqttAliasDataService { private readonly IMapper _mapper; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IMqttAliasManagementService _mqttAliasManagementService; private readonly IDataStorageService _dataStorageService; @@ -21,16 +21,16 @@ public class MqttAliasDataService : IMqttAliasDataService /// MqttAliasDataService类的构造函数。 /// /// AutoMapper 实例。 - /// 应用数据存储服务实例。 + /// 应用数据存储服务实例。 /// MQTT别名管理服务实例。 /// 数据存储服务实例。 public MqttAliasDataService(IMapper mapper, - IAppDataStorageService appDataStorageService, + IAppStorageService appStorageService, IMqttAliasManagementService mqttAliasManagementService, IDataStorageService dataStorageService) { _mapper = mapper; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _mqttAliasManagementService = mqttAliasManagementService; _dataStorageService = dataStorageService; } @@ -46,7 +46,7 @@ public class MqttAliasDataService : IMqttAliasDataService _dataStorageService.MqttAliases.Clear(); // 加载MQTT别名数据 - foreach (var mqttAlias in _appDataStorageService.MqttAliases.Values) + foreach (var mqttAlias in _appStorageService.MqttAliases.Values) { MqttAliasItem mqttAliasItem = _mapper.Map(mqttAlias); if(_dataStorageService.MqttAliases.TryAdd(mqttAlias.Id, mqttAliasItem)) diff --git a/DMS.WPF/Services/MqttDataService.cs b/DMS.WPF/Services/MqttDataService.cs index 9066f14..597441f 100644 --- a/DMS.WPF/Services/MqttDataService.cs +++ b/DMS.WPF/Services/MqttDataService.cs @@ -17,7 +17,7 @@ namespace DMS.WPF.Services; public class MqttDataService : IMqttDataService { private readonly IMapper _mapper; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppStorageService _appStorageService; private readonly IMqttManagementService _mqttManagementService; private readonly IMenuDataService _menuDataService; private readonly IMenuManagementService _menuManagementServiceImpl; @@ -29,10 +29,10 @@ public class MqttDataService : IMqttDataService /// /// AutoMapper 实例。 /// MQTT应用服务实例。 - public MqttDataService(IMapper mapper, IAppDataStorageService appDataStorageService, IMqttManagementService mqttManagementService, IMenuDataService menuDataService, IMenuManagementService menuManagementServiceImpl, IDataStorageService dataStorageService) + public MqttDataService(IMapper mapper, IAppStorageService appStorageService, IMqttManagementService mqttManagementService, IMenuDataService menuDataService, IMenuManagementService menuManagementServiceImpl, IDataStorageService dataStorageService) { _mapper = mapper; - _appDataStorageService = appDataStorageService; + _appStorageService = appStorageService; _mqttManagementService = mqttManagementService; _menuDataService = menuDataService; _menuManagementServiceImpl = menuManagementServiceImpl; @@ -47,7 +47,7 @@ public class MqttDataService : IMqttDataService try { // 加载MQTT服务器数据 - foreach (var mqttServer in _appDataStorageService.MqttServers.Values) + foreach (var mqttServer in _appStorageService.MqttServers.Values) { _dataStorageService.MqttServers.TryAdd(mqttServer.Id, _mapper.Map(mqttServer)); } diff --git a/DMS.WPF/Services/TriggerDataService.cs b/DMS.WPF/Services/TriggerDataService.cs index 045f3da..6f97ea7 100644 --- a/DMS.WPF/Services/TriggerDataService.cs +++ b/DMS.WPF/Services/TriggerDataService.cs @@ -3,6 +3,7 @@ using AutoMapper; using DMS.Application.DTOs; using DMS.Application.Interfaces; using DMS.Core.Events; +using DMS.Core.Models.Triggers; using DMS.WPF.Interfaces; using DMS.WPF.ItemViewModel; using Opc.Ua; @@ -15,8 +16,8 @@ namespace DMS.WPF.Services; public class TriggerDataService : ITriggerDataService { private readonly IMapper _mapper; - private readonly IAppDataCenterService _appDataCenterService; - private readonly IAppDataStorageService _appDataStorageService; + private readonly IAppCenterService _appCenterService; + private readonly IAppStorageService _appStorageService; private readonly IDataStorageService _dataStorageService; private readonly IEventService _eventService; private readonly INotificationService _notificationService; @@ -26,18 +27,18 @@ public class TriggerDataService : ITriggerDataService /// TriggerDataService类的构造函数。 /// /// AutoMapper 实例。 - /// 数据服务中心实例。 - /// 应用数据存储服务实例。 + /// 数据服务中心实例。 + /// 应用数据存储服务实例。 /// 数据存储服务实例。 /// 事件服务实例。 /// 通知服务实例。 - public TriggerDataService(IMapper mapper, IAppDataCenterService appDataCenterService, - IAppDataStorageService appDataStorageService, IDataStorageService dataStorageService, + public TriggerDataService(IMapper mapper, IAppCenterService appCenterService, + IAppStorageService appStorageService, IDataStorageService dataStorageService, IEventService eventService, INotificationService notificationService) { _mapper = mapper; - _appDataCenterService = appDataCenterService; - _appDataStorageService = appDataStorageService; + _appCenterService = appCenterService; + _appStorageService = appStorageService; _dataStorageService = dataStorageService; _eventService = eventService; _notificationService = notificationService; @@ -49,7 +50,7 @@ public class TriggerDataService : ITriggerDataService /// public void LoadAllTriggers() { - foreach (var triggerDto in _appDataStorageService.Triggers.Values) + foreach (var triggerDto in _appStorageService.Triggers.Values) { _dataStorageService.Triggers.Add(triggerDto.Id, _mapper.Map(triggerDto)); } @@ -65,8 +66,8 @@ public class TriggerDataService : ITriggerDataService return null; var addDto - = await _appDataCenterService.TriggerManagementService.CreateTriggerAsync( - _mapper.Map(dto)); + = await _appCenterService.TriggerManagementService.CreateTriggerAsync( + _mapper.Map(dto)); // 添加null检查 if (addDto == null) @@ -87,7 +88,7 @@ public class TriggerDataService : ITriggerDataService public async Task DeleteTrigger(TriggerItem trigger) { // 从数据库删除触发器数据 - if (!await _appDataCenterService.TriggerManagementService.DeleteTriggerAsync(trigger.Id)) + if (!await _appCenterService.TriggerManagementService.DeleteTriggerAsync(trigger.Id)) { return false; } @@ -103,13 +104,13 @@ public class TriggerDataService : ITriggerDataService /// public async Task UpdateTrigger(TriggerItem trigger) { - if (!_appDataStorageService.Triggers.TryGetValue(trigger.Id, out var triggerDto)) + if (!_appStorageService.Triggers.TryGetValue(trigger.Id, out var triggerDto)) { return false; } _mapper.Map(trigger, triggerDto); - if (await _appDataCenterService.TriggerManagementService.UpdateTriggerAsync(trigger.Id, triggerDto) != null) + if (await _appCenterService.TriggerManagementService.UpdateTriggerAsync(trigger.Id, triggerDto) != null) { return true; } diff --git a/DMS.WPF/Services/VariableDataService.cs b/DMS.WPF/Services/VariableDataService.cs index f45d017..9c23fe0 100644 --- a/DMS.WPF/Services/VariableDataService.cs +++ b/DMS.WPF/Services/VariableDataService.cs @@ -17,7 +17,7 @@ public class VariableDataService : IVariableDataService { private readonly IMapper _mapper; private readonly IDataStorageService _dataStorageService; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppCenterService _appCenterService; @@ -25,15 +25,15 @@ public class VariableDataService : IVariableDataService /// VariableDataService类的构造函数。 /// /// AutoMapper 实例。 - /// 数据服务中心实例。 - public VariableDataService(IMapper mapper, IDataStorageService dataStorageService, IAppDataCenterService appDataCenterService) + /// 数据服务中心实例。 + public VariableDataService(IMapper mapper, IDataStorageService dataStorageService, IAppCenterService appCenterService) { _mapper = mapper; _dataStorageService = dataStorageService; - _appDataCenterService = appDataCenterService; + _appCenterService = appCenterService; // 订阅批量导入变量事件 - if (_appDataCenterService.VariableManagementService is VariableManagementService variableManagementService) + if (_appCenterService.VariableManagementService is VariableManagementService variableManagementService) { // 如果需要直接订阅事件,这将需要EventService实例 } @@ -84,7 +84,7 @@ public class VariableDataService : IVariableDataService } var variableTable = _mapper.Map(variableTableItem); - if (await _appDataCenterService.VariableTableManagementService.UpdateVariableTableAsync(variableTable) > 0) + if (await _appCenterService.VariableTableManagementService.UpdateVariableTableAsync(variableTable) > 0) { // 更新数据库后会自动更新内存,无需额外操作 return true; @@ -105,7 +105,7 @@ public class VariableDataService : IVariableDataService if (isDeleteDb) { - if (!await _appDataCenterService.VariableTableManagementService.DeleteVariableTableAsync(variableTable.Id)) + if (!await _appCenterService.VariableTableManagementService.DeleteVariableTableAsync(variableTable.Id)) { return false; } diff --git a/DMS.WPF/Services/VariableTableDataService.cs b/DMS.WPF/Services/VariableTableDataService.cs index 3988525..3e8a694 100644 --- a/DMS.WPF/Services/VariableTableDataService.cs +++ b/DMS.WPF/Services/VariableTableDataService.cs @@ -13,17 +13,17 @@ public class VariableTableDataService : IVariableTableDataService { private readonly IMapper _mapper; private readonly IDataStorageService _dataStorageService; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppCenterService _appCenterService; private readonly IMenuDataService _menuDataService; - public VariableTableDataService(IMapper mapper, IDataStorageService dataStorageService, IAppDataCenterService appDataCenterService, + public VariableTableDataService(IMapper mapper, IDataStorageService dataStorageService, IAppCenterService appCenterService, IMenuDataService menuDataService) { _mapper = mapper; _dataStorageService = dataStorageService; - _appDataCenterService = appDataCenterService; + _appCenterService = appCenterService; _menuDataService = menuDataService; } @@ -51,7 +51,7 @@ public class VariableTableDataService : IVariableTableDataService createDto.VariableTable = variableTable; createDto.DeviceId = variableTable.DeviceId; createDto.Menu = menuDto; - var resDto = await _appDataCenterService.VariableTableManagementService.CreateVariableTableAsync(createDto); + var resDto = await _appCenterService.VariableTableManagementService.CreateVariableTableAsync(createDto); await _menuDataService.AddMenuItem(_mapper.Map(resDto.Menu)); return resDto.VariableTable.Id; @@ -71,7 +71,7 @@ public class VariableTableDataService : IVariableTableDataService } var variableTable_mapped = _mapper.Map(variableTable); - if (await _appDataCenterService.VariableTableManagementService.UpdateVariableTableAsync(variableTable_mapped) > 0) + if (await _appCenterService.VariableTableManagementService.UpdateVariableTableAsync(variableTable_mapped) > 0) { // 更新数据库后会自动更新内存,无需额外操作 @@ -98,7 +98,7 @@ public class VariableTableDataService : IVariableTableDataService if (isDeleteDb) { - if (!await _appDataCenterService.VariableTableManagementService.DeleteVariableTableAsync(variableTable.Id)) + if (!await _appCenterService.VariableTableManagementService.DeleteVariableTableAsync(variableTable.Id)) { return false; } diff --git a/DMS.WPF/Services/WPFDataService.cs b/DMS.WPF/Services/WPFDataService.cs index 81b1467..1a39d92 100644 --- a/DMS.WPF/Services/WPFDataService.cs +++ b/DMS.WPF/Services/WPFDataService.cs @@ -12,7 +12,7 @@ namespace DMS.WPF.Services; public class WPFDataService : IWPFDataService { private readonly IMapper _mapper; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppCenterService _appCenterService; /// /// 设备数据服务。 @@ -59,7 +59,7 @@ public class WPFDataService : IWPFDataService /// public WPFDataService( IMapper mapper, - IAppDataCenterService appDataCenterService, + IAppCenterService appCenterService, IDeviceDataService deviceDataService, IVariableDataService variableDataService, IMenuDataService menuDataService, @@ -70,7 +70,7 @@ public class WPFDataService : IWPFDataService IMqttAliasDataService mqttAliasDataService) { _mapper = mapper; - _appDataCenterService = appDataCenterService; + _appCenterService = appCenterService; DeviceDataService = deviceDataService; VariableDataService = variableDataService; MenuDataService = menuDataService; diff --git a/DMS.WPF/ViewModels/LogHistoryViewModel.cs b/DMS.WPF/ViewModels/LogHistoryViewModel.cs index adb1a8d..82e641f 100644 --- a/DMS.WPF/ViewModels/LogHistoryViewModel.cs +++ b/DMS.WPF/ViewModels/LogHistoryViewModel.cs @@ -30,7 +30,7 @@ partial class LogHistoryViewModel : ViewModelBase,IDisposable private readonly IDialogService _dialogService; private readonly IDataStorageService _dataStorageService; private readonly INotificationService _notificationService; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppCenterService _appCenterService; [ObservableProperty] private NlogItem _selectedLog; @@ -51,7 +51,7 @@ partial class LogHistoryViewModel : ViewModelBase,IDisposable public ObservableCollection LogLevels { get; } = new ObservableCollection { "Trace", "Debug", "Info", "Warn", "Error", "Fatal" }; public LogHistoryViewModel(IMapper mapper, INlogAppService nlogAppService, IDialogService dialogService, IDataStorageService dataStorageService - , INotificationService notificationService, IWPFDataService wpfDataService, IAppDataCenterService appDataCenterService) + , INotificationService notificationService, IWPFDataService wpfDataService, IAppCenterService appCenterService) { _mapper = mapper; _nlogAppService = nlogAppService; @@ -59,7 +59,7 @@ partial class LogHistoryViewModel : ViewModelBase,IDisposable _dataStorageService = dataStorageService; _notificationService = notificationService; _wpfDataService = wpfDataService; - _appDataCenterService = appDataCenterService; + _appCenterService = appCenterService; _logItemList = new ObservableList(_dataStorageService.Nlogs); @@ -67,7 +67,7 @@ partial class LogHistoryViewModel : ViewModelBase,IDisposable LogItemListView = _synchronizedView.ToNotifyCollectionChanged(); // 订阅日志变更事件 - _appDataCenterService.LogManagementService.OnLogChanged += _wpfDataService.LogDataService.OnNlogChanged; + _appCenterService.LogManagementService.OnLogChanged += _wpfDataService.LogDataService.OnNlogChanged; } /// @@ -246,7 +246,7 @@ partial class LogHistoryViewModel : ViewModelBase,IDisposable public void Dispose() { // 取消订阅事件 - _appDataCenterService.LogManagementService.OnLogChanged -= OnNlogChanged; + _appCenterService.LogManagementService.OnLogChanged -= OnNlogChanged; } } \ No newline at end of file diff --git a/DMS.WPF/ViewModels/SplashViewModel.cs b/DMS.WPF/ViewModels/SplashViewModel.cs index e0e33b7..8145bc3 100644 --- a/DMS.WPF/ViewModels/SplashViewModel.cs +++ b/DMS.WPF/ViewModels/SplashViewModel.cs @@ -26,7 +26,7 @@ public partial class SplashViewModel : ObservableObject private readonly IServiceProvider _serviceProvider; private readonly IInitializeService _initializeService; private readonly IDataEventService _dataEventService; - private readonly IAppDataCenterService _appDataCenterService; + private readonly IAppCenterService _appCenterService; private readonly AppSettings _appSettings; [ObservableProperty] @@ -34,13 +34,13 @@ public partial class SplashViewModel : ObservableObject public SplashViewModel(ILogger logger, IServiceProvider serviceProvider, IInitializeService initializeService, IDataEventService dataEventService, - IAppDataCenterService appDataCenterService, AppSettings appSettings) + IAppCenterService appCenterService, AppSettings appSettings) { _logger = logger; _serviceProvider = serviceProvider; _initializeService = initializeService; _dataEventService = dataEventService; - this._appDataCenterService = appDataCenterService; + this._appCenterService = appCenterService; _appSettings = appSettings; } @@ -60,7 +60,7 @@ public partial class SplashViewModel : ObservableObject _initializeService.InitializeMenus(); - await _appDataCenterService.DataLoaderService.LoadAllDataToMemoryAsync(); + await _appCenterService.DataLoaderService.LoadAllDataToMemoryAsync(); // 可以在这里添加加载配置的逻辑 await Task.Delay(500); // 模拟耗时 diff --git a/DMS.WPF/ViewModels/TriggersViewModel.cs b/DMS.WPF/ViewModels/TriggersViewModel.cs index 7a0d667..96109d4 100644 --- a/DMS.WPF/ViewModels/TriggersViewModel.cs +++ b/DMS.WPF/ViewModels/TriggersViewModel.cs @@ -1,7 +1,9 @@ using System.Collections.ObjectModel; +using AutoMapper; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using DMS.Application.DTOs; +using DMS.Core.Models.Triggers; using DMS.WPF.Interfaces; using DMS.WPF.ViewModels.Dialogs; using DMS.WPF.ItemViewModel; @@ -15,6 +17,7 @@ namespace DMS.WPF.ViewModels /// public partial class TriggersViewModel : ViewModelBase { + private readonly IMapper _mapper; private readonly ITriggerDataService _triggerDataService; private readonly IDataStorageService _dataStorageService; private readonly IDialogService _dialogService; @@ -27,11 +30,13 @@ namespace DMS.WPF.ViewModels private TriggerItem? _selectedTrigger; public TriggersViewModel( + IMapper mapper, ITriggerDataService triggerDataService, IDataStorageService dataStorageService, IDialogService dialogService, INotificationService notificationService) { + _mapper = mapper; _triggerDataService = triggerDataService ?? throw new ArgumentNullException(nameof(triggerDataService)); _dataStorageService = dataStorageService ?? throw new ArgumentNullException(nameof(dataStorageService)); _dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService)); @@ -100,23 +105,7 @@ namespace DMS.WPF.ViewModels } // 传递副本以避免直接修改原始对象 - var triggerToEdit = new TriggerDefinitionDto - { - Id = SelectedTrigger.Id, - VariableIds = new List(SelectedTrigger.VariableIds), - IsActive = SelectedTrigger.IsActive, - Condition = SelectedTrigger.Condition, - Threshold = SelectedTrigger.Threshold, - LowerBound = SelectedTrigger.LowerBound, - UpperBound = SelectedTrigger.UpperBound, - Action = SelectedTrigger.Action, - ActionConfigurationJson = SelectedTrigger.ActionConfigurationJson, - SuppressionDuration = SelectedTrigger.SuppressionDuration, - LastTriggeredAt = SelectedTrigger.LastTriggeredAt, - Description = SelectedTrigger.Description, - CreatedAt = SelectedTrigger.CreatedAt, - UpdatedAt = SelectedTrigger.UpdatedAt - }; + var triggerToEdit = _mapper.Map(SelectedTrigger); TriggerDialogViewModel viewModel = App.Current.Services.GetRequiredService(); await viewModel.OnInitializedAsync(triggerToEdit);