diff --git a/CoreAgent.API/Program.cs b/CoreAgent.API/Program.cs index 979a6b1..c82418f 100644 --- a/CoreAgent.API/Program.cs +++ b/CoreAgent.API/Program.cs @@ -1,5 +1,6 @@ using CoreAgent.API; using CoreAgent.Domain.Contexts; +using CoreAgent.Domain.Interfaces.Network; using CoreAgent.Domain.Models.System; using CoreAgent.Infrastructure.Logging; using Serilog; @@ -13,7 +14,6 @@ try // 第一步:添加所有配置 builder.AddConfigurations(); - // 第二步:创建Startup实例 var startup = builder.CreateStartup(); @@ -30,27 +30,8 @@ try Log.Information("Application startup completed"); - // 注册应用程序关闭事件 - var lifetime = app.Lifetime; - lifetime.ApplicationStopping.Register(() => - { - try - { - CellularNetworkContext.Instance.Dispose(); - Log.Information("蜂窝网络上下文已释放"); - } - catch (Exception ex) - { - Log.Error(ex, "释放蜂窝网络上下文时发生错误"); - } - }); - - lifetime.ApplicationStopped.Register(() => - { - Log.Information("Application has stopped."); - // 确保所有日志都被写入 - Log.CloseAndFlush(); - }); + // 注册应用程序生命周期事件处理器 + app.RegisterApplicationLifetimeHandlers(); app.Run(); } diff --git a/CoreAgent.API/Startup.cs b/CoreAgent.API/Startup.cs index 3e0c362..666cc0e 100644 --- a/CoreAgent.API/Startup.cs +++ b/CoreAgent.API/Startup.cs @@ -6,6 +6,7 @@ using CoreAgent.Infrastructure.Middleware.GlobalException; using CoreAgent.Domain.Contexts; using CoreAgent.Domain.Models.System; using Microsoft.Extensions.Configuration; +using CoreAgent.Domain.Interfaces.Network; namespace CoreAgent.API { @@ -32,13 +33,15 @@ namespace CoreAgent.API // 添加基础设施服务 services.AddInfrastructure(Configuration); - // 添加控制器 services.AddControllers(); // 添加API文档 services.AddEndpointsApiExplorer(); services.AddSwaggerGen(); + + // 添加网络命令配置 + services.Configure(Configuration.GetSection("networkCommand")); } public void Configure(IApplicationBuilder app) @@ -60,21 +63,6 @@ namespace CoreAgent.API { endpoints.MapControllers(); }); - - // 注册应用程序关闭事件 - var lifetime = app.ApplicationServices.GetRequiredService(); - lifetime.ApplicationStopping.Register(() => - { - try - { - CellularNetworkContext.Instance.Dispose(); - Log.Information("蜂窝网络上下文已释放"); - } - catch (Exception ex) - { - Log.Error(ex, "释放蜂窝网络上下文时发生错误"); - } - }); } } @@ -102,9 +90,6 @@ namespace CoreAgent.API .AddJsonFile($"{configurationsDirectory}/netcommand.json", optional: false, reloadOnChange: true) .AddJsonFile($"{configurationsDirectory}/netcommand.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); - var networkCommandConfig = builder.Configuration.GetSection("networkCommand").Get(); - CellularNetworkContext.Instance.Initialize(networkCommandConfig); - // 添加配置 builder.Services.Configure(builder.Configuration); @@ -134,15 +119,42 @@ namespace CoreAgent.API public static void ConfigureSwagger(this WebApplication app) { - //if (app.Environment.IsDevelopment()) - //{ - // app.UseSwagger(); - // app.UseSwaggerUI(); - //} app.UseSwagger(); app.UseSwaggerUI(); } + // 新增:注册应用程序生命周期事件处理器 + public static void RegisterApplicationLifetimeHandlers(this WebApplication app) + { + var lifetime = app.Lifetime; + + // 处理应用程序停止事件 + lifetime.ApplicationStopping.Register(() => + { + try + { + var networkContext = app.Services.GetRequiredService(); + if (networkContext is IDisposable disposable) + { + disposable.Dispose(); + Log.Information("蜂窝网络上下文已释放"); + } + } + catch (Exception ex) + { + Log.Error(ex, "释放蜂窝网络上下文时发生错误"); + } + }); + + // 处理应用程序已停止事件 + lifetime.ApplicationStopped.Register(() => + { + Log.Information("Application has stopped."); + // 确保所有日志都被写入 + Log.CloseAndFlush(); + }); + } + // 新增:创建Startup实例的扩展方法 public static Startup CreateStartup(this WebApplicationBuilder builder) { diff --git a/CoreAgent.Domain/Contexts/CellularNetworkContext.cs b/CoreAgent.Domain/Contexts/CellularNetworkContext.cs index 80cd9d0..e441e4a 100644 --- a/CoreAgent.Domain/Contexts/CellularNetworkContext.cs +++ b/CoreAgent.Domain/Contexts/CellularNetworkContext.cs @@ -1,76 +1,59 @@ using CoreAgent.Domain.Interfaces.Network; +using CoreAgent.Domain.Models.Network; using CoreAgent.Domain.Models.System; +using Microsoft.Extensions.Options; namespace CoreAgent.Domain.Contexts; /// /// 蜂窝网络领域上下文 /// -public class CellularNetworkContext : IDisposable +public class CellularNetworkContext : ICellularNetworkContext, IDisposable { - private static readonly Lazy _instance = new(() => new CellularNetworkContext()); private readonly object _lock = new(); private CellularNetworkState _networkState; - private NetworkCommandConfig _networkCommandConfig; + private readonly NetworkCommandConfig _networkCommandConfig; + private readonly AppSettings _appSettings; private string _neConfigKey = string.Empty; - public CancellationTokenSource token = new CancellationTokenSource(); + private CancellationTokenSource _token; private bool _isDisposed; private bool _isInitialized; /// - /// 获取单例实例 + /// 获取取消令牌源 /// - public static CellularNetworkContext Instance => _instance.Value; + public CancellationTokenSource TokenSource => _token; - private CellularNetworkContext() + public CellularNetworkContext( + IOptions networkCommandConfig, + IOptions appSettings) { _isDisposed = false; _isInitialized = false; + _token = new CancellationTokenSource(); + _networkCommandConfig = networkCommandConfig?.Value ?? throw new ArgumentNullException(nameof(networkCommandConfig)); + _appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings)); } /// /// 初始化上下文 /// - /// 网络命令配置 - public void Initialize(NetworkCommandConfig config = null) + public void Initialize() { - lock (_lock) + if (_isDisposed) { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(CellularNetworkContext)); - } - - if (_isInitialized) - { - return; - } - - _networkState = new CellularNetworkState(_neConfigKey); - _networkCommandConfig = config; - _isInitialized = true; + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } + + if (_isInitialized) + { + return; } - } - /// - /// 设置网络命令配置 - /// - /// 网络命令配置 - public void SetNetworkCommandConfig(NetworkCommandConfig config) - { lock (_lock) { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(CellularNetworkContext)); - } - - if (!_isInitialized) - { - throw new InvalidOperationException("上下文未初始化,请先调用Initialize方法"); - } - - _networkCommandConfig = config ?? throw new ArgumentNullException(nameof(config)); + _networkState = new CellularNetworkState(_neConfigKey); + _isInitialized = true; } } @@ -80,55 +63,67 @@ public class CellularNetworkContext : IDisposable /// 网络命令配置 public NetworkCommandConfig GetNetworkCommandConfig() { - lock (_lock) + if (_isDisposed) { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(CellularNetworkContext)); - } + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } - if (!_isInitialized) - { - throw new InvalidOperationException("上下文未初始化"); - } + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化"); + } + lock (_lock) + { return _networkCommandConfig ?? throw new InvalidOperationException("网络命令配置未设置"); } } + /// + /// 设置网络配置键 + /// + /// 配置键 public string SetNeConfigKey(string key) { - lock (_lock) + if (_isDisposed) { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(CellularNetworkContext)); - } + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } - if (!_isInitialized) - { - throw new InvalidOperationException("上下文未初始化"); - } + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化"); + } - _neConfigKey = key ?? throw new ArgumentNullException(nameof(key)); + if (string.IsNullOrEmpty(key)) + { + throw new ArgumentNullException(nameof(key)); + } + + lock (_lock) + { + _neConfigKey = key; return _neConfigKey; } } + /// + /// 获取网络配置键 + /// public string GetNeConfigKey() { - lock (_lock) + if (_isDisposed) { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(CellularNetworkContext)); - } + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } - if (!_isInitialized) - { - throw new InvalidOperationException("上下文未初始化"); - } + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化"); + } + lock (_lock) + { return _neConfigKey; } } @@ -164,18 +159,18 @@ public class CellularNetworkContext : IDisposable /// 网络状态 public CellularNetworkState GetNetworkState() { - lock (_lock) + if (_isDisposed) { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(CellularNetworkContext)); - } + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } - if (!_isInitialized) - { - throw new InvalidOperationException("上下文未初始化"); - } + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化"); + } + lock (_lock) + { return _networkState ?? throw new InvalidOperationException("网络状态未初始化"); } } @@ -185,129 +180,79 @@ public class CellularNetworkContext : IDisposable /// public void Reset() { - lock (_lock) + if (_isDisposed) { - if (_isDisposed) - { - throw new ObjectDisposedException(nameof(CellularNetworkContext)); - } + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } - if (!_isInitialized) - { - return; - } + if (!_isInitialized) + { + return; + } - token.Cancel(); - token = new CancellationTokenSource(); + lock (_lock) + { + _token.Cancel(); + _token = new CancellationTokenSource(); _networkState = new CellularNetworkState(_neConfigKey); } } /// - /// 释放资源 + /// 取消操作 /// - public void Dispose() + public void Cancel() { if (_isDisposed) { - return; + throw new ObjectDisposedException(nameof(CellularNetworkContext)); } lock (_lock) { - if (_isDisposed) - { - return; - } - - token.Cancel(); - token.Dispose(); - _isInitialized = false; - _isDisposed = true; + _token.Cancel(); } } -} - -/// -/// 蜂窝网络状态 -/// -public class CellularNetworkState -{ - /// - /// 网络接口名称 - /// - public string NeConfigKey { get; } /// - /// 是否已初始化 + /// 获取应用设置 /// - public bool IsInitialized { get; private set; } - - /// - /// 最后启动时间 - /// - public DateTime? LastStartTime { get; private set; } - - /// - /// 最后停止时间 - /// - public DateTime? LastStopTime { get; private set; } - - /// - /// 当前运行状态 - /// - public NetworkStatus CurrentStatus { get; private set; } - - /// - /// 当前网络类型 - /// - public NetworkType CurrentNetworkType { get; private set; } - - - - public CellularNetworkState(string _NeConfigKey) - { - NeConfigKey = _NeConfigKey; - IsInitialized = false; - CurrentStatus = NetworkStatus.Unknown; - } - - /// - /// 更新网络状态 - /// - public void UpdateStatus(NetworkStatus status) + public AppSettings GetAppSettings() { - CurrentStatus = status; - } + if (_isDisposed) + { + throw new ObjectDisposedException(nameof(CellularNetworkContext)); + } + if (!_isInitialized) + { + throw new InvalidOperationException("上下文未初始化"); + } - /// - /// 更新网络类型 - /// - public void UpdateNetworkType(NetworkType type) - { - CurrentNetworkType = type; + return _appSettings; } - /// - /// 标记为已启动 + /// 释放资源 /// - public void MarkAsStarted() + public void Dispose() { - IsInitialized = true; - LastStartTime = DateTime.Now; - CurrentStatus = NetworkStatus.Connected; - } + if (_isDisposed) + { + return; + } - /// - /// 标记为已停止 - /// - public void MarkAsStopped() - { - IsInitialized = false; - LastStopTime = DateTime.Now; - CurrentStatus = NetworkStatus.Disconnected; - CurrentNetworkType = NetworkType.Unknown; + lock (_lock) + { + if (_isDisposed) + { + return; + } + + _token?.Cancel(); + _token?.Dispose(); + _isInitialized = false; + _isDisposed = true; + } } } \ No newline at end of file diff --git a/CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs b/CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs new file mode 100644 index 0000000..edb14db --- /dev/null +++ b/CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs @@ -0,0 +1,67 @@ +using CoreAgent.Domain.Models.Network; +using CoreAgent.Domain.Models.System; + +namespace CoreAgent.Domain.Interfaces.Network; + +/// +/// 蜂窝网络上下文接口 +/// +public interface ICellularNetworkContext +{ + /// + /// 获取取消令牌源 + /// + CancellationTokenSource TokenSource { get; } + + /// + /// 取消操作 + /// + void Cancel(); + + /// + /// 初始化网络上下文 + /// + void Initialize(); + + /// + /// 获取网络命令配置 + /// + NetworkCommandConfig GetNetworkCommandConfig(); + + /// + /// 获取应用设置 + /// + AppSettings GetAppSettings(); + + /// + /// 设置网络配置键 + /// + /// 配置键 + string SetNeConfigKey(string key); + + /// + /// 获取网络配置键 + /// + string GetNeConfigKey(); + + /// + /// 获取指定类型的命令配置 + /// + /// 命令类型 + List GetCommandsByType(NetworkCommandType type); + + /// + /// 获取所有命令类型 + /// + NetworkCommandType[] GetCommandTypes(); + + /// + /// 获取网络状态 + /// + CellularNetworkState GetNetworkState(); + + /// + /// 重置网络上下文 + /// + void Reset(); +} \ No newline at end of file diff --git a/CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs b/CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs index 75697f9..59931a0 100644 --- a/CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs +++ b/CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs @@ -19,118 +19,4 @@ public interface ICellularNetworkService /// /// 停止结果 Task StopAsync(); -} - -/// -/// 网络状态 -/// -public enum NetworkStatus -{ - /// - /// 未知 - /// - Unknown, - - /// - /// 已连接 - /// - Connected, - - /// - /// 未连接 - /// - Disconnected -} - -/// -/// 信号强度 -/// -public enum SignalStrength -{ - /// - /// 无信号 - /// - NoSignal, - - /// - /// 弱信号 - /// - Weak, - - /// - /// 中等信号 - /// - Medium, - - /// - /// 强信号 - /// - Strong -} - -/// -/// 网络类型 -/// -public enum NetworkType -{ - /// - /// 未知 - /// - Unknown, - - /// - /// 4G网络 - /// - LTE, - - /// - /// 5G网络 - /// - NR, - - /// - /// 4+5 G网络 - /// - LTE_NR, -} - -/// -/// 蜂窝网络全局状态 -/// -public class CellularNetworkGlobalStatus -{ - /// - /// 是否已初始化 - /// - public bool IsInitialized { get; set; } - - /// - /// 最后启动时间 - /// - public DateTime? LastStartTime { get; set; } - - /// - /// 最后停止时间 - /// - public DateTime? LastStopTime { get; set; } - - /// - /// 当前运行状态 - /// - public NetworkStatus CurrentStatus { get; set; } - - /// - /// 当前信号强度 - /// - public SignalStrength CurrentSignalStrength { get; set; } - - /// - /// 当前网络类型 - /// - public NetworkType CurrentNetworkType { get; set; } - - /// - /// 当前发射功率 - /// - public int CurrentTransmitPower { get; set; } -} \ No newline at end of file +} \ No newline at end of file diff --git a/CoreAgent.Domain/Models/Network/CellularNetworkState.cs b/CoreAgent.Domain/Models/Network/CellularNetworkState.cs new file mode 100644 index 0000000..4949bda --- /dev/null +++ b/CoreAgent.Domain/Models/Network/CellularNetworkState.cs @@ -0,0 +1,84 @@ +using CoreAgent.Domain.Models.System; + +namespace CoreAgent.Domain.Models.Network; + +/// +/// 蜂窝网络状态 +/// +public class CellularNetworkState +{ + /// + /// 网络接口名称 + /// + public string NeConfigKey { get; } + + /// + /// 是否已初始化 + /// + public bool IsInitialized { get; private set; } + + /// + /// 最后启动时间 + /// + public DateTime? LastStartTime { get; private set; } + + /// + /// 最后停止时间 + /// + public DateTime? LastStopTime { get; private set; } + + /// + /// 当前运行状态 + /// + public NetworkStatus CurrentStatus { get; private set; } + + /// + /// 当前网络类型 + /// + public NetworkType CurrentNetworkType { get; private set; } + + public CellularNetworkState(string neConfigKey) + { + NeConfigKey = neConfigKey ?? throw new ArgumentNullException(nameof(neConfigKey)); + IsInitialized = false; + CurrentStatus = NetworkStatus.Unknown; + CurrentNetworkType = NetworkType.Unknown; + } + + /// + /// 更新网络状态 + /// + public void UpdateStatus(NetworkStatus status) + { + CurrentStatus = status; + } + + /// + /// 更新网络类型 + /// + public void UpdateNetworkType(NetworkType type) + { + CurrentNetworkType = type; + } + + /// + /// 标记为已启动 + /// + public void MarkAsStarted() + { + IsInitialized = true; + LastStartTime = DateTime.Now; + CurrentStatus = NetworkStatus.Connected; + } + + /// + /// 标记为已停止 + /// + public void MarkAsStopped() + { + IsInitialized = false; + LastStopTime = DateTime.Now; + CurrentStatus = NetworkStatus.Disconnected; + CurrentNetworkType = NetworkType.Unknown; + } +} \ No newline at end of file diff --git a/CoreAgent.Domain/Models/Network/NetworkEnums.cs b/CoreAgent.Domain/Models/Network/NetworkEnums.cs new file mode 100644 index 0000000..abf5bf7 --- /dev/null +++ b/CoreAgent.Domain/Models/Network/NetworkEnums.cs @@ -0,0 +1,48 @@ +namespace CoreAgent.Domain.Models.Network; + +/// +/// 网络状态 +/// +public enum NetworkStatus +{ + /// + /// 未知 + /// + Unknown, + + /// + /// 已连接 + /// + Connected, + + /// + /// 未连接 + /// + Disconnected +} + +/// +/// 网络类型 +/// +public enum NetworkType +{ + /// + /// 未知 + /// + Unknown, + + /// + /// 4G网络 + /// + LTE, + + /// + /// 5G网络 + /// + NR, + + /// + /// 4+5 G网络 + /// + LTE_NR +} \ No newline at end of file diff --git a/CoreAgent.Infrastructure/Extensions/ServiceCollection/CommandServiceExtensions.cs b/CoreAgent.Infrastructure/Extensions/ServiceCollection/CommandServiceExtensions.cs index 3383a48..200bc4b 100644 --- a/CoreAgent.Infrastructure/Extensions/ServiceCollection/CommandServiceExtensions.cs +++ b/CoreAgent.Infrastructure/Extensions/ServiceCollection/CommandServiceExtensions.cs @@ -1,3 +1,4 @@ +using CoreAgent.Domain.Contexts; using CoreAgent.Domain.Interfaces; using CoreAgent.Domain.Interfaces.Network; using CoreAgent.Domain.Interfaces.System.Command; @@ -21,6 +22,7 @@ public static class CommandServiceExtensions /// 服务集合 public static IServiceCollection AddCommandCustomService(this IServiceCollection services) { + services.AddSingleton(); // 注册命令执行器工厂 services.AddSingleton(); diff --git a/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs b/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs index 5636a9f..29b98f2 100644 --- a/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs +++ b/CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs @@ -4,6 +4,7 @@ using CoreAgent.Domain.Entities; using CoreAgent.Domain.Interfaces; using CoreAgent.Domain.Interfaces.Network; using CoreAgent.Domain.Interfaces.System.Command; +using CoreAgent.Domain.Models.Network; using CoreAgent.Domain.Models.System; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -19,8 +20,7 @@ public class CellularNetworkService : ICellularNetworkService private readonly ILogger _logger; private readonly ISystemCommandExecutor _commandExecutor; private readonly INetworkConfigurationService _configService; - private readonly CellularNetworkContext _context; - private readonly AppSettings _appSettings; + private readonly ICellularNetworkContext _context; private static readonly SemaphoreSlim _startLock = new(1, 1); private const int MaxConnectionAttempts = 30; private const int ConnectionCheckDelayMs = 1000; @@ -32,13 +32,12 @@ public class CellularNetworkService : ICellularNetworkService ILogger logger, ISystemCommandExecutor commandExecutor, INetworkConfigurationService configService, - IOptions appSettings) + ICellularNetworkContext context) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _commandExecutor = commandExecutor ?? throw new ArgumentNullException(nameof(commandExecutor)); _configService = configService ?? throw new ArgumentNullException(nameof(configService)); - _appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings)); - _context = CellularNetworkContext.Instance; + _context = context ?? throw new ArgumentNullException(nameof(context)); } public async Task StartAsync(string key) @@ -57,20 +56,27 @@ public class CellularNetworkService : ICellularNetworkService return false; } - try + // 初始化网络上下文 + _context.Initialize(); + var result = await StartInternalAsync(key); + if (!result) { - return await StartInternalAsync(key); - } - finally - { - _startLock.Release(); + _logger.LogWarning("启动蜂窝网络内部操作失败,重置上下文"); + _context.Reset(); } + return result; } catch (Exception ex) { - _logger.LogError(ex, "启动蜂窝网络接口失败"); + _logger.LogError(ex, "启动蜂窝网络失败"); + // 重置上下文 + _context.Reset(); return false; } + finally + { + _startLock.Release(); + } } @@ -116,7 +122,6 @@ public class CellularNetworkService : ICellularNetworkService } // 5. 更新状态 - state.MarkAsStopped(); _logger.LogInformation($"蜂窝网络 {NeConfigKey} 停止成功"); // 6. 重置上下文 @@ -280,7 +285,7 @@ public class CellularNetworkService : ICellularNetworkService // 复制 RAG 配置文件 if (!string.IsNullOrEmpty(networkConfig.RagConfig)) { - if (!CopyConfigFile(networkConfig.RagConfig, _appSettings.RanConfigDirectory, + if (!CopyConfigFile(networkConfig.RagConfig, _context.GetAppSettings().RanConfigDirectory, path => networkConfig.RagConfig = path, "RAG")) { return false; @@ -292,7 +297,7 @@ public class CellularNetworkService : ICellularNetworkService { if (!string.IsNullOrEmpty(config.CoreNetworkConfig)) { - if (!CopyConfigFile(config.CoreNetworkConfig, _appSettings.MmeConfigDirectory, + if (!CopyConfigFile(config.CoreNetworkConfig, _context.GetAppSettings().MmeConfigDirectory, path => config.CoreNetworkConfig = path, "核心网络")) { return false; @@ -301,7 +306,7 @@ public class CellularNetworkService : ICellularNetworkService if (!string.IsNullOrEmpty(config.ImsConfig)) { - if (!CopyConfigFile(config.ImsConfig, _appSettings.MmeConfigDirectory, + if (!CopyConfigFile(config.ImsConfig, _context.GetAppSettings().MmeConfigDirectory, path => config.ImsConfig = path, "IMS")) { return false; @@ -320,22 +325,24 @@ public class CellularNetworkService : ICellularNetworkService private void EnsureDirectoriesExist() { - if (!Directory.Exists(_appSettings.TempDirectory)) + var appSettings = _context.GetAppSettings(); + if (!Directory.Exists(appSettings.TempDirectory)) { - Directory.CreateDirectory(_appSettings.TempDirectory); + Directory.CreateDirectory(appSettings.TempDirectory); } - if (!Directory.Exists(_appSettings.RanConfigDirectory)) + if (!Directory.Exists(appSettings.RanConfigDirectory)) { - Directory.CreateDirectory(_appSettings.RanConfigDirectory); + Directory.CreateDirectory(appSettings.RanConfigDirectory); } - if (!Directory.Exists(_appSettings.MmeConfigDirectory)) + if (!Directory.Exists(appSettings.MmeConfigDirectory)) { - Directory.CreateDirectory(_appSettings.MmeConfigDirectory); + Directory.CreateDirectory(appSettings.MmeConfigDirectory); } } private bool CopyConfigFile(string sourcePath, string targetDirectory, Action updatePath, string configType) { + var appSettings = _context.GetAppSettings(); if (!File.Exists(sourcePath)) { _logger.LogError("{ConfigType}配置文件不存在: {FilePath}", configType, sourcePath); @@ -343,7 +350,7 @@ public class CellularNetworkService : ICellularNetworkService } var fileName = Path.GetFileName(sourcePath); - var tempPath = Path.Combine(_appSettings.TempDirectory, fileName); + var tempPath = Path.Combine(appSettings.TempDirectory, fileName); // 始终复制到临时目录 File.Copy(sourcePath, tempPath, true); @@ -394,7 +401,7 @@ public class CellularNetworkService : ICellularNetworkService var fullCommand = $"{command} {networkConfig.RagConfig}"; _logger.LogInformation("执行RAG配置启动命令: {Command}", fullCommand); - var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.token); + var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, new CancellationTokenSource()); return result.IsSuccess; } @@ -412,7 +419,7 @@ public class CellularNetworkService : ICellularNetworkService var fullCommand = $"{command} {NULL_CONFIG} {config.CoreNetworkConfig} {config.ImsConfig}"; _logger.LogInformation("并发执行次要配置启动命令: {Command}", fullCommand); - secondaryTasks.Add(_commandExecutor.ExecuteCommandAsync(fullCommand, _context.token)); + secondaryTasks.Add(_commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource)); } // 等待所有次要配置命令执行完成 var secondaryResults = await Task.WhenAll(secondaryTasks); @@ -431,7 +438,7 @@ public class CellularNetworkService : ICellularNetworkService var fullCommand = $"{command} {networkConfig.RagConfig} {config.CoreNetworkConfig} {config.ImsConfig}"; _logger.LogInformation("执行单配置启动命令: {Command}", fullCommand); - var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.token); + var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource); return result.IsSuccess; } @@ -450,7 +457,7 @@ public class CellularNetworkService : ICellularNetworkService var fullCommand = $"{command} NULL {config.CoreNetworkConfig} {config.ImsConfig}"; _logger.LogInformation("并发执行次要配置启动命令: {Command}", fullCommand); - secondaryTasks.Add(_commandExecutor.ExecuteCommandAsync(fullCommand, _context.token)); + secondaryTasks.Add(_commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource)); } // 等待所有次要配置命令执行完成 @@ -469,7 +476,7 @@ public class CellularNetworkService : ICellularNetworkService var fullCommand = $"{primaryCommand} {networkConfig.RagConfig} {primaryConfig.CoreNetworkConfig} {primaryConfig.ImsConfig}"; _logger.LogInformation("执行主配置启动命令: {Command}", fullCommand); - var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.token); + var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource); if (!result.IsSuccess) { _logger.LogWarning("主配置命令执行失败: {Command}", fullCommand);