Browse Source

refactor: 优化CellularNetworkContext和CellularNetworkService的配置管理和错误处理

master
root 3 days ago
parent
commit
60c22c4805
  1. 25
      CoreAgent.API/Program.cs
  2. 60
      CoreAgent.API/Startup.cs
  3. 193
      CoreAgent.Domain/Contexts/CellularNetworkContext.cs
  4. 67
      CoreAgent.Domain/Interfaces/Network/ICellularNetworkContext.cs
  5. 114
      CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs
  6. 84
      CoreAgent.Domain/Models/Network/CellularNetworkState.cs
  7. 48
      CoreAgent.Domain/Models/Network/NetworkEnums.cs
  8. 2
      CoreAgent.Infrastructure/Extensions/ServiceCollection/CommandServiceExtensions.cs
  9. 63
      CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs

25
CoreAgent.API/Program.cs

@ -1,5 +1,6 @@
using CoreAgent.API; using CoreAgent.API;
using CoreAgent.Domain.Contexts; using CoreAgent.Domain.Contexts;
using CoreAgent.Domain.Interfaces.Network;
using CoreAgent.Domain.Models.System; using CoreAgent.Domain.Models.System;
using CoreAgent.Infrastructure.Logging; using CoreAgent.Infrastructure.Logging;
using Serilog; using Serilog;
@ -13,7 +14,6 @@ try
// 第一步:添加所有配置 // 第一步:添加所有配置
builder.AddConfigurations(); builder.AddConfigurations();
// 第二步:创建Startup实例 // 第二步:创建Startup实例
var startup = builder.CreateStartup(); var startup = builder.CreateStartup();
@ -30,27 +30,8 @@ try
Log.Information("Application startup completed"); Log.Information("Application startup completed");
// 注册应用程序关闭事件 // 注册应用程序生命周期事件处理器
var lifetime = app.Lifetime; app.RegisterApplicationLifetimeHandlers();
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.Run(); app.Run();
} }

60
CoreAgent.API/Startup.cs

@ -6,6 +6,7 @@ using CoreAgent.Infrastructure.Middleware.GlobalException;
using CoreAgent.Domain.Contexts; using CoreAgent.Domain.Contexts;
using CoreAgent.Domain.Models.System; using CoreAgent.Domain.Models.System;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using CoreAgent.Domain.Interfaces.Network;
namespace CoreAgent.API namespace CoreAgent.API
{ {
@ -32,13 +33,15 @@ namespace CoreAgent.API
// 添加基础设施服务 // 添加基础设施服务
services.AddInfrastructure(Configuration); services.AddInfrastructure(Configuration);
// 添加控制器 // 添加控制器
services.AddControllers(); services.AddControllers();
// 添加API文档 // 添加API文档
services.AddEndpointsApiExplorer(); services.AddEndpointsApiExplorer();
services.AddSwaggerGen(); services.AddSwaggerGen();
// 添加网络命令配置
services.Configure<NetworkCommandConfig>(Configuration.GetSection("networkCommand"));
} }
public void Configure(IApplicationBuilder app) public void Configure(IApplicationBuilder app)
@ -60,21 +63,6 @@ namespace CoreAgent.API
{ {
endpoints.MapControllers(); endpoints.MapControllers();
}); });
// 注册应用程序关闭事件
var lifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();
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.json", optional: false, reloadOnChange: true)
.AddJsonFile($"{configurationsDirectory}/netcommand.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); .AddJsonFile($"{configurationsDirectory}/netcommand.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
var networkCommandConfig = builder.Configuration.GetSection("networkCommand").Get<NetworkCommandConfig>();
CellularNetworkContext.Instance.Initialize(networkCommandConfig);
// 添加配置 // 添加配置
builder.Services.Configure<AppSettings>(builder.Configuration); builder.Services.Configure<AppSettings>(builder.Configuration);
@ -134,15 +119,42 @@ namespace CoreAgent.API
public static void ConfigureSwagger(this WebApplication app) public static void ConfigureSwagger(this WebApplication app)
{ {
//if (app.Environment.IsDevelopment())
//{
// app.UseSwagger();
// app.UseSwaggerUI();
//}
app.UseSwagger(); app.UseSwagger();
app.UseSwaggerUI(); app.UseSwaggerUI();
} }
// 新增:注册应用程序生命周期事件处理器
public static void RegisterApplicationLifetimeHandlers(this WebApplication app)
{
var lifetime = app.Lifetime;
// 处理应用程序停止事件
lifetime.ApplicationStopping.Register(() =>
{
try
{
var networkContext = app.Services.GetRequiredService<ICellularNetworkContext>();
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实例的扩展方法 // 新增:创建Startup实例的扩展方法
public static Startup CreateStartup(this WebApplicationBuilder builder) public static Startup CreateStartup(this WebApplicationBuilder builder)
{ {

193
CoreAgent.Domain/Contexts/CellularNetworkContext.cs

@ -1,40 +1,44 @@
using CoreAgent.Domain.Interfaces.Network; using CoreAgent.Domain.Interfaces.Network;
using CoreAgent.Domain.Models.Network;
using CoreAgent.Domain.Models.System; using CoreAgent.Domain.Models.System;
using Microsoft.Extensions.Options;
namespace CoreAgent.Domain.Contexts; namespace CoreAgent.Domain.Contexts;
/// <summary> /// <summary>
/// 蜂窝网络领域上下文 /// 蜂窝网络领域上下文
/// </summary> /// </summary>
public class CellularNetworkContext : IDisposable public class CellularNetworkContext : ICellularNetworkContext, IDisposable
{ {
private static readonly Lazy<CellularNetworkContext> _instance = new(() => new CellularNetworkContext());
private readonly object _lock = new(); private readonly object _lock = new();
private CellularNetworkState _networkState; private CellularNetworkState _networkState;
private NetworkCommandConfig _networkCommandConfig; private readonly NetworkCommandConfig _networkCommandConfig;
private readonly AppSettings _appSettings;
private string _neConfigKey = string.Empty; private string _neConfigKey = string.Empty;
public CancellationTokenSource token = new CancellationTokenSource(); private CancellationTokenSource _token;
private bool _isDisposed; private bool _isDisposed;
private bool _isInitialized; private bool _isInitialized;
/// <summary> /// <summary>
/// 获取单例实例 /// 获取取消令牌源
/// </summary> /// </summary>
public static CellularNetworkContext Instance => _instance.Value; public CancellationTokenSource TokenSource => _token;
private CellularNetworkContext() public CellularNetworkContext(
IOptions<NetworkCommandConfig> networkCommandConfig,
IOptions<AppSettings> appSettings)
{ {
_isDisposed = false; _isDisposed = false;
_isInitialized = false; _isInitialized = false;
_token = new CancellationTokenSource();
_networkCommandConfig = networkCommandConfig?.Value ?? throw new ArgumentNullException(nameof(networkCommandConfig));
_appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings));
} }
/// <summary> /// <summary>
/// 初始化上下文 /// 初始化上下文
/// </summary> /// </summary>
/// <param name="config">网络命令配置</param> public void Initialize()
public void Initialize(NetworkCommandConfig config = null)
{
lock (_lock)
{ {
if (_isDisposed) if (_isDisposed)
{ {
@ -46,31 +50,10 @@ public class CellularNetworkContext : IDisposable
return; return;
} }
_networkState = new CellularNetworkState(_neConfigKey);
_networkCommandConfig = config;
_isInitialized = true;
}
}
/// <summary>
/// 设置网络命令配置
/// </summary>
/// <param name="config">网络命令配置</param>
public void SetNetworkCommandConfig(NetworkCommandConfig config)
{
lock (_lock) lock (_lock)
{ {
if (_isDisposed) _networkState = new CellularNetworkState(_neConfigKey);
{ _isInitialized = true;
throw new ObjectDisposedException(nameof(CellularNetworkContext));
}
if (!_isInitialized)
{
throw new InvalidOperationException("上下文未初始化,请先调用Initialize方法");
}
_networkCommandConfig = config ?? throw new ArgumentNullException(nameof(config));
} }
} }
@ -79,8 +62,6 @@ public class CellularNetworkContext : IDisposable
/// </summary> /// </summary>
/// <returns>网络命令配置</returns> /// <returns>网络命令配置</returns>
public NetworkCommandConfig GetNetworkCommandConfig() public NetworkCommandConfig GetNetworkCommandConfig()
{
lock (_lock)
{ {
if (_isDisposed) if (_isDisposed)
{ {
@ -92,13 +73,17 @@ public class CellularNetworkContext : IDisposable
throw new InvalidOperationException("上下文未初始化"); throw new InvalidOperationException("上下文未初始化");
} }
lock (_lock)
{
return _networkCommandConfig ?? throw new InvalidOperationException("网络命令配置未设置"); return _networkCommandConfig ?? throw new InvalidOperationException("网络命令配置未设置");
} }
} }
/// <summary>
/// 设置网络配置键
/// </summary>
/// <param name="key">配置键</param>
public string SetNeConfigKey(string key) public string SetNeConfigKey(string key)
{
lock (_lock)
{ {
if (_isDisposed) if (_isDisposed)
{ {
@ -110,14 +95,22 @@ public class CellularNetworkContext : IDisposable
throw new InvalidOperationException("上下文未初始化"); 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; return _neConfigKey;
} }
} }
/// <summary>
/// 获取网络配置键
/// </summary>
public string GetNeConfigKey() public string GetNeConfigKey()
{
lock (_lock)
{ {
if (_isDisposed) if (_isDisposed)
{ {
@ -129,6 +122,8 @@ public class CellularNetworkContext : IDisposable
throw new InvalidOperationException("上下文未初始化"); throw new InvalidOperationException("上下文未初始化");
} }
lock (_lock)
{
return _neConfigKey; return _neConfigKey;
} }
} }
@ -163,8 +158,6 @@ public class CellularNetworkContext : IDisposable
/// </summary> /// </summary>
/// <returns>网络状态</returns> /// <returns>网络状态</returns>
public CellularNetworkState GetNetworkState() public CellularNetworkState GetNetworkState()
{
lock (_lock)
{ {
if (_isDisposed) if (_isDisposed)
{ {
@ -176,6 +169,8 @@ public class CellularNetworkContext : IDisposable
throw new InvalidOperationException("上下文未初始化"); throw new InvalidOperationException("上下文未初始化");
} }
lock (_lock)
{
return _networkState ?? throw new InvalidOperationException("网络状态未初始化"); return _networkState ?? throw new InvalidOperationException("网络状态未初始化");
} }
} }
@ -184,8 +179,6 @@ public class CellularNetworkContext : IDisposable
/// 重置上下文状态 /// 重置上下文状态
/// </summary> /// </summary>
public void Reset() public void Reset()
{
lock (_lock)
{ {
if (_isDisposed) if (_isDisposed)
{ {
@ -197,117 +190,69 @@ public class CellularNetworkContext : IDisposable
return; return;
} }
token.Cancel(); lock (_lock)
token = new CancellationTokenSource(); {
_token.Cancel();
_token = new CancellationTokenSource();
_networkState = new CellularNetworkState(_neConfigKey); _networkState = new CellularNetworkState(_neConfigKey);
} }
} }
/// <summary> /// <summary>
/// 释放资源 /// 取消操作
/// </summary> /// </summary>
public void Dispose() public void Cancel()
{ {
if (_isDisposed) if (_isDisposed)
{ {
return; throw new ObjectDisposedException(nameof(CellularNetworkContext));
} }
lock (_lock) lock (_lock)
{ {
if (_isDisposed) _token.Cancel();
{
return;
} }
token.Cancel();
token.Dispose();
_isInitialized = false;
_isDisposed = true;
} }
}
}
/// <summary>
/// 蜂窝网络状态
/// </summary>
public class CellularNetworkState
{
/// <summary>
/// 网络接口名称
/// </summary>
public string NeConfigKey { get; }
/// <summary> /// <summary>
/// 是否已初始化 /// 获取应用设置
/// </summary> /// </summary>
public bool IsInitialized { get; private set; } public AppSettings GetAppSettings()
/// <summary>
/// 最后启动时间
/// </summary>
public DateTime? LastStartTime { get; private set; }
/// <summary>
/// 最后停止时间
/// </summary>
public DateTime? LastStopTime { get; private set; }
/// <summary>
/// 当前运行状态
/// </summary>
public NetworkStatus CurrentStatus { get; private set; }
/// <summary>
/// 当前网络类型
/// </summary>
public NetworkType CurrentNetworkType { get; private set; }
public CellularNetworkState(string _NeConfigKey)
{ {
NeConfigKey = _NeConfigKey; if (_isDisposed)
IsInitialized = false; {
CurrentStatus = NetworkStatus.Unknown; throw new ObjectDisposedException(nameof(CellularNetworkContext));
} }
/// <summary> if (!_isInitialized)
/// 更新网络状态
/// </summary>
public void UpdateStatus(NetworkStatus status)
{ {
CurrentStatus = status; throw new InvalidOperationException("上下文未初始化");
} }
return _appSettings;
}
/// <summary> /// <summary>
/// 更新网络类型 /// 释放资源
/// </summary> /// </summary>
public void UpdateNetworkType(NetworkType type) public void Dispose()
{ {
CurrentNetworkType = type; if (_isDisposed)
{
return;
} }
lock (_lock)
/// <summary>
/// 标记为已启动
/// </summary>
public void MarkAsStarted()
{ {
IsInitialized = true; if (_isDisposed)
LastStartTime = DateTime.Now; {
CurrentStatus = NetworkStatus.Connected; return;
} }
/// <summary> _token?.Cancel();
/// 标记为已停止 _token?.Dispose();
/// </summary> _isInitialized = false;
public void MarkAsStopped() _isDisposed = true;
{ }
IsInitialized = false;
LastStopTime = DateTime.Now;
CurrentStatus = NetworkStatus.Disconnected;
CurrentNetworkType = NetworkType.Unknown;
} }
} }

67
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;
/// <summary>
/// 蜂窝网络上下文接口
/// </summary>
public interface ICellularNetworkContext
{
/// <summary>
/// 获取取消令牌源
/// </summary>
CancellationTokenSource TokenSource { get; }
/// <summary>
/// 取消操作
/// </summary>
void Cancel();
/// <summary>
/// 初始化网络上下文
/// </summary>
void Initialize();
/// <summary>
/// 获取网络命令配置
/// </summary>
NetworkCommandConfig GetNetworkCommandConfig();
/// <summary>
/// 获取应用设置
/// </summary>
AppSettings GetAppSettings();
/// <summary>
/// 设置网络配置键
/// </summary>
/// <param name="key">配置键</param>
string SetNeConfigKey(string key);
/// <summary>
/// 获取网络配置键
/// </summary>
string GetNeConfigKey();
/// <summary>
/// 获取指定类型的命令配置
/// </summary>
/// <param name="type">命令类型</param>
List<CommandTemplateConfig> GetCommandsByType(NetworkCommandType type);
/// <summary>
/// 获取所有命令类型
/// </summary>
NetworkCommandType[] GetCommandTypes();
/// <summary>
/// 获取网络状态
/// </summary>
CellularNetworkState GetNetworkState();
/// <summary>
/// 重置网络上下文
/// </summary>
void Reset();
}

114
CoreAgent.Domain/Interfaces/Network/ICellularNetworkService.cs

@ -20,117 +20,3 @@ public interface ICellularNetworkService
/// <returns>停止结果</returns> /// <returns>停止结果</returns>
Task<bool> StopAsync(); Task<bool> StopAsync();
} }
/// <summary>
/// 网络状态
/// </summary>
public enum NetworkStatus
{
/// <summary>
/// 未知
/// </summary>
Unknown,
/// <summary>
/// 已连接
/// </summary>
Connected,
/// <summary>
/// 未连接
/// </summary>
Disconnected
}
/// <summary>
/// 信号强度
/// </summary>
public enum SignalStrength
{
/// <summary>
/// 无信号
/// </summary>
NoSignal,
/// <summary>
/// 弱信号
/// </summary>
Weak,
/// <summary>
/// 中等信号
/// </summary>
Medium,
/// <summary>
/// 强信号
/// </summary>
Strong
}
/// <summary>
/// 网络类型
/// </summary>
public enum NetworkType
{
/// <summary>
/// 未知
/// </summary>
Unknown,
/// <summary>
/// 4G网络
/// </summary>
LTE,
/// <summary>
/// 5G网络
/// </summary>
NR,
/// <summary>
/// 4+5 G网络
/// </summary>
LTE_NR,
}
/// <summary>
/// 蜂窝网络全局状态
/// </summary>
public class CellularNetworkGlobalStatus
{
/// <summary>
/// 是否已初始化
/// </summary>
public bool IsInitialized { get; set; }
/// <summary>
/// 最后启动时间
/// </summary>
public DateTime? LastStartTime { get; set; }
/// <summary>
/// 最后停止时间
/// </summary>
public DateTime? LastStopTime { get; set; }
/// <summary>
/// 当前运行状态
/// </summary>
public NetworkStatus CurrentStatus { get; set; }
/// <summary>
/// 当前信号强度
/// </summary>
public SignalStrength CurrentSignalStrength { get; set; }
/// <summary>
/// 当前网络类型
/// </summary>
public NetworkType CurrentNetworkType { get; set; }
/// <summary>
/// 当前发射功率
/// </summary>
public int CurrentTransmitPower { get; set; }
}

84
CoreAgent.Domain/Models/Network/CellularNetworkState.cs

@ -0,0 +1,84 @@
using CoreAgent.Domain.Models.System;
namespace CoreAgent.Domain.Models.Network;
/// <summary>
/// 蜂窝网络状态
/// </summary>
public class CellularNetworkState
{
/// <summary>
/// 网络接口名称
/// </summary>
public string NeConfigKey { get; }
/// <summary>
/// 是否已初始化
/// </summary>
public bool IsInitialized { get; private set; }
/// <summary>
/// 最后启动时间
/// </summary>
public DateTime? LastStartTime { get; private set; }
/// <summary>
/// 最后停止时间
/// </summary>
public DateTime? LastStopTime { get; private set; }
/// <summary>
/// 当前运行状态
/// </summary>
public NetworkStatus CurrentStatus { get; private set; }
/// <summary>
/// 当前网络类型
/// </summary>
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;
}
/// <summary>
/// 更新网络状态
/// </summary>
public void UpdateStatus(NetworkStatus status)
{
CurrentStatus = status;
}
/// <summary>
/// 更新网络类型
/// </summary>
public void UpdateNetworkType(NetworkType type)
{
CurrentNetworkType = type;
}
/// <summary>
/// 标记为已启动
/// </summary>
public void MarkAsStarted()
{
IsInitialized = true;
LastStartTime = DateTime.Now;
CurrentStatus = NetworkStatus.Connected;
}
/// <summary>
/// 标记为已停止
/// </summary>
public void MarkAsStopped()
{
IsInitialized = false;
LastStopTime = DateTime.Now;
CurrentStatus = NetworkStatus.Disconnected;
CurrentNetworkType = NetworkType.Unknown;
}
}

48
CoreAgent.Domain/Models/Network/NetworkEnums.cs

@ -0,0 +1,48 @@
namespace CoreAgent.Domain.Models.Network;
/// <summary>
/// 网络状态
/// </summary>
public enum NetworkStatus
{
/// <summary>
/// 未知
/// </summary>
Unknown,
/// <summary>
/// 已连接
/// </summary>
Connected,
/// <summary>
/// 未连接
/// </summary>
Disconnected
}
/// <summary>
/// 网络类型
/// </summary>
public enum NetworkType
{
/// <summary>
/// 未知
/// </summary>
Unknown,
/// <summary>
/// 4G网络
/// </summary>
LTE,
/// <summary>
/// 5G网络
/// </summary>
NR,
/// <summary>
/// 4+5 G网络
/// </summary>
LTE_NR
}

2
CoreAgent.Infrastructure/Extensions/ServiceCollection/CommandServiceExtensions.cs

@ -1,3 +1,4 @@
using CoreAgent.Domain.Contexts;
using CoreAgent.Domain.Interfaces; using CoreAgent.Domain.Interfaces;
using CoreAgent.Domain.Interfaces.Network; using CoreAgent.Domain.Interfaces.Network;
using CoreAgent.Domain.Interfaces.System.Command; using CoreAgent.Domain.Interfaces.System.Command;
@ -21,6 +22,7 @@ public static class CommandServiceExtensions
/// <returns>服务集合</returns> /// <returns>服务集合</returns>
public static IServiceCollection AddCommandCustomService(this IServiceCollection services) public static IServiceCollection AddCommandCustomService(this IServiceCollection services)
{ {
services.AddSingleton<ICellularNetworkContext, CellularNetworkContext>();
// 注册命令执行器工厂 // 注册命令执行器工厂
services.AddSingleton<ISystemCommandExecutorFactory, SystemCommandExecutorFactory>(); services.AddSingleton<ISystemCommandExecutorFactory, SystemCommandExecutorFactory>();

63
CoreAgent.Infrastructure/Services/Network/CellularNetworkService.cs

@ -4,6 +4,7 @@ using CoreAgent.Domain.Entities;
using CoreAgent.Domain.Interfaces; using CoreAgent.Domain.Interfaces;
using CoreAgent.Domain.Interfaces.Network; using CoreAgent.Domain.Interfaces.Network;
using CoreAgent.Domain.Interfaces.System.Command; using CoreAgent.Domain.Interfaces.System.Command;
using CoreAgent.Domain.Models.Network;
using CoreAgent.Domain.Models.System; using CoreAgent.Domain.Models.System;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@ -19,8 +20,7 @@ public class CellularNetworkService : ICellularNetworkService
private readonly ILogger<CellularNetworkService> _logger; private readonly ILogger<CellularNetworkService> _logger;
private readonly ISystemCommandExecutor _commandExecutor; private readonly ISystemCommandExecutor _commandExecutor;
private readonly INetworkConfigurationService _configService; private readonly INetworkConfigurationService _configService;
private readonly CellularNetworkContext _context; private readonly ICellularNetworkContext _context;
private readonly AppSettings _appSettings;
private static readonly SemaphoreSlim _startLock = new(1, 1); private static readonly SemaphoreSlim _startLock = new(1, 1);
private const int MaxConnectionAttempts = 30; private const int MaxConnectionAttempts = 30;
private const int ConnectionCheckDelayMs = 1000; private const int ConnectionCheckDelayMs = 1000;
@ -32,13 +32,12 @@ public class CellularNetworkService : ICellularNetworkService
ILogger<CellularNetworkService> logger, ILogger<CellularNetworkService> logger,
ISystemCommandExecutor commandExecutor, ISystemCommandExecutor commandExecutor,
INetworkConfigurationService configService, INetworkConfigurationService configService,
IOptions<AppSettings> appSettings) ICellularNetworkContext context)
{ {
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); _logger = logger ?? throw new ArgumentNullException(nameof(logger));
_commandExecutor = commandExecutor ?? throw new ArgumentNullException(nameof(commandExecutor)); _commandExecutor = commandExecutor ?? throw new ArgumentNullException(nameof(commandExecutor));
_configService = configService ?? throw new ArgumentNullException(nameof(configService)); _configService = configService ?? throw new ArgumentNullException(nameof(configService));
_appSettings = appSettings?.Value ?? throw new ArgumentNullException(nameof(appSettings)); _context = context ?? throw new ArgumentNullException(nameof(context));
_context = CellularNetworkContext.Instance;
} }
public async Task<bool> StartAsync(string key) public async Task<bool> StartAsync(string key)
@ -57,20 +56,27 @@ public class CellularNetworkService : ICellularNetworkService
return false; return false;
} }
try // 初始化网络上下文
{ _context.Initialize();
return await StartInternalAsync(key); var result = await StartInternalAsync(key);
} if (!result)
finally
{ {
_startLock.Release(); _logger.LogWarning("启动蜂窝网络内部操作失败,重置上下文");
_context.Reset();
} }
return result;
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "启动蜂窝网络接口失败"); _logger.LogError(ex, "启动蜂窝网络失败");
// 重置上下文
_context.Reset();
return false; return false;
} }
finally
{
_startLock.Release();
}
} }
@ -116,7 +122,6 @@ public class CellularNetworkService : ICellularNetworkService
} }
// 5. 更新状态 // 5. 更新状态
state.MarkAsStopped();
_logger.LogInformation($"蜂窝网络 {NeConfigKey} 停止成功"); _logger.LogInformation($"蜂窝网络 {NeConfigKey} 停止成功");
// 6. 重置上下文 // 6. 重置上下文
@ -280,7 +285,7 @@ public class CellularNetworkService : ICellularNetworkService
// 复制 RAG 配置文件 // 复制 RAG 配置文件
if (!string.IsNullOrEmpty(networkConfig.RagConfig)) if (!string.IsNullOrEmpty(networkConfig.RagConfig))
{ {
if (!CopyConfigFile(networkConfig.RagConfig, _appSettings.RanConfigDirectory, if (!CopyConfigFile(networkConfig.RagConfig, _context.GetAppSettings().RanConfigDirectory,
path => networkConfig.RagConfig = path, "RAG")) path => networkConfig.RagConfig = path, "RAG"))
{ {
return false; return false;
@ -292,7 +297,7 @@ public class CellularNetworkService : ICellularNetworkService
{ {
if (!string.IsNullOrEmpty(config.CoreNetworkConfig)) if (!string.IsNullOrEmpty(config.CoreNetworkConfig))
{ {
if (!CopyConfigFile(config.CoreNetworkConfig, _appSettings.MmeConfigDirectory, if (!CopyConfigFile(config.CoreNetworkConfig, _context.GetAppSettings().MmeConfigDirectory,
path => config.CoreNetworkConfig = path, "核心网络")) path => config.CoreNetworkConfig = path, "核心网络"))
{ {
return false; return false;
@ -301,7 +306,7 @@ public class CellularNetworkService : ICellularNetworkService
if (!string.IsNullOrEmpty(config.ImsConfig)) if (!string.IsNullOrEmpty(config.ImsConfig))
{ {
if (!CopyConfigFile(config.ImsConfig, _appSettings.MmeConfigDirectory, if (!CopyConfigFile(config.ImsConfig, _context.GetAppSettings().MmeConfigDirectory,
path => config.ImsConfig = path, "IMS")) path => config.ImsConfig = path, "IMS"))
{ {
return false; return false;
@ -320,22 +325,24 @@ public class CellularNetworkService : ICellularNetworkService
private void EnsureDirectoriesExist() 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<string> updatePath, string configType) private bool CopyConfigFile(string sourcePath, string targetDirectory, Action<string> updatePath, string configType)
{ {
var appSettings = _context.GetAppSettings();
if (!File.Exists(sourcePath)) if (!File.Exists(sourcePath))
{ {
_logger.LogError("{ConfigType}配置文件不存在: {FilePath}", configType, sourcePath); _logger.LogError("{ConfigType}配置文件不存在: {FilePath}", configType, sourcePath);
@ -343,7 +350,7 @@ public class CellularNetworkService : ICellularNetworkService
} }
var fileName = Path.GetFileName(sourcePath); var fileName = Path.GetFileName(sourcePath);
var tempPath = Path.Combine(_appSettings.TempDirectory, fileName); var tempPath = Path.Combine(appSettings.TempDirectory, fileName);
// 始终复制到临时目录 // 始终复制到临时目录
File.Copy(sourcePath, tempPath, true); File.Copy(sourcePath, tempPath, true);
@ -394,7 +401,7 @@ public class CellularNetworkService : ICellularNetworkService
var fullCommand = $"{command} {networkConfig.RagConfig}"; var fullCommand = $"{command} {networkConfig.RagConfig}";
_logger.LogInformation("执行RAG配置启动命令: {Command}", fullCommand); _logger.LogInformation("执行RAG配置启动命令: {Command}", fullCommand);
var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.token); var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, new CancellationTokenSource());
return result.IsSuccess; return result.IsSuccess;
} }
@ -412,7 +419,7 @@ public class CellularNetworkService : ICellularNetworkService
var fullCommand = $"{command} {NULL_CONFIG} {config.CoreNetworkConfig} {config.ImsConfig}"; var fullCommand = $"{command} {NULL_CONFIG} {config.CoreNetworkConfig} {config.ImsConfig}";
_logger.LogInformation("并发执行次要配置启动命令: {Command}", fullCommand); _logger.LogInformation("并发执行次要配置启动命令: {Command}", fullCommand);
secondaryTasks.Add(_commandExecutor.ExecuteCommandAsync(fullCommand, _context.token)); secondaryTasks.Add(_commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource));
} }
// 等待所有次要配置命令执行完成 // 等待所有次要配置命令执行完成
var secondaryResults = await Task.WhenAll(secondaryTasks); var secondaryResults = await Task.WhenAll(secondaryTasks);
@ -431,7 +438,7 @@ public class CellularNetworkService : ICellularNetworkService
var fullCommand = $"{command} {networkConfig.RagConfig} {config.CoreNetworkConfig} {config.ImsConfig}"; var fullCommand = $"{command} {networkConfig.RagConfig} {config.CoreNetworkConfig} {config.ImsConfig}";
_logger.LogInformation("执行单配置启动命令: {Command}", fullCommand); _logger.LogInformation("执行单配置启动命令: {Command}", fullCommand);
var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.token); var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource);
return result.IsSuccess; return result.IsSuccess;
} }
@ -450,7 +457,7 @@ public class CellularNetworkService : ICellularNetworkService
var fullCommand = $"{command} NULL {config.CoreNetworkConfig} {config.ImsConfig}"; var fullCommand = $"{command} NULL {config.CoreNetworkConfig} {config.ImsConfig}";
_logger.LogInformation("并发执行次要配置启动命令: {Command}", fullCommand); _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}"; var fullCommand = $"{primaryCommand} {networkConfig.RagConfig} {primaryConfig.CoreNetworkConfig} {primaryConfig.ImsConfig}";
_logger.LogInformation("执行主配置启动命令: {Command}", fullCommand); _logger.LogInformation("执行主配置启动命令: {Command}", fullCommand);
var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.token); var result = await _commandExecutor.ExecuteCommandAsync(fullCommand, _context.TokenSource);
if (!result.IsSuccess) if (!result.IsSuccess)
{ {
_logger.LogWarning("主配置命令执行失败: {Command}", fullCommand); _logger.LogWarning("主配置命令执行失败: {Command}", fullCommand);

Loading…
Cancel
Save