From 33aff69cad654e5599428ff983ec71288451422f Mon Sep 17 00:00:00 2001 From: root <295172551@qq.com> Date: Sat, 14 Jun 2025 17:22:54 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=9B=B4=E6=96=B0=E8=9C=82=E7=AA=9D?= =?UTF-8?q?=E7=BD=91=E7=BB=9C=E7=9B=B8=E5=85=B3=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/CellularNetworkController.cs | 5 +- .../StartCellularNetworkCommand.cs | 6 +- .../StartCellularNetworkCommandHandler.cs | 26 ++-- .../Contexts/CellularNetworkContext.cs | 41 ++---- .../Network/ICellularNetworkContext.cs | 39 +++-- .../Network/ICellularNetworkService.cs | 6 +- .../Network/CellularNetworkOperationResult.cs | 47 ++++++ .../Network/CellularNetworkService.cs | 138 ++++++++++++------ 8 files changed, 186 insertions(+), 122 deletions(-) create mode 100644 CoreAgent.Domain/Models/Network/CellularNetworkOperationResult.cs diff --git a/CoreAgent.API/Controllers/CellularNetworkController.cs b/CoreAgent.API/Controllers/CellularNetworkController.cs index eed4601..0f7b064 100644 --- a/CoreAgent.API/Controllers/CellularNetworkController.cs +++ b/CoreAgent.API/Controllers/CellularNetworkController.cs @@ -1,4 +1,5 @@ using CoreAgent.Application.Commands.CellularNetwork; +using CoreAgent.Domain.Models.Network; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; @@ -28,8 +29,8 @@ public class CellularNetworkController : BaseApiController [HttpPost("start")] public async Task Start([FromBody] StartCellularNetworkCommand command) { - _logger.LogInformation("收到启动蜂窝网络请求: {InterfaceName}", command.Key); - return await HandleRequest(command); + _logger.LogInformation("收到启动蜂窝网络请求: {ConfigKey}", command.Key); + return await HandleRequest(command); } /// diff --git a/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommand.cs b/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommand.cs index 4364ba7..fa21763 100644 --- a/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommand.cs +++ b/CoreAgent.Application/Commands/CellularNetwork/StartCellularNetworkCommand.cs @@ -1,4 +1,4 @@ - +using CoreAgent.Domain.Models.Network; using MediatR; namespace CoreAgent.Application.Commands.CellularNetwork; @@ -6,10 +6,10 @@ namespace CoreAgent.Application.Commands.CellularNetwork; /// /// 启动蜂窝网络命令 /// -public class StartCellularNetworkCommand : IRequest +public class StartCellularNetworkCommand : IRequest { /// - /// 网络接口名称 + /// 网络配置键 /// public string Key { get; set; } } \ No newline at end of file diff --git a/CoreAgent.Application/Handlers/CellularNetwork/StartCellularNetworkCommandHandler.cs b/CoreAgent.Application/Handlers/CellularNetwork/StartCellularNetworkCommandHandler.cs index d4a323e..3ee4efc 100644 --- a/CoreAgent.Application/Handlers/CellularNetwork/StartCellularNetworkCommandHandler.cs +++ b/CoreAgent.Application/Handlers/CellularNetwork/StartCellularNetworkCommandHandler.cs @@ -1,5 +1,6 @@ using CoreAgent.Application.Commands.CellularNetwork; using CoreAgent.Domain.Interfaces.Network; +using CoreAgent.Domain.Models.Network; using MediatR; using Microsoft.Extensions.Logging; @@ -8,7 +9,7 @@ namespace CoreAgent.Application.Handlers.CellularNetwork; /// /// 启动蜂窝网络命令处理器 /// -public class StartCellularNetworkCommandHandler : IRequestHandler +public class StartCellularNetworkCommandHandler : IRequestHandler { private readonly ICellularNetworkService _cellularNetworkService; private readonly ILogger _logger; @@ -21,39 +22,30 @@ public class StartCellularNetworkCommandHandler : IRequestHandler Handle(StartCellularNetworkCommand request, CancellationToken cancellationToken) + public async Task Handle(StartCellularNetworkCommand request, CancellationToken cancellationToken) { try { - _logger.LogInformation("正在启动蜂窝网络接口: {InterfaceName}", request.Key); + _logger.LogInformation("正在启动蜂窝网络配置: {ConfigKey}", request.Key); // 启动网络 var result = await _cellularNetworkService.StartAsync(request.Key); - if (result) + if (result.IsSuccess) { - _logger.LogInformation("蜂窝网络接口 {InterfaceName} 启动成功", request.Key); - - //// 获取全局状态 - //var status = await _cellularNetworkService.GetGlobalStatusAsync(); - //_logger.LogInformation( - // "蜂窝网络状态: 已连接={IsConnected}, 信号强度={SignalStrength}, 网络类型={NetworkType}, 发射功率={TransmitPower}", - // status.CurrentStatus == NetworkStatus.Connected, - // status.CurrentSignalStrength, - // status.CurrentNetworkType, - // status.CurrentTransmitPower); + _logger.LogInformation("蜂窝网络配置 {ConfigKey} 启动成功", request.Key); } else { - _logger.LogWarning("蜂窝网络接口 {InterfaceName} 启动失败", request.Key); + _logger.LogWarning("蜂窝网络配置 {ConfigKey} 启动失败: {Error}", request.Key, result.ErrorMessage); } return result; } catch (Exception ex) { - _logger.LogError(ex, "启动蜂窝网络接口 {InterfaceName} 失败", request.Key); - return false; + _logger.LogError(ex, "启动蜂窝网络配置 {ConfigKey} 失败", request.Key); + return CellularNetworkOperationResult.Failure($"启动蜂窝网络失败: {ex.Message}"); } } } \ No newline at end of file diff --git a/CoreAgent.Domain/Contexts/CellularNetworkContext.cs b/CoreAgent.Domain/Contexts/CellularNetworkContext.cs index e441e4a..5a53d16 100644 --- a/CoreAgent.Domain/Contexts/CellularNetworkContext.cs +++ b/CoreAgent.Domain/Contexts/CellularNetworkContext.cs @@ -38,7 +38,8 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable /// /// 初始化上下文 /// - public void Initialize() + /// 网络配置键 + public void Initialize(string neConfigKey) { if (_isDisposed) { @@ -50,8 +51,14 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable return; } + if (string.IsNullOrEmpty(neConfigKey)) + { + throw new ArgumentNullException(nameof(neConfigKey)); + } + lock (_lock) { + _neConfigKey = neConfigKey; _networkState = new CellularNetworkState(_neConfigKey); _isInitialized = true; } @@ -79,34 +86,6 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable } } - /// - /// 设置网络配置键 - /// - /// 配置键 - public string SetNeConfigKey(string key) - { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(CellularNetworkContext)); - } - - if (!_isInitialized) - { - throw new InvalidOperationException("上下文未初始化"); - } - - if (string.IsNullOrEmpty(key)) - { - throw new ArgumentNullException(nameof(key)); - } - - lock (_lock) - { - _neConfigKey = key; - return _neConfigKey; - } - } - /// /// 获取网络配置键 /// @@ -194,7 +173,9 @@ public class CellularNetworkContext : ICellularNetworkContext, IDisposable { _token.Cancel(); _token = new CancellationTokenSource(); - _networkState = new CellularNetworkState(_neConfigKey); + _neConfigKey = string.Empty; + _isInitialized = false; + _networkState = new CellularNetworkState(string.Empty); } } diff --git a/CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs b/CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs index edb14db..c33dbdc 100644 --- a/CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs +++ b/CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs @@ -4,7 +4,7 @@ using CoreAgent.Domain.Models.System; namespace CoreAgent.Domain.Interfaces.Network; /// -/// 蜂窝网络上下文接口 +/// 蜂窝网络领域上下文接口 /// public interface ICellularNetworkContext { @@ -14,31 +14,17 @@ public interface ICellularNetworkContext CancellationTokenSource TokenSource { get; } /// - /// 取消操作 - /// - void Cancel(); - - /// - /// 初始化网络上下文 + /// 初始化上下文 /// - void Initialize(); + /// 网络配置键 + void Initialize(string neConfigKey); /// /// 获取网络命令配置 /// + /// 网络命令配置 NetworkCommandConfig GetNetworkCommandConfig(); - /// - /// 获取应用设置 - /// - AppSettings GetAppSettings(); - - /// - /// 设置网络配置键 - /// - /// 配置键 - string SetNeConfigKey(string key); - /// /// 获取网络配置键 /// @@ -48,20 +34,33 @@ public interface ICellularNetworkContext /// 获取指定类型的命令配置 /// /// 命令类型 + /// 命令配置列表 List GetCommandsByType(NetworkCommandType type); /// /// 获取所有命令类型 /// + /// 命令类型数组 NetworkCommandType[] GetCommandTypes(); /// /// 获取网络状态 /// + /// 网络状态 CellularNetworkState GetNetworkState(); /// - /// 重置网络上下文 + /// 重置上下文状态 /// void Reset(); + + /// + /// 取消操作 + /// + void Cancel(); + + /// + /// 获取应用设置 + /// + AppSettings GetAppSettings(); } \ No newline at end of file diff --git a/CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs b/CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs index 59931a0..451763e 100644 --- a/CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs +++ b/CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs @@ -1,4 +1,4 @@ - +using CoreAgent.Domain.Models.Network; namespace CoreAgent.Domain.Interfaces.Network; @@ -12,11 +12,11 @@ public interface ICellularNetworkService /// /// 网络配置映射Key /// 启动结果 - Task StartAsync(string Key); + Task StartAsync(string Key); /// /// 停止蜂窝网络 /// /// 停止结果 - Task StopAsync(); + Task StopAsync(); } \ No newline at end of file diff --git a/CoreAgent.Domain/Models/Network/CellularNetworkOperationResult.cs b/CoreAgent.Domain/Models/Network/CellularNetworkOperationResult.cs new file mode 100644 index 0000000..93c5abd --- /dev/null +++ b/CoreAgent.Domain/Models/Network/CellularNetworkOperationResult.cs @@ -0,0 +1,47 @@ +using CoreAgent.Domain.Models.System; + +namespace CoreAgent.Domain.Models.Network; + +/// +/// 蜂窝网络操作结果 +/// +public class CellularNetworkOperationResult +{ + /// + /// 操作是否成功 + /// + public bool IsSuccess { get; private set; } + + /// + /// 错误信息 + /// + public string ErrorMessage { get; private set; } + + /// + /// 网络状态 + /// + public NetworkStatus NetworkStatus { get; private set; } + + private CellularNetworkOperationResult(bool isSuccess, string errorMessage, NetworkStatus status) + { + IsSuccess = isSuccess; + ErrorMessage = errorMessage; + NetworkStatus = status; + } + + /// + /// 创建成功结果 + /// + public static CellularNetworkOperationResult Success(NetworkStatus status) + { + return new CellularNetworkOperationResult(true, null, status); + } + + /// + /// 创建失败结果 + /// + public static CellularNetworkOperationResult Failure(string errorMessage, NetworkStatus status = NetworkStatus.Unknown) + { + return new CellularNetworkOperationResult(false, errorMessage, status); + } +} \ No newline at end of file diff --git a/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs b/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs index 29b98f2..5bbb212 100644 --- a/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs +++ b/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs @@ -40,12 +40,12 @@ public class CellularNetworkService : ICellularNetworkService _context = context ?? throw new ArgumentNullException(nameof(context)); } - public async Task StartAsync(string key) + public async Task StartAsync(string key) { if (string.IsNullOrEmpty(key)) { _logger.LogError("启动蜂窝网络失败:配置键为空"); - return false; + return CellularNetworkOperationResult.Failure("启动蜂窝网络失败:配置键为空"); } try @@ -53,17 +53,26 @@ public class CellularNetworkService : ICellularNetworkService if (!await _startLock.WaitAsync(TimeSpan.FromSeconds(LockTimeoutSeconds))) { _logger.LogWarning("蜂窝网络启动操作被锁定,可能已有其他启动操作正在进行"); - return false; + return CellularNetworkOperationResult.Failure("蜂窝网络启动操作被锁定,可能已有其他启动操作正在进行"); + } + + // 检查网络状态 + var stateCheckResult = CheckNetworkState(key); + if (!stateCheckResult.IsSuccess) + { + return stateCheckResult; } // 初始化网络上下文 - _context.Initialize(); - var result = await StartInternalAsync(key); - if (!result) + _context.Initialize(key); + var result = await StartNetworkAsync(key); + if (!result.IsSuccess) { _logger.LogWarning("启动蜂窝网络内部操作失败,重置上下文"); _context.Reset(); + return result; } + return result; } catch (Exception ex) @@ -71,7 +80,7 @@ public class CellularNetworkService : ICellularNetworkService _logger.LogError(ex, "启动蜂窝网络失败"); // 重置上下文 _context.Reset(); - return false; + return CellularNetworkOperationResult.Failure($"启动蜂窝网络失败: {ex.Message}"); } finally { @@ -79,10 +88,55 @@ public class CellularNetworkService : ICellularNetworkService } } + /// + /// 检查网络状态 + /// + /// 新的网络配置键 + /// 检查结果 + private CellularNetworkOperationResult CheckNetworkState(string newConfigKey) + { + try + { + // 获取当前网络状态 + var currentKey = _context.GetNeConfigKey(); + var currentState = _context.GetNetworkState(); + + // 检查是否已初始化 + if (!string.IsNullOrEmpty(currentKey)) + { + // 检查是否是相同的配置 + if (currentKey == newConfigKey) + { + // 检查当前状态 + if (currentState.CurrentStatus == NetworkStatus.Connected) + { + return CellularNetworkOperationResult.Failure("当前网络配置已经处于连接状态"); + } + } + else + { + // 检查当前网络状态 + if (currentState.CurrentStatus == NetworkStatus.Connected) + { + var message = $"检测到不同的网络配置,当前运行配置: {currentKey},新配置: {newConfigKey},请先停止当前网络"; + _logger.LogWarning(message); + return CellularNetworkOperationResult.Failure(message); + } + } + } + + return CellularNetworkOperationResult.Success(NetworkStatus.Unknown); + } + catch (Exception ex) + { + _logger.LogError(ex, "检查网络状态失败"); + return CellularNetworkOperationResult.Failure($"检查网络状态失败: {ex.Message}"); + } + } - public async Task StopAsync() + public async Task StopAsync() { - string NeConfigKey = _context.GetNeConfigKey(); + string neConfigKey = _context.GetNeConfigKey(); try { // 1. 检查网络状态 @@ -91,14 +145,14 @@ public class CellularNetworkService : ICellularNetworkService { _logger.LogWarning("蜂窝网络已经处于断开或未知状态,无需停止"); _context.Reset(); // 即使不需要停止,也重置状态 - return true; + return CellularNetworkOperationResult.Success(NetworkStatus.Disconnected); } // 2. 执行初始化命令 await ExecuteInitializeCommandsAsync(); // 3. 执行停止命令 - _logger.LogInformation("正在执行停止命令: {InterfaceName}", NeConfigKey); + _logger.LogInformation("正在执行停止命令: {ConfigKey}", neConfigKey); var commands = _context.GetNetworkCommandConfig(); if (commands?.NetworkCommands != null) { @@ -115,64 +169,54 @@ public class CellularNetworkService : ICellularNetworkService } } - // 4. 停止网络接口 - if (!await DisableNetworkInterfaceAsync(NeConfigKey)) + // 4. 停止网络配置 + if (!await DisableNetworkInterfaceAsync(neConfigKey)) { - return false; + return CellularNetworkOperationResult.Failure("停止网络配置失败"); } // 5. 更新状态 - _logger.LogInformation($"蜂窝网络 {NeConfigKey} 停止成功"); + _logger.LogInformation($"蜂窝网络配置 {neConfigKey} 停止成功"); // 6. 重置上下文 _context.Reset(); - return true; + return CellularNetworkOperationResult.Success(NetworkStatus.Disconnected); } catch (Exception ex) { - _logger.LogError(ex, $"停止蜂窝网络 {NeConfigKey} 失败"); - return false; + _logger.LogError(ex, $"停止蜂窝网络配置 {neConfigKey} 失败"); + return CellularNetworkOperationResult.Failure($"停止蜂窝网络失败: {ex.Message}"); } } - private async Task StartInternalAsync(string key) + private async Task StartNetworkAsync(string key) { // 1. 获取并验证配置 var config = await _configService.GetByConfigKeyAsync(key); if (config == null) { - _logger.LogError("未找到网络配置: {ConfigKey}", key); - return false; + var message = $"未找到网络配置: {key}"; + _logger.LogError(message); + return CellularNetworkOperationResult.Failure(message); } - // 2. 检查网络状态 - var state = _context.GetNetworkState(); - if (state.CurrentStatus == NetworkStatus.Connected) - { - _logger.LogWarning("蜂窝网络已经处于连接状态,不能重复启动"); - return false; - } - - // 3. 执行初始化命令 + // 2. 执行初始化命令 await ExecuteInitializeCommandsAsync(true); - // 4. 启动网络接口 - _logger.LogInformation("正在启动蜂窝网络接口: {InterfaceName}", key); + // 3. 启动网络配置 + _logger.LogInformation("正在启动蜂窝网络配置: {ConfigKey}", key); if (!await EnableNetworkInterfaceAsync(config)) { - return false; + var message = $"启动网络配置失败: {key}"; + _logger.LogError(message); + return CellularNetworkOperationResult.Failure(message); } - // 5. 等待连接 - //if (!await WaitForConnectionAsync(key)) - //{ - // return false; - //} - - // 6. 更新状态 + // 4. 更新状态 + var state = _context.GetNetworkState(); state.MarkAsStarted(); - _logger.LogInformation("蜂窝网络接口 {InterfaceName} 启动成功", key); - return true; + _logger.LogInformation("蜂窝网络配置 {ConfigKey} 启动成功", key); + return CellularNetworkOperationResult.Success(state.CurrentStatus); } private async Task ExecuteInitializeCommandsAsync(bool bStartInit = false) @@ -487,26 +531,26 @@ public class CellularNetworkService : ICellularNetworkService return true; } - private async Task DisableNetworkInterfaceAsync(string interfaceName) + private async Task DisableNetworkInterfaceAsync(string neConfigKey) { var result = await _commandExecutor.ExecuteCommandAsync( - $"netsh interface cellular set interface \"{interfaceName}\" admin=disable", + $"netsh interface cellular set interface \"{neConfigKey}\" admin=disable", new CancellationTokenSource()); if (!result.IsSuccess) { - _logger.LogError("停止蜂窝网络接口失败"); + _logger.LogError("停止网络配置失败"); return false; } return true; } - private async Task WaitForConnectionAsync(string interfaceName) + private async Task WaitForConnectionAsync(string neConfigKey) { for (int i = 0; i < MaxConnectionAttempts; i++) { var status = await _commandExecutor.ExecuteCommandAsync( - $"netsh interface cellular show interfaces \"{interfaceName}\"", + $"netsh interface cellular show interfaces \"{neConfigKey}\"", new CancellationTokenSource()); if (status.IsSuccess && status.Output.Contains("已连接", StringComparison.OrdinalIgnoreCase))