diff --git a/DMS.Application/Interfaces/IEventService.cs b/DMS.Application/Interfaces/IEventService.cs
index e8a9b15..63d5a2a 100644
--- a/DMS.Application/Interfaces/IEventService.cs
+++ b/DMS.Application/Interfaces/IEventService.cs
@@ -55,17 +55,6 @@ public interface IEventService
#region MQTT事件
- ///
- /// MQTT连接状态改变事件
- ///
- event EventHandler MqttConnectionChanged;
-
- ///
- /// 触发MQTT连接状态改变事件
- ///
- /// 事件发送者
- /// MQTT连接状态改变事件参数
- void RaiseMqttConnectionChanged(object sender, MqttConnectionChangedEventArgs e);
///
/// MQTT服务器改变事件
@@ -107,7 +96,6 @@ public interface IEventService
/// 变量值改变事件参数
void RaiseVariableChanged(object sender, VariableChangedEventArgs e);
- void RaiseVariableActiveChanged(object sender,VariablesActiveChangedEventArgs e);
///
/// 批量导入变量事件
@@ -121,11 +109,6 @@ public interface IEventService
/// 批量导入变量事件参数
void RaiseBatchImportVariables(object sender, BatchImportVariablesEventArgs e);
- ///
- /// 变量启停改变事件
- ///
- event EventHandler OnVariableActiveChanged;
-
///
/// 数据加载完成事件
///
diff --git a/DMS.Application/Profiles/MappingProfile.cs b/DMS.Application/Profiles/MappingProfile.cs
index f1d6750..c9091e0 100644
--- a/DMS.Application/Profiles/MappingProfile.cs
+++ b/DMS.Application/Profiles/MappingProfile.cs
@@ -29,6 +29,7 @@ public class MappingProfile : Profile
// MqttServer 映射
CreateMap().ReverseMap();
+ CreateMap().ReverseMap();
// VariableMqttAlias 映射
CreateMap()
diff --git a/DMS.Application/Services/EventService.cs b/DMS.Application/Services/EventService.cs
index 7ddf331..1a19561 100644
--- a/DMS.Application/Services/EventService.cs
+++ b/DMS.Application/Services/EventService.cs
@@ -85,15 +85,6 @@ public class EventService : IEventService
}
- ///
- /// 变量启停改变事件
- ///
- public event EventHandler OnVariableActiveChanged;
- public void RaiseVariableActiveChanged(object sender, VariablesActiveChangedEventArgs e)
- {
- OnVariableActiveChanged?.Invoke(sender, e);
- }
-
///
/// 批量导入变量事件
///
@@ -128,22 +119,6 @@ public class EventService : IEventService
#endregion
#region MQTT事件
-
- ///
- /// MQTT连接状态改变事件
- ///
- public event EventHandler MqttConnectionChanged;
-
- ///
- /// 触发MQTT连接状态改变事件
- ///
- /// 事件发送者
- /// MQTT连接状态改变事件参数
- public void RaiseMqttConnectionChanged(object sender, MqttConnectionChangedEventArgs e)
- {
- MqttConnectionChanged?.Invoke(sender, e);
- }
-
///
/// MQTT服务器改变事件
///
diff --git a/DMS.Application/Services/Management/MqttManagementService.cs b/DMS.Application/Services/Management/MqttManagementService.cs
index 7e73661..680e618 100644
--- a/DMS.Application/Services/Management/MqttManagementService.cs
+++ b/DMS.Application/Services/Management/MqttManagementService.cs
@@ -105,12 +105,6 @@ public class MqttManagementService : IMqttManagementService
this, new MqttServerChangedEventArgs(ActionChangeType.Updated, mMqttServerDto, property));
}
- // 如果没有任何属性发生变化,至少触发一次更新事件
- if (changedProperties.Count == 0)
- {
- _eventService.RaiseMqttServerChanged(
- this, new MqttServerChangedEventArgs(ActionChangeType.Updated, mMqttServerDto, MqttServerPropertyType.All));
- }
}
else
{
diff --git a/DMS.Core/Events/MqttConnectionChangedEventArgs.cs b/DMS.Core/Events/MqttConnectionChangedEventArgs.cs
deleted file mode 100644
index 8608861..0000000
--- a/DMS.Core/Events/MqttConnectionChangedEventArgs.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-namespace DMS.Core.Events;
-
-///
-/// MQTT连接状态改变事件参数
-///
-public class MqttConnectionChangedEventArgs : EventArgs
-{
- ///
- /// MQTT服务器ID
- ///
- public int MqttServerId { get; }
-
- ///
- /// MQTT服务器名称
- ///
- public string MqttServerName { get; }
-
- ///
- /// 旧连接状态
- ///
- public bool OldConnectionStatus { get; }
-
- ///
- /// 新连接状态
- ///
- public bool NewConnectionStatus { get; }
-
- ///
- /// 状态改变时间
- ///
- public DateTime ChangeTime { get; }
-
- ///
- /// 初始化MqttConnectionChangedEventArgs类的新实例
- ///
- /// MQTT服务器ID
- /// MQTT服务器名称
- /// 旧连接状态
- /// 新连接状态
- public MqttConnectionChangedEventArgs(int mqttServerId, string mqttServerName, bool oldStatus, bool newStatus)
- {
- MqttServerId = mqttServerId;
- MqttServerName = mqttServerName;
- OldConnectionStatus = oldStatus;
- NewConnectionStatus = newStatus;
- ChangeTime = DateTime.Now;
- }
-}
\ No newline at end of file
diff --git a/DMS.Core/Events/VariableActiveChangedEventArgs.cs b/DMS.Core/Events/VariableActiveChangedEventArgs.cs
deleted file mode 100644
index bb12f23..0000000
--- a/DMS.Core/Events/VariableActiveChangedEventArgs.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-namespace DMS.Core.Events;
-
-public class VariablesActiveChangedEventArgs: EventArgs
-{
-
- public List VariableIds { get; }
-
- public int DeviceId{get;}
-
- public bool NewStatus { get; }
-
-
-
- public VariablesActiveChangedEventArgs(List variableIds,int deviceId, bool newStatus)
- {
- VariableIds = variableIds;
- DeviceId=deviceId;
- NewStatus = newStatus;
- }
-}
\ No newline at end of file
diff --git a/DMS.Infrastructure/Services/Mqtt/MqttBackgroundService.cs b/DMS.Infrastructure/Services/Mqtt/MqttBackgroundService.cs
index 3aea17e..e04e9cf 100644
--- a/DMS.Infrastructure/Services/Mqtt/MqttBackgroundService.cs
+++ b/DMS.Infrastructure/Services/Mqtt/MqttBackgroundService.cs
@@ -45,7 +45,7 @@ namespace DMS.Infrastructure.Services.Mqtt
{
Start();
}
-
+
}
///
@@ -137,11 +137,11 @@ namespace DMS.Infrastructure.Services.Mqtt
try
{
- while (!stoppingToken.IsCancellationRequested )
+ while (!stoppingToken.IsCancellationRequested)
{
await _reloadSemaphore.WaitAsync(stoppingToken);
- if (stoppingToken.IsCancellationRequested ) break;
+ if (stoppingToken.IsCancellationRequested) break;
// 加载MQTT配置
if (!LoadMqttConfigurations())
@@ -155,7 +155,7 @@ namespace DMS.Infrastructure.Services.Mqtt
_logger.LogInformation("MQTT后台服务已启动");
// 保持运行状态
- while (!stoppingToken.IsCancellationRequested && _reloadSemaphore.CurrentCount == 0)
+ while (!stoppingToken.IsCancellationRequested && _reloadSemaphore.CurrentCount == 0)
{
await Task.Delay(1000, stoppingToken);
}
@@ -186,9 +186,7 @@ namespace DMS.Infrastructure.Services.Mqtt
_mqttServers.Clear();
// 从数据服务中心获取所有激活的MQTT服务器
- var mqttServerDtos = _appDataStorageService.MqttServers.Values
- .Where(m => m.IsActive)
- .ToList();
+ var mqttServerDtos = _appDataStorageService.MqttServers.Values.ToList();
foreach (var mqttServerDto in mqttServerDtos)
{
@@ -252,12 +250,12 @@ namespace DMS.Infrastructure.Services.Mqtt
public override void Dispose()
{
_logger.LogInformation("正在释放MQTT后台服务资源...");
-
+
_eventService.OnLoadDataCompleted -= OnLoadDataCompleted;
_reloadSemaphore?.Dispose();
-
+
base.Dispose();
-
+
_logger.LogInformation("MQTT后台服务资源已释放");
}
}
diff --git a/DMS.Infrastructure/Services/Mqtt/MqttServiceManager.cs b/DMS.Infrastructure/Services/Mqtt/MqttServiceManager.cs
index ba2d018..67eba68 100644
--- a/DMS.Infrastructure/Services/Mqtt/MqttServiceManager.cs
+++ b/DMS.Infrastructure/Services/Mqtt/MqttServiceManager.cs
@@ -49,11 +49,6 @@ namespace DMS.Infrastructure.Services.Mqtt
_eventService.OnMqttServerChanged += OnMqttServerChanged;
}
- ///
- /// 标志是否正在处理事件,用于防止递归调用
- ///
- private readonly ConcurrentDictionary _isProcessingUpdate = new();
-
///
/// 初始化服务管理器
///
@@ -81,10 +76,6 @@ namespace DMS.Infrastructure.Services.Mqtt
_mqttContexts.AddOrUpdate(mqttServer.Id, context, (key, oldValue) => context);
_logger.LogInformation("已添加MQTT服务器 {MqttServerId} 到监控列表", mqttServer.Id);
- // 使用AutoMapper触发MQTT服务器改变事件
- var mqttServerDto = _mapper.Map(mqttServer);
-
- _eventService.RaiseMqttServerChanged(this, new MqttServerChangedEventArgs(Core.Enums.ActionChangeType.Added, mqttServerDto));
}
///
@@ -97,10 +88,6 @@ namespace DMS.Infrastructure.Services.Mqtt
await DisconnectMqttServerAsync(mqttServerId, cancellationToken);
_logger.LogInformation("已移除MQTT服务器 {MqttServerId} 的监控", mqttServerId);
- // 使用AutoMapper触发MQTT服务器删除事件
- var mqttServerDto = _mapper.Map(context.MqttServerConfig);
-
- _eventService.RaiseMqttServerChanged(this, new MqttServerChangedEventArgs(Core.Enums.ActionChangeType.Deleted, mqttServerDto));
}
}
@@ -352,14 +339,6 @@ namespace DMS.Infrastructure.Services.Mqtt
{
try
{
- // 防止同一服务器的递归更新
- if (_isProcessingUpdate.ContainsKey(e.MqttServer.Id) && _isProcessingUpdate[e.MqttServer.Id])
- {
- _logger.LogDebug("正在处理服务器 {MqttServerId} 的更新,跳过重复事件", e.MqttServer.Id);
- return;
- }
-
- _isProcessingUpdate[e.MqttServer.Id] = true;
_logger.LogDebug("处理MQTT服务器变更事件: 服务器ID={MqttServerId}, 变更类型={ChangeType}, 变更属性={PropertyType}",
e.MqttServer.Id, e.ChangeType, e.PropertyType);
@@ -382,10 +361,6 @@ namespace DMS.Infrastructure.Services.Mqtt
_logger.LogError(ex, "处理MQTT服务器变更事件时发生错误: 服务器ID={MqttServerId}, 变更类型={ChangeType}",
e.MqttServer.Id, e.ChangeType);
}
- finally
- {
- _isProcessingUpdate.TryRemove(e.MqttServer.Id, out _);
- }
}
///
@@ -474,10 +449,6 @@ namespace DMS.Infrastructure.Services.Mqtt
await ReconnectMqttServerAsync(mqttServer.Id, CancellationToken.None);
break;
case MqttServerPropertyType.IsActive:
- // 检查当前激活状态和新激活状态是否一致
- if (context.MqttServerConfig.IsActive != mqttServer.IsActive)
- {
- context.MqttServerConfig.IsActive = mqttServer.IsActive;
if (mqttServer.IsActive)
{
@@ -489,7 +460,6 @@ namespace DMS.Infrastructure.Services.Mqtt
// 激活状态变为false,断开服务器连接
await DisconnectMqttServerAsync(mqttServer.Id, CancellationToken.None);
}
- }
break;
case MqttServerPropertyType.SubscribeTopic:
context.MqttServerConfig.SubscribeTopic = mqttServer.SubscribeTopic;
@@ -556,9 +526,6 @@ namespace DMS.Infrastructure.Services.Mqtt
context.MqttServerConfig?.ServerName ?? "Unknown");
}
}
-
- // 清理处理更新状态的字典
- _isProcessingUpdate.Clear();
_logger.LogInformation("MQTT服务管理器已释放资源");
}
diff --git a/DMS.Infrastructure/Services/S7/S7ServiceManager.cs b/DMS.Infrastructure/Services/S7/S7ServiceManager.cs
index 65e2b05..9a09d75 100644
--- a/DMS.Infrastructure/Services/S7/S7ServiceManager.cs
+++ b/DMS.Infrastructure/Services/S7/S7ServiceManager.cs
@@ -45,33 +45,32 @@ namespace DMS.Infrastructure.Services.S7
_deviceContexts = new ConcurrentDictionary();
_semaphore = new SemaphoreSlim(10, 10); // 默认最大并发连接数为10
- _eventService.OnVariableActiveChanged += OnVariableActiveChanged;
_eventService.OnBatchImportVariables += OnBatchImportVariables;
_eventService.OnVariableChanged += OnVariableChanged;
}
- private void OnVariableActiveChanged(object? sender, VariablesActiveChangedEventArgs e)
- {
- if (_deviceContexts.TryGetValue(e.DeviceId, out var s7DeviceContext))
- {
+ //private void OnVariableActiveChanged(object? sender, VariablesActiveChangedEventArgs e)
+ //{
+ // if (_deviceContexts.TryGetValue(e.DeviceId, out var s7DeviceContext))
+ // {
- var variables = _appDataStorageService.Variables.Values.Where(v => e.VariableIds.Contains(v.Id))
- .ToList();
- foreach (var variable in variables)
- {
- if (e.NewStatus)
- {
- // 变量启用,从轮询列表中添加变量
- s7DeviceContext.Variables.AddOrUpdate(variable.S7Address,variable, (key, oldValue) => variable);
- }
- else
- {
- // 变量停用,从轮询列表中移除变量
- s7DeviceContext.Variables.Remove(variable.S7Address, out _);
- }
- }
- }
- }
+ // var variables = _appDataStorageService.Variables.Values.Where(v => e.VariableIds.Contains(v.Id))
+ // .ToList();
+ // foreach (var variable in variables)
+ // {
+ // if (e.NewStatus)
+ // {
+ // // 变量启用,从轮询列表中添加变量
+ // s7DeviceContext.Variables.AddOrUpdate(variable.S7Address,variable, (key, oldValue) => variable);
+ // }
+ // else
+ // {
+ // // 变量停用,从轮询列表中移除变量
+ // s7DeviceContext.Variables.Remove(variable.S7Address, out _);
+ // }
+ // }
+ // }
+ //}
///
/// 初始化服务管理器
diff --git a/DMS.WPF/Services/DataEventService.cs b/DMS.WPF/Services/DataEventService.cs
index 8eecac9..a4b1bb6 100644
--- a/DMS.WPF/Services/DataEventService.cs
+++ b/DMS.WPF/Services/DataEventService.cs
@@ -82,7 +82,6 @@ public class DataEventService : IDataEventService
break;
case MqttServerPropertyType.IsConnect:
mqttServerItem.IsConnect=e.MqttServer.IsConnect;
- _notificationService.ShowSuccess($"MQTT服务器:{mqttServerItem.ServerName},连接发生了变化,状态:{e.MqttServer.IsConnect}");
break;
case MqttServerPropertyType.Username:
break;
diff --git a/DMS.WPF/Services/MqttDataService.cs b/DMS.WPF/Services/MqttDataService.cs
index 1958503..62352be 100644
--- a/DMS.WPF/Services/MqttDataService.cs
+++ b/DMS.WPF/Services/MqttDataService.cs
@@ -4,6 +4,7 @@ using CommunityToolkit.Mvvm.ComponentModel;
using DMS.Application.DTOs;
using DMS.Application.Interfaces;
using DMS.Application.Interfaces.Database;
+using DMS.Application.Interfaces.Management;
using DMS.WPF.Interfaces;
using DMS.WPF.ViewModels.Items;
@@ -16,8 +17,8 @@ public class MqttDataService : IMqttDataService
{
private readonly IMapper _mapper;
private readonly IAppDataStorageService _appDataStorageService;
+ private readonly IMqttManagementService _mqttManagementService;
private readonly IDataStorageService _dataStorageService;
- private readonly IMqttAppService _mqttAppService;
///
@@ -25,12 +26,12 @@ public class MqttDataService : IMqttDataService
///
/// AutoMapper 实例。
/// MQTT应用服务实例。
- public MqttDataService(IMapper mapper, IAppDataStorageService appDataStorageService, IDataStorageService dataStorageService, IMqttAppService mqttAppService)
+ public MqttDataService(IMapper mapper, IAppDataStorageService appDataStorageService,IMqttManagementService mqttManagementService, IDataStorageService dataStorageService)
{
_mapper = mapper;
_appDataStorageService = appDataStorageService;
+ _mqttManagementService = mqttManagementService;
_dataStorageService = dataStorageService;
- _mqttAppService = mqttAppService;
}
///
@@ -60,11 +61,8 @@ public class MqttDataService : IMqttDataService
///
public async Task AddMqttServer(MqttServerItemViewModel mqttServer)
{
- var dto = _mapper.Map(mqttServer);
- var id = await _mqttAppService.CreateMqttServerAsync(dto);
- dto.Id = id;
-
- var mqttServerItem = _mapper.Map(dto);
+ var mqttServerDto = await _mqttManagementService.CreateMqttServerAsync(_mapper.Map(mqttServer));
+ var mqttServerItem = _mapper.Map(mqttServerDto);
_dataStorageService.MqttServers.Add(mqttServerItem.Id,mqttServerItem);
return mqttServerItem;
@@ -76,7 +74,7 @@ public class MqttDataService : IMqttDataService
public async Task UpdateMqttServer(MqttServerItemViewModel mqttServer)
{
var dto = _mapper.Map(mqttServer);
- await _mqttAppService.UpdateMqttServerAsync(dto);
+ await _mqttManagementService.UpdateMqttServerAsync(dto);
return true;
}
@@ -85,7 +83,7 @@ public class MqttDataService : IMqttDataService
///
public async Task DeleteMqttServer(MqttServerItemViewModel mqttServer)
{
- await _mqttAppService.DeleteMqttServerAsync(mqttServer.Id);
+ await _mqttManagementService.DeleteMqttServerAsync(mqttServer.Id);
_dataStorageService.MqttServers.Remove(mqttServer.Id);
return true;
}
diff --git a/DMS.WPF/ViewModels/MqttsViewModel.cs b/DMS.WPF/ViewModels/MqttsViewModel.cs
index 74008a4..3b31c84 100644
--- a/DMS.WPF/ViewModels/MqttsViewModel.cs
+++ b/DMS.WPF/ViewModels/MqttsViewModel.cs
@@ -64,12 +64,36 @@ public partial class MqttsViewModel : ViewModelBase
_navigationService = navigationService;
_notificationService = notificationService;
- // Set static services for MqttServerItemViewModel
- MqttServerItemViewModel.SetServices(_wpfDataService, _notificationService);
_mqttServeise = _dataStorageService.MqttServers.ToNotifyCollectionChanged(x=>x.Value);
}
+ [RelayCommand]
+ public async Task ToggleIsActive(MqttServerItemViewModel mqttServerItem)
+ {
+ try
+ {
+ if (mqttServerItem == null)
+ {
+ _notificationService.ShowError("没有选择任何MQTT服务器,请选择后再点击切换激活状态");
+ return;
+ }
+
+
+ // 更新到数据存储
+ await _wpfDataService.MqttDataService.UpdateMqttServer(mqttServerItem);
+
+ // 显示操作结果
+ var statusText = mqttServerItem.IsActive ? "已启用" : "已停用";
+ _notificationService.ShowSuccess($"MQTT服务器 {mqttServerItem.ServerName} 已{statusText}");
+ }
+ catch (Exception e)
+ {
+ _logger.LogError(e, "切换MQTT服务器激活状态时发生错误");
+ _notificationService.ShowError($"切换MQTT服务器激活状态时发生错误:{e.Message}", e);
+ }
+ }
+
///
/// 添加MQTT服务器命令。
///
diff --git a/DMS.WPF/Views/MqttsView.xaml b/DMS.WPF/Views/MqttsView.xaml
index 61a5bac..1053221 100644
--- a/DMS.WPF/Views/MqttsView.xaml
+++ b/DMS.WPF/Views/MqttsView.xaml
@@ -45,11 +45,13 @@
-
+ Command="{Binding DataContext.ToggleIsActiveCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
+ CommandParameter="{Binding }"
+ IsChecked="{Binding IsActive}"
+ Style="{StaticResource ToggleButtonSwitch}" />
+