18 changed files with 1046 additions and 434 deletions
@ -0,0 +1,62 @@ |
|||||
|
{ |
||||
|
"NetworkCommand": { |
||||
|
"DefaultRetryCount": 3, |
||||
|
"DefaultRetryInterval": 1000, |
||||
|
"NetworkCommands": [ |
||||
|
{ |
||||
|
"type": 1, |
||||
|
"template": "network init", |
||||
|
"timeout": 30000, |
||||
|
"isEnabled": true |
||||
|
}, |
||||
|
{ |
||||
|
"type": 1, |
||||
|
"template": "network check", |
||||
|
"timeout": 15000, |
||||
|
"isEnabled": true |
||||
|
}, |
||||
|
{ |
||||
|
"type": 1, |
||||
|
"template": "network verify", |
||||
|
"timeout": 20000, |
||||
|
"isEnabled": true |
||||
|
}, |
||||
|
{ |
||||
|
"type": 2, |
||||
|
"template": "network start", |
||||
|
"timeout": 25000, |
||||
|
"isEnabled": true |
||||
|
}, |
||||
|
{ |
||||
|
"type": 2, |
||||
|
"template": "network resume", |
||||
|
"timeout": 20000, |
||||
|
"isEnabled": true |
||||
|
}, |
||||
|
{ |
||||
|
"type": 3, |
||||
|
"template": "network stop", |
||||
|
"timeout": 8000, |
||||
|
"isEnabled": true |
||||
|
}, |
||||
|
{ |
||||
|
"type": 3, |
||||
|
"template": "network cleanup", |
||||
|
"timeout": 5000, |
||||
|
"isEnabled": true |
||||
|
}, |
||||
|
{ |
||||
|
"type": 4, |
||||
|
"template": "network status", |
||||
|
"timeout": 5000, |
||||
|
"isEnabled": true |
||||
|
}, |
||||
|
{ |
||||
|
"type": 4, |
||||
|
"template": "network info", |
||||
|
"timeout": 5000, |
||||
|
"isEnabled": true |
||||
|
} |
||||
|
] |
||||
|
} |
||||
|
} |
@ -0,0 +1,238 @@ |
|||||
|
using CoreAgent.Domain.Interfaces.Network; |
||||
|
using CoreAgent.Domain.Models.Network; |
||||
|
using CoreAgent.Domain.Models.System; |
||||
|
|
||||
|
namespace CoreAgent.Domain.Contexts; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 蜂窝网络领域上下文
|
||||
|
/// </summary>
|
||||
|
public class CellularNetworkContext |
||||
|
{ |
||||
|
private static readonly Lazy<CellularNetworkContext> _instance = new(() => new CellularNetworkContext()); |
||||
|
private readonly object _lock = new(); |
||||
|
private readonly Dictionary<string, CellularNetworkState> _networkStates = new(); |
||||
|
private NetworkCommandConfig _networkCommandConfig; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取单例实例
|
||||
|
/// </summary>
|
||||
|
public static CellularNetworkContext Instance => _instance.Value; |
||||
|
|
||||
|
private CellularNetworkContext() { } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 设置网络命令配置
|
||||
|
/// </summary>
|
||||
|
/// <param name="config">网络命令配置</param>
|
||||
|
public void SetNetworkCommandConfig(NetworkCommandConfig config) |
||||
|
{ |
||||
|
lock (_lock) |
||||
|
{ |
||||
|
_networkCommandConfig = config ?? throw new ArgumentNullException(nameof(config)); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取网络命令配置
|
||||
|
/// </summary>
|
||||
|
/// <returns>网络命令配置</returns>
|
||||
|
public NetworkCommandConfig GetNetworkCommandConfig() |
||||
|
{ |
||||
|
lock (_lock) |
||||
|
{ |
||||
|
return _networkCommandConfig ?? throw new InvalidOperationException("网络命令配置未初始化"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取指定类型的命令配置
|
||||
|
/// </summary>
|
||||
|
/// <param name="type">命令类型</param>
|
||||
|
/// <returns>命令配置列表</returns>
|
||||
|
public List<CommandTemplateConfig> GetCommandsByType(NetworkCommandType type) |
||||
|
{ |
||||
|
lock (_lock) |
||||
|
{ |
||||
|
return _networkCommandConfig?.GetCommandsByType(type) ?? new List<CommandTemplateConfig>(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取所有命令类型
|
||||
|
/// </summary>
|
||||
|
/// <returns>命令类型数组</returns>
|
||||
|
public NetworkCommandType[] GetCommandTypes() |
||||
|
{ |
||||
|
lock (_lock) |
||||
|
{ |
||||
|
return _networkCommandConfig?.GetCommandTypes() ?? Array.Empty<NetworkCommandType>(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取或创建网络状态
|
||||
|
/// </summary>
|
||||
|
/// <param name="interfaceName">网络接口名称</param>
|
||||
|
/// <returns>网络状态</returns>
|
||||
|
public CellularNetworkState GetOrCreateNetworkState(string interfaceName) |
||||
|
{ |
||||
|
lock (_lock) |
||||
|
{ |
||||
|
if (!_networkStates.TryGetValue(interfaceName, out var state)) |
||||
|
{ |
||||
|
state = new CellularNetworkState(interfaceName); |
||||
|
_networkStates[interfaceName] = state; |
||||
|
} |
||||
|
return state; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 移除网络状态
|
||||
|
/// </summary>
|
||||
|
/// <param name="interfaceName">网络接口名称</param>
|
||||
|
public void RemoveNetworkState(string interfaceName) |
||||
|
{ |
||||
|
lock (_lock) |
||||
|
{ |
||||
|
_networkStates.Remove(interfaceName); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取所有网络状态
|
||||
|
/// </summary>
|
||||
|
/// <returns>所有网络状态的集合</returns>
|
||||
|
public IReadOnlyCollection<CellularNetworkState> GetAllNetworkStates() |
||||
|
{ |
||||
|
lock (_lock) |
||||
|
{ |
||||
|
return _networkStates.Values.ToList().AsReadOnly(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 蜂窝网络状态
|
||||
|
/// </summary>
|
||||
|
public class CellularNetworkState |
||||
|
{ |
||||
|
/// <summary>
|
||||
|
/// 网络接口名称
|
||||
|
/// </summary>
|
||||
|
public string InterfaceName { 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 SignalStrength CurrentSignalStrength { get; private set; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 当前网络类型
|
||||
|
/// </summary>
|
||||
|
public NetworkType CurrentNetworkType { get; private set; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 当前发射功率
|
||||
|
/// </summary>
|
||||
|
public int CurrentTransmitPower { get; private set; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 网络配置
|
||||
|
/// </summary>
|
||||
|
public CellularNetworkConfig Config { get; private set; } |
||||
|
|
||||
|
public CellularNetworkState(string interfaceName) |
||||
|
{ |
||||
|
InterfaceName = interfaceName; |
||||
|
IsInitialized = false; |
||||
|
CurrentStatus = NetworkStatus.Unknown; |
||||
|
CurrentSignalStrength = SignalStrength.NoSignal; |
||||
|
CurrentNetworkType = NetworkType.Unknown; |
||||
|
CurrentTransmitPower = 0; |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 更新网络状态
|
||||
|
/// </summary>
|
||||
|
public void UpdateStatus(NetworkStatus status) |
||||
|
{ |
||||
|
CurrentStatus = status; |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 更新信号强度
|
||||
|
/// </summary>
|
||||
|
public void UpdateSignalStrength(SignalStrength strength) |
||||
|
{ |
||||
|
CurrentSignalStrength = strength; |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 更新网络类型
|
||||
|
/// </summary>
|
||||
|
public void UpdateNetworkType(NetworkType type) |
||||
|
{ |
||||
|
CurrentNetworkType = type; |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 更新发射功率
|
||||
|
/// </summary>
|
||||
|
public void UpdateTransmitPower(int power) |
||||
|
{ |
||||
|
CurrentTransmitPower = power; |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 更新网络配置
|
||||
|
/// </summary>
|
||||
|
public void UpdateConfig(CellularNetworkConfig config) |
||||
|
{ |
||||
|
Config = config; |
||||
|
} |
||||
|
|
||||
|
/// <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; |
||||
|
CurrentSignalStrength = SignalStrength.NoSignal; |
||||
|
CurrentNetworkType = NetworkType.Unknown; |
||||
|
CurrentTransmitPower = 0; |
||||
|
} |
||||
|
} |
@ -0,0 +1,25 @@ |
|||||
|
using CoreAgent.Domain.Models.Network; |
||||
|
|
||||
|
namespace CoreAgent.Domain.Interfaces.Network; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 网络配置器接口
|
||||
|
/// </summary>
|
||||
|
public interface INetworkConfigurator |
||||
|
{ |
||||
|
/// <summary>
|
||||
|
/// 配置网络参数
|
||||
|
/// </summary>
|
||||
|
/// <param name="interfaceName">网络接口名称</param>
|
||||
|
/// <param name="config">网络配置</param>
|
||||
|
/// <returns>配置结果</returns>
|
||||
|
Task<bool> ConfigureAsync(string interfaceName, CellularNetworkConfig config); |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 设置发射功率
|
||||
|
/// </summary>
|
||||
|
/// <param name="interfaceName">网络接口名称</param>
|
||||
|
/// <param name="powerLevel">功率等级(0-100)</param>
|
||||
|
/// <returns>设置结果</returns>
|
||||
|
Task<bool> SetTransmitPowerAsync(string interfaceName, int powerLevel); |
||||
|
} |
@ -0,0 +1,36 @@ |
|||||
|
using CoreAgent.Domain.Models.Network; |
||||
|
|
||||
|
namespace CoreAgent.Domain.Interfaces.Network; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 网络状态提供者接口
|
||||
|
/// </summary>
|
||||
|
public interface INetworkStatusProvider |
||||
|
{ |
||||
|
/// <summary>
|
||||
|
/// 获取网络状态
|
||||
|
/// </summary>
|
||||
|
/// <param name="interfaceName">网络接口名称</param>
|
||||
|
/// <returns>网络状态信息</returns>
|
||||
|
Task<NetworkStatus> GetNetworkStatusAsync(string interfaceName); |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取信号强度
|
||||
|
/// </summary>
|
||||
|
/// <param name="interfaceName">网络接口名称</param>
|
||||
|
/// <returns>信号强度信息</returns>
|
||||
|
Task<SignalStrength> GetSignalStrengthAsync(string interfaceName); |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取网络类型
|
||||
|
/// </summary>
|
||||
|
/// <param name="interfaceName">网络接口名称</param>
|
||||
|
/// <returns>网络类型信息</returns>
|
||||
|
Task<NetworkType> GetNetworkTypeAsync(string interfaceName); |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取全局状态
|
||||
|
/// </summary>
|
||||
|
/// <returns>全局状态信息</returns>
|
||||
|
Task<CellularNetworkGlobalStatus> GetGlobalStatusAsync(); |
||||
|
} |
@ -0,0 +1,33 @@ |
|||||
|
using System.Text.Json.Serialization; |
||||
|
|
||||
|
namespace CoreAgent.Domain.Models.System; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 命令模板配置
|
||||
|
/// </summary>
|
||||
|
public class CommandTemplateConfig |
||||
|
{ |
||||
|
/// <summary>
|
||||
|
/// 命令类型
|
||||
|
/// </summary>
|
||||
|
[JsonPropertyName("type")] |
||||
|
public NetworkCommandType Type { get; set; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 命令模板
|
||||
|
/// </summary>
|
||||
|
[JsonPropertyName("template")] |
||||
|
public string Template { get; set; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 超时时间(毫秒)
|
||||
|
/// </summary>
|
||||
|
[JsonPropertyName("timeout")] |
||||
|
public int Timeout { get; set; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 是否启用
|
||||
|
/// </summary>
|
||||
|
[JsonPropertyName("isEnabled")] |
||||
|
public bool IsEnabled { get; set; } = true; |
||||
|
} |
@ -0,0 +1,46 @@ |
|||||
|
using System.Text.Json.Serialization; |
||||
|
|
||||
|
namespace CoreAgent.Domain.Models.System; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 网络命令配置
|
||||
|
/// </summary>
|
||||
|
public class NetworkCommandConfig |
||||
|
{ |
||||
|
/// <summary>
|
||||
|
/// 默认重试次数
|
||||
|
/// </summary>
|
||||
|
[JsonPropertyName("DefaultRetryCount")] |
||||
|
public int DefaultRetryCount { get; set; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 默认重试间隔(毫秒)
|
||||
|
/// </summary>
|
||||
|
[JsonPropertyName("DefaultRetryInterval")] |
||||
|
public int DefaultRetryInterval { get; set; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 网络命令配置列表
|
||||
|
/// </summary>
|
||||
|
[JsonPropertyName("NetworkCommands")] |
||||
|
public List<CommandTemplateConfig> NetworkCommands { get; set; } |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取指定类型的命令配置
|
||||
|
/// </summary>
|
||||
|
/// <param name="type">命令类型</param>
|
||||
|
/// <returns>命令配置列表</returns>
|
||||
|
public List<CommandTemplateConfig> GetCommandsByType(NetworkCommandType type) |
||||
|
{ |
||||
|
return NetworkCommands?.Where(c => c.Type == type).ToList() ?? new List<CommandTemplateConfig>(); |
||||
|
} |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 获取所有命令类型
|
||||
|
/// </summary>
|
||||
|
/// <returns>命令类型数组</returns>
|
||||
|
public NetworkCommandType[] GetCommandTypes() |
||||
|
{ |
||||
|
return NetworkCommands?.Select(c => c.Type).Distinct().ToArray() ?? Array.Empty<NetworkCommandType>(); |
||||
|
} |
||||
|
} |
@ -0,0 +1,27 @@ |
|||||
|
namespace CoreAgent.Domain.Models.System; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 网络命令类型
|
||||
|
/// </summary>
|
||||
|
public enum NetworkCommandType |
||||
|
{ |
||||
|
/// <summary>
|
||||
|
/// 初始化命令
|
||||
|
/// </summary>
|
||||
|
Initialize = 1, |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 启动命令
|
||||
|
/// </summary>
|
||||
|
Start = 2, |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 停止命令
|
||||
|
/// </summary>
|
||||
|
Stop = 3, |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 状态命令
|
||||
|
/// </summary>
|
||||
|
Status = 4 |
||||
|
} |
@ -1,380 +0,0 @@ |
|||||
using CoreAgent.Domain.Interfaces.Network; |
|
||||
using CoreAgent.Domain.Interfaces.System.Command; |
|
||||
using CoreAgent.Domain.Models.Network; |
|
||||
using CoreAgent.Domain.Models.System; |
|
||||
using CoreAgent.Infrastructure.Command.Factories; |
|
||||
using Microsoft.Extensions.Logging; |
|
||||
using System.Diagnostics; |
|
||||
|
|
||||
namespace CoreAgent.Infrastructure.Services; |
|
||||
|
|
||||
/// <summary>
|
|
||||
/// 蜂窝网络服务实现
|
|
||||
/// </summary>
|
|
||||
public class CellularNetworkService : ICellularNetworkService |
|
||||
{ |
|
||||
private readonly ILogger<CellularNetworkService> _logger; |
|
||||
private readonly CellularNetworkGlobalStatus _globalStatus; |
|
||||
private readonly ISystemCommandExecutorFactory _commandExecutorFactory; |
|
||||
private static readonly SemaphoreSlim _startLock = new SemaphoreSlim(1, 1); |
|
||||
|
|
||||
public CellularNetworkService( |
|
||||
ILogger<CellularNetworkService> logger, |
|
||||
ISystemCommandExecutorFactory commandExecutorFactory) |
|
||||
{ |
|
||||
_logger = logger; |
|
||||
_commandExecutorFactory = commandExecutorFactory; |
|
||||
_globalStatus = new CellularNetworkGlobalStatus |
|
||||
{ |
|
||||
IsInitialized = false, |
|
||||
CurrentStatus = NetworkStatus.Unknown, |
|
||||
CurrentSignalStrength = SignalStrength.NoSignal, |
|
||||
CurrentNetworkType = NetworkType.Unknown, |
|
||||
CurrentTransmitPower = 0 |
|
||||
}; |
|
||||
} |
|
||||
|
|
||||
public async Task<bool> StartAsync(string interfaceName, CellularNetworkConfig config) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
// 使用信号量确保只能启动一次
|
|
||||
if (!await _startLock.WaitAsync(TimeSpan.FromSeconds(5))) |
|
||||
{ |
|
||||
_logger.LogWarning("蜂窝网络启动操作被锁定,可能已有其他启动操作正在进行"); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
try |
|
||||
{ |
|
||||
if (_globalStatus.IsInitialized) |
|
||||
{ |
|
||||
_logger.LogWarning("蜂窝网络已经初始化,不能重复启动"); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
_logger.LogInformation("正在启动蜂窝网络接口: {InterfaceName}", interfaceName); |
|
||||
|
|
||||
// 1. 配置网络参数
|
|
||||
var configResult = await ConfigureNetworkAsync(interfaceName, config); |
|
||||
if (!configResult) |
|
||||
{ |
|
||||
_logger.LogError("配置蜂窝网络参数失败"); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
// 2. 启动网络接口
|
|
||||
var startResult = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" admin=enable"); |
|
||||
if (!startResult) |
|
||||
{ |
|
||||
_logger.LogError("启动蜂窝网络接口失败"); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
// 3. 等待网络连接
|
|
||||
var connected = await WaitForConnectionAsync(interfaceName); |
|
||||
if (!connected) |
|
||||
{ |
|
||||
_logger.LogError("蜂窝网络连接超时"); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
// 4. 更新全局状态
|
|
||||
_globalStatus.IsInitialized = true; |
|
||||
_globalStatus.LastStartTime = DateTime.Now; |
|
||||
_globalStatus.CurrentStatus = NetworkStatus.Connected; |
|
||||
_globalStatus.CurrentSignalStrength = await GetSignalStrengthAsync(interfaceName); |
|
||||
_globalStatus.CurrentNetworkType = await GetNetworkTypeAsync(interfaceName); |
|
||||
|
|
||||
_logger.LogInformation("蜂窝网络接口 {InterfaceName} 启动成功", interfaceName); |
|
||||
return true; |
|
||||
} |
|
||||
finally |
|
||||
{ |
|
||||
_startLock.Release(); |
|
||||
} |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
_logger.LogError(ex, "启动蜂窝网络接口 {InterfaceName} 失败", interfaceName); |
|
||||
return false; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async Task<bool> StopAsync(string interfaceName) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
if (!_globalStatus.IsInitialized) |
|
||||
{ |
|
||||
_logger.LogWarning("蜂窝网络未初始化,无需停止"); |
|
||||
return true; |
|
||||
} |
|
||||
|
|
||||
_logger.LogInformation("正在停止蜂窝网络接口: {InterfaceName}", interfaceName); |
|
||||
|
|
||||
// 1. 停止网络接口
|
|
||||
var stopResult = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" admin=disable"); |
|
||||
if (!stopResult) |
|
||||
{ |
|
||||
_logger.LogError("停止蜂窝网络接口失败"); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
// 2. 更新全局状态
|
|
||||
_globalStatus.IsInitialized = false; |
|
||||
_globalStatus.LastStopTime = DateTime.Now; |
|
||||
_globalStatus.CurrentStatus = NetworkStatus.Disconnected; |
|
||||
_globalStatus.CurrentSignalStrength = SignalStrength.NoSignal; |
|
||||
_globalStatus.CurrentNetworkType = NetworkType.Unknown; |
|
||||
_globalStatus.CurrentTransmitPower = 0; |
|
||||
|
|
||||
_logger.LogInformation("蜂窝网络接口 {InterfaceName} 停止成功", interfaceName); |
|
||||
return true; |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
_logger.LogError(ex, "停止蜂窝网络接口 {InterfaceName} 失败", interfaceName); |
|
||||
return false; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async Task<NetworkStatus> GetNetworkStatusAsync(string interfaceName) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
_logger.LogDebug("正在获取蜂窝网络状态: {InterfaceName}", interfaceName); |
|
||||
var result = await ExecuteCommandWithResultAsync($"netsh interface cellular show interfaces \"{interfaceName}\""); |
|
||||
|
|
||||
if (!result.IsSuccess) |
|
||||
{ |
|
||||
_logger.LogError("获取蜂窝网络状态失败: {Error}", result.Error); |
|
||||
return NetworkStatus.Unknown; |
|
||||
} |
|
||||
|
|
||||
var output = result.Output; |
|
||||
if (output.Contains("已连接", StringComparison.OrdinalIgnoreCase)) |
|
||||
{ |
|
||||
return NetworkStatus.Connected; |
|
||||
} |
|
||||
else if (output.Contains("已断开", StringComparison.OrdinalIgnoreCase)) |
|
||||
{ |
|
||||
return NetworkStatus.Disconnected; |
|
||||
} |
|
||||
|
|
||||
return NetworkStatus.Unknown; |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
_logger.LogError(ex, "获取蜂窝网络状态失败: {InterfaceName}", interfaceName); |
|
||||
return NetworkStatus.Unknown; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async Task<SignalStrength> GetSignalStrengthAsync(string interfaceName) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
_logger.LogDebug("正在获取蜂窝网络信号强度: {InterfaceName}", interfaceName); |
|
||||
var result = await ExecuteCommandWithResultAsync($"netsh interface cellular show interfaces \"{interfaceName}\""); |
|
||||
|
|
||||
if (!result.IsSuccess) |
|
||||
{ |
|
||||
_logger.LogError("获取蜂窝网络信号强度失败: {Error}", result.Error); |
|
||||
return SignalStrength.NoSignal; |
|
||||
} |
|
||||
|
|
||||
var output = result.Output; |
|
||||
if (output.Contains("信号强度: 强", StringComparison.OrdinalIgnoreCase)) |
|
||||
{ |
|
||||
return SignalStrength.Strong; |
|
||||
} |
|
||||
else if (output.Contains("信号强度: 中", StringComparison.OrdinalIgnoreCase)) |
|
||||
{ |
|
||||
return SignalStrength.Medium; |
|
||||
} |
|
||||
else if (output.Contains("信号强度: 弱", StringComparison.OrdinalIgnoreCase)) |
|
||||
{ |
|
||||
return SignalStrength.Weak; |
|
||||
} |
|
||||
|
|
||||
return SignalStrength.NoSignal; |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
_logger.LogError(ex, "获取蜂窝网络信号强度失败: {InterfaceName}", interfaceName); |
|
||||
return SignalStrength.NoSignal; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async Task<NetworkType> GetNetworkTypeAsync(string interfaceName) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
_logger.LogDebug("正在获取蜂窝网络类型: {InterfaceName}", interfaceName); |
|
||||
var result = await ExecuteCommandWithResultAsync($"netsh interface cellular show interfaces \"{interfaceName}\""); |
|
||||
|
|
||||
if (!result.IsSuccess) |
|
||||
{ |
|
||||
_logger.LogError("获取蜂窝网络类型失败: {Error}", result.Error); |
|
||||
return NetworkType.Unknown; |
|
||||
} |
|
||||
|
|
||||
var output = result.Output; |
|
||||
if (output.Contains("5G", StringComparison.OrdinalIgnoreCase)) |
|
||||
{ |
|
||||
return NetworkType.G5; |
|
||||
} |
|
||||
else if (output.Contains("4G", StringComparison.OrdinalIgnoreCase)) |
|
||||
{ |
|
||||
return NetworkType.G4; |
|
||||
} |
|
||||
else if (output.Contains("3G", StringComparison.OrdinalIgnoreCase)) |
|
||||
{ |
|
||||
return NetworkType.G3; |
|
||||
} |
|
||||
else if (output.Contains("2G", StringComparison.OrdinalIgnoreCase)) |
|
||||
{ |
|
||||
return NetworkType.G2; |
|
||||
} |
|
||||
|
|
||||
return NetworkType.Unknown; |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
_logger.LogError(ex, "获取蜂窝网络类型失败: {InterfaceName}", interfaceName); |
|
||||
return NetworkType.Unknown; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public async Task<bool> SetTransmitPowerAsync(string interfaceName, int powerLevel) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
if (!_globalStatus.IsInitialized) |
|
||||
{ |
|
||||
_logger.LogWarning("蜂窝网络未初始化,无法设置发射功率"); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
if (powerLevel < 0 || powerLevel > 100) |
|
||||
{ |
|
||||
_logger.LogWarning("发射功率设置无效: {PowerLevel}", powerLevel); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
_logger.LogInformation("正在设置蜂窝网络发射功率: {InterfaceName}, {PowerLevel}", interfaceName, powerLevel); |
|
||||
|
|
||||
// 设置发射功率
|
|
||||
var result = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" power={powerLevel}"); |
|
||||
if (!result) |
|
||||
{ |
|
||||
_logger.LogError("设置蜂窝网络发射功率失败"); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
_globalStatus.CurrentTransmitPower = powerLevel; |
|
||||
_logger.LogInformation("蜂窝网络发射功率设置成功: {PowerLevel}", powerLevel); |
|
||||
return true; |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
_logger.LogError(ex, "设置蜂窝网络发射功率失败: {InterfaceName}, {PowerLevel}", interfaceName, powerLevel); |
|
||||
return false; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
public Task<CellularNetworkGlobalStatus> GetGlobalStatusAsync() |
|
||||
{ |
|
||||
return Task.FromResult(_globalStatus); |
|
||||
} |
|
||||
|
|
||||
private async Task<bool> ConfigureNetworkAsync(string interfaceName, CellularNetworkConfig config) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
_logger.LogDebug("正在配置蜂窝网络参数: {InterfaceName}", interfaceName); |
|
||||
|
|
||||
// 配置APN
|
|
||||
var apnResult = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" apn=\"{config.Apn}\""); |
|
||||
if (!apnResult) |
|
||||
{ |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
// 配置用户名和密码
|
|
||||
if (!string.IsNullOrEmpty(config.Username) && !string.IsNullOrEmpty(config.Password)) |
|
||||
{ |
|
||||
var authResult = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" username=\"{config.Username}\" password=\"{config.Password}\""); |
|
||||
if (!authResult) |
|
||||
{ |
|
||||
return false; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
return true; |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
_logger.LogError(ex, "配置蜂窝网络参数失败: {InterfaceName}", interfaceName); |
|
||||
return false; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
private async Task<bool> WaitForConnectionAsync(string interfaceName) |
|
||||
{ |
|
||||
const int maxAttempts = 30; |
|
||||
const int delayMs = 1000; |
|
||||
|
|
||||
for (int i = 0; i < maxAttempts; i++) |
|
||||
{ |
|
||||
var status = await GetNetworkStatusAsync(interfaceName); |
|
||||
if (status == NetworkStatus.Connected) |
|
||||
{ |
|
||||
return true; |
|
||||
} |
|
||||
|
|
||||
await Task.Delay(delayMs); |
|
||||
} |
|
||||
|
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
private async Task<bool> ExecuteCommandAsync(string command) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
var executor = _commandExecutorFactory.CreateExecutor(); |
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); |
|
||||
var result = await executor.ExecuteCommandAsync(command, cts); |
|
||||
|
|
||||
if (!result.IsSuccess) |
|
||||
{ |
|
||||
_logger.LogError("命令执行失败: {Command}, 错误: {Error}", command, result.Error); |
|
||||
return false; |
|
||||
} |
|
||||
|
|
||||
return true; |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
_logger.LogError(ex, "执行命令失败: {Command}", command); |
|
||||
return false; |
|
||||
} |
|
||||
} |
|
||||
|
|
||||
private async Task<CommandExecutionResult> ExecuteCommandWithResultAsync(string command) |
|
||||
{ |
|
||||
try |
|
||||
{ |
|
||||
var executor = _commandExecutorFactory.CreateExecutor(); |
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); |
|
||||
return await executor.ExecuteCommandAsync(command, cts); |
|
||||
} |
|
||||
catch (Exception ex) |
|
||||
{ |
|
||||
_logger.LogError(ex, "执行命令失败: {Command}", command); |
|
||||
return CommandExecutionResult.Failure(ex.Message, 0); |
|
||||
} |
|
||||
} |
|
||||
} |
|
@ -0,0 +1 @@ |
|||||
|
|
@ -0,0 +1,110 @@ |
|||||
|
using CoreAgent.Domain.Interfaces.Network; |
||||
|
using CoreAgent.Domain.Interfaces.System.Command; |
||||
|
using CoreAgent.Domain.Models.Network; |
||||
|
using Microsoft.Extensions.Logging; |
||||
|
|
||||
|
namespace CoreAgent.Infrastructure.Services.Network; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 蜂窝网络配置器实现
|
||||
|
/// </summary>
|
||||
|
public class CellularNetworkConfigurator : INetworkConfigurator |
||||
|
{ |
||||
|
private readonly ILogger<CellularNetworkConfigurator> _logger; |
||||
|
private readonly ISystemCommandExecutor _commandExecutor; |
||||
|
|
||||
|
public CellularNetworkConfigurator( |
||||
|
ILogger<CellularNetworkConfigurator> logger, |
||||
|
ISystemCommandExecutor commandExecutor) |
||||
|
{ |
||||
|
_logger = logger; |
||||
|
_commandExecutor = commandExecutor; |
||||
|
} |
||||
|
|
||||
|
public async Task<bool> ConfigureAsync(string interfaceName, CellularNetworkConfig config) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
_logger.LogInformation("正在配置蜂窝网络接口: {InterfaceName}", interfaceName); |
||||
|
|
||||
|
// 1. 配置APN
|
||||
|
if (!string.IsNullOrEmpty(config.Apn)) |
||||
|
{ |
||||
|
var apnResult = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" apn=\"{config.Apn}\""); |
||||
|
if (!apnResult) |
||||
|
{ |
||||
|
_logger.LogError("配置APN失败"); |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 2. 配置认证信息
|
||||
|
if (!string.IsNullOrEmpty(config.Username) && !string.IsNullOrEmpty(config.Password)) |
||||
|
{ |
||||
|
var authResult = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" username=\"{config.Username}\" password=\"{config.Password}\""); |
||||
|
if (!authResult) |
||||
|
{ |
||||
|
_logger.LogError("配置认证信息失败"); |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// 3. 配置网络类型
|
||||
|
//if (config.NetworkType != NetworkType.Auto)
|
||||
|
//{
|
||||
|
// var networkTypeResult = await ExecuteCommandAsync(
|
||||
|
// $"netsh interface cellular set networktype \"{interfaceName}\" " +
|
||||
|
// $"type={(int)config.NetworkType}");
|
||||
|
// if (!networkTypeResult)
|
||||
|
// {
|
||||
|
// _logger.LogError("配置网络类型失败");
|
||||
|
// return false;
|
||||
|
// }
|
||||
|
//}
|
||||
|
|
||||
|
_logger.LogInformation("蜂窝网络接口 {InterfaceName} 配置成功", interfaceName); |
||||
|
return true; |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
_logger.LogError(ex, "配置蜂窝网络接口 {InterfaceName} 失败", interfaceName); |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public async Task<bool> SetTransmitPowerAsync(string interfaceName, int powerLevel) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
if (powerLevel < 0 || powerLevel > 100) |
||||
|
{ |
||||
|
_logger.LogWarning("发射功率设置无效: {PowerLevel}", powerLevel); |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
_logger.LogInformation("正在设置蜂窝网络发射功率: {InterfaceName}, {PowerLevel}", interfaceName, powerLevel); |
||||
|
|
||||
|
// 设置发射功率
|
||||
|
var result = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" power={powerLevel}"); |
||||
|
if (!result) |
||||
|
{ |
||||
|
_logger.LogError("设置蜂窝网络发射功率失败"); |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
_logger.LogInformation("蜂窝网络发射功率设置成功: {PowerLevel}", powerLevel); |
||||
|
return true; |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
_logger.LogError(ex, "设置蜂窝网络发射功率失败: {InterfaceName}, {PowerLevel}", interfaceName, powerLevel); |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private async Task<bool> ExecuteCommandAsync(string command) |
||||
|
{ |
||||
|
var result = await _commandExecutor.ExecuteCommandAsync(command, new CancellationTokenSource()); |
||||
|
return result.IsSuccess; |
||||
|
} |
||||
|
} |
@ -0,0 +1,162 @@ |
|||||
|
using CoreAgent.Domain.Contexts; |
||||
|
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; |
||||
|
|
||||
|
namespace CoreAgent.Infrastructure.Services.Network; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 蜂窝网络服务实现
|
||||
|
/// </summary>
|
||||
|
public class CellularNetworkService : ICellularNetworkService |
||||
|
{ |
||||
|
private readonly ILogger<CellularNetworkService> _logger; |
||||
|
private readonly ISystemCommandExecutor _commandExecutor; |
||||
|
private readonly INetworkConfigurator _configurator; |
||||
|
private readonly CellularNetworkContext _context; |
||||
|
private static readonly SemaphoreSlim _startLock = new(1, 1); |
||||
|
|
||||
|
public CellularNetworkService( |
||||
|
ILogger<CellularNetworkService> logger, |
||||
|
ISystemCommandExecutor commandExecutor, |
||||
|
INetworkConfigurator configurator) |
||||
|
{ |
||||
|
_logger = logger; |
||||
|
_commandExecutor = commandExecutor; |
||||
|
_configurator = configurator; |
||||
|
_context = CellularNetworkContext.Instance; |
||||
|
} |
||||
|
|
||||
|
public async Task<bool> StartAsync(string interfaceName, CellularNetworkConfig config) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
// 使用信号量确保只能启动一次
|
||||
|
if (!await _startLock.WaitAsync(TimeSpan.FromSeconds(5))) |
||||
|
{ |
||||
|
_logger.LogWarning("蜂窝网络启动操作被锁定,可能已有其他启动操作正在进行"); |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
try |
||||
|
{ |
||||
|
var commands = _context.GetNetworkCommandConfig(); |
||||
|
|
||||
|
var state = _context.GetOrCreateNetworkState(interfaceName); |
||||
|
if (state.IsInitialized) |
||||
|
{ |
||||
|
_logger.LogWarning("蜂窝网络已经初始化,不能重复启动"); |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
_logger.LogInformation("正在启动蜂窝网络接口: {InterfaceName}", interfaceName); |
||||
|
|
||||
|
// 1. 配置网络参数
|
||||
|
var configResult = await _configurator.ConfigureAsync(interfaceName, config); |
||||
|
if (!configResult) |
||||
|
{ |
||||
|
_logger.LogError("配置蜂窝网络参数失败"); |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
// 2. 启动网络接口
|
||||
|
var startResult = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" admin=enable"); |
||||
|
if (!startResult) |
||||
|
{ |
||||
|
_logger.LogError("启动蜂窝网络接口失败"); |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
// 3. 等待网络连接
|
||||
|
var connected = await WaitForConnectionAsync(interfaceName); |
||||
|
if (!connected) |
||||
|
{ |
||||
|
_logger.LogError("蜂窝网络连接超时"); |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
// 4. 更新状态
|
||||
|
state.UpdateConfig(config); |
||||
|
state.MarkAsStarted(); |
||||
|
|
||||
|
_logger.LogInformation("蜂窝网络接口 {InterfaceName} 启动成功", interfaceName); |
||||
|
return true; |
||||
|
} |
||||
|
finally |
||||
|
{ |
||||
|
_startLock.Release(); |
||||
|
} |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
_logger.LogError(ex, "启动蜂窝网络接口 {InterfaceName} 失败", interfaceName); |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public async Task<bool> StopAsync(string interfaceName) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
var state = _context.GetOrCreateNetworkState(interfaceName); |
||||
|
if (!state.IsInitialized) |
||||
|
{ |
||||
|
_logger.LogWarning("蜂窝网络未初始化,无需停止"); |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
_logger.LogInformation("正在停止蜂窝网络接口: {InterfaceName}", interfaceName); |
||||
|
|
||||
|
// 1. 停止网络接口
|
||||
|
var stopResult = await ExecuteCommandAsync($"netsh interface cellular set interface \"{interfaceName}\" admin=disable"); |
||||
|
if (!stopResult) |
||||
|
{ |
||||
|
_logger.LogError("停止蜂窝网络接口失败"); |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
// 2. 更新状态
|
||||
|
state.MarkAsStopped(); |
||||
|
|
||||
|
_logger.LogInformation("蜂窝网络接口 {InterfaceName} 停止成功", interfaceName); |
||||
|
return true; |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
_logger.LogError(ex, "停止蜂窝网络接口 {InterfaceName} 失败", interfaceName); |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private async Task<bool> WaitForConnectionAsync(string interfaceName) |
||||
|
{ |
||||
|
const int maxAttempts = 30; |
||||
|
const int delayMs = 1000; |
||||
|
|
||||
|
for (int i = 0; i < maxAttempts; i++) |
||||
|
{ |
||||
|
var status = await ExecuteCommandWithResultAsync($"netsh interface cellular show interfaces \"{interfaceName}\""); |
||||
|
if (status.IsSuccess && status.Output.Contains("已连接", StringComparison.OrdinalIgnoreCase)) |
||||
|
{ |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
await Task.Delay(delayMs); |
||||
|
} |
||||
|
|
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
private async Task<bool> ExecuteCommandAsync(string command) |
||||
|
{ |
||||
|
var result = await _commandExecutor.ExecuteCommandAsync(command, new CancellationTokenSource()); |
||||
|
return result.IsSuccess; |
||||
|
} |
||||
|
|
||||
|
private async Task<CommandExecutionResult> ExecuteCommandWithResultAsync(string command) |
||||
|
{ |
||||
|
return await _commandExecutor.ExecuteCommandAsync(command, new CancellationTokenSource()); |
||||
|
} |
||||
|
} |
@ -0,0 +1,244 @@ |
|||||
|
using CoreAgent.Domain.Contexts; |
||||
|
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; |
||||
|
|
||||
|
namespace CoreAgent.Infrastructure.Services.Network; |
||||
|
|
||||
|
/// <summary>
|
||||
|
/// 蜂窝网络状态提供者实现
|
||||
|
/// </summary>
|
||||
|
public class CellularNetworkStatusProvider : INetworkStatusProvider |
||||
|
{ |
||||
|
private readonly ILogger<CellularNetworkStatusProvider> _logger; |
||||
|
private readonly ISystemCommandExecutor _commandExecutor; |
||||
|
private readonly CellularNetworkContext _context; |
||||
|
|
||||
|
public CellularNetworkStatusProvider( |
||||
|
ILogger<CellularNetworkStatusProvider> logger, |
||||
|
ISystemCommandExecutor commandExecutor) |
||||
|
{ |
||||
|
_logger = logger; |
||||
|
_commandExecutor = commandExecutor; |
||||
|
_context = CellularNetworkContext.Instance; |
||||
|
} |
||||
|
|
||||
|
public async Task<NetworkStatus> GetNetworkStatusAsync(string interfaceName) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
var result = await ExecuteCommandWithResultAsync($"netsh interface cellular show interfaces \"{interfaceName}\""); |
||||
|
if (!result.IsSuccess) |
||||
|
{ |
||||
|
_logger.LogError("获取蜂窝网络状态失败"); |
||||
|
return NetworkStatus.Unknown; |
||||
|
} |
||||
|
|
||||
|
var state = _context.GetOrCreateNetworkState(interfaceName); |
||||
|
var status = ParseNetworkStatus(result.Output); |
||||
|
state.UpdateStatus(status); |
||||
|
return status; |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
_logger.LogError(ex, "获取蜂窝网络状态失败"); |
||||
|
return NetworkStatus.Unknown; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public async Task<SignalStrength> GetSignalStrengthAsync(string interfaceName) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
var result = await ExecuteCommandWithResultAsync($"netsh interface cellular show interfaces \"{interfaceName}\""); |
||||
|
if (!result.IsSuccess) |
||||
|
{ |
||||
|
_logger.LogError("获取蜂窝网络信号强度失败"); |
||||
|
return SignalStrength.NoSignal; |
||||
|
} |
||||
|
|
||||
|
var state = _context.GetOrCreateNetworkState(interfaceName); |
||||
|
var strength = ParseSignalStrength(result.Output); |
||||
|
state.UpdateSignalStrength(strength); |
||||
|
return strength; |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
_logger.LogError(ex, "获取蜂窝网络信号强度失败"); |
||||
|
return SignalStrength.NoSignal; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public async Task<NetworkType> GetNetworkTypeAsync(string interfaceName) |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
var result = await ExecuteCommandWithResultAsync($"netsh interface cellular show interfaces \"{interfaceName}\""); |
||||
|
if (!result.IsSuccess) |
||||
|
{ |
||||
|
_logger.LogError("获取蜂窝网络类型失败"); |
||||
|
return NetworkType.Unknown; |
||||
|
} |
||||
|
|
||||
|
var state = _context.GetOrCreateNetworkState(interfaceName); |
||||
|
var type = ParseNetworkType(result.Output); |
||||
|
state.UpdateNetworkType(type); |
||||
|
return type; |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
_logger.LogError(ex, "获取蜂窝网络类型失败"); |
||||
|
return NetworkType.Unknown; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public async Task<CellularNetworkGlobalStatus> GetGlobalStatusAsync() |
||||
|
{ |
||||
|
try |
||||
|
{ |
||||
|
var result = await ExecuteCommandWithResultAsync("netsh interface cellular show interfaces"); |
||||
|
if (!result.IsSuccess) |
||||
|
{ |
||||
|
_logger.LogError("获取蜂窝网络全局状态失败"); |
||||
|
return new CellularNetworkGlobalStatus |
||||
|
{ |
||||
|
IsInitialized = false, |
||||
|
CurrentStatus = NetworkStatus.Unknown, |
||||
|
CurrentSignalStrength = SignalStrength.NoSignal, |
||||
|
CurrentNetworkType = NetworkType.Unknown, |
||||
|
CurrentTransmitPower = 0 |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
// 解析所有接口的状态
|
||||
|
var interfaces = ParseInterfaces(result.Output); |
||||
|
foreach (var iface in interfaces) |
||||
|
{ |
||||
|
var state = _context.GetOrCreateNetworkState(iface.Name); |
||||
|
state.UpdateStatus(iface.Status); |
||||
|
state.UpdateSignalStrength(iface.SignalStrength); |
||||
|
state.UpdateNetworkType(iface.NetworkType); |
||||
|
} |
||||
|
|
||||
|
// 聚合所有接口的状态
|
||||
|
var states = _context.GetAllNetworkStates(); |
||||
|
return new CellularNetworkGlobalStatus |
||||
|
{ |
||||
|
IsInitialized = states.Any(s => s.IsInitialized), |
||||
|
LastStartTime = states.Max(s => s.LastStartTime), |
||||
|
LastStopTime = states.Max(s => s.LastStopTime), |
||||
|
CurrentStatus = states.FirstOrDefault()?.CurrentStatus ?? NetworkStatus.Unknown, |
||||
|
CurrentSignalStrength = states.FirstOrDefault()?.CurrentSignalStrength ?? SignalStrength.NoSignal, |
||||
|
CurrentNetworkType = states.FirstOrDefault()?.CurrentNetworkType ?? NetworkType.Unknown, |
||||
|
CurrentTransmitPower = states.FirstOrDefault()?.CurrentTransmitPower ?? 0 |
||||
|
}; |
||||
|
} |
||||
|
catch (Exception ex) |
||||
|
{ |
||||
|
_logger.LogError(ex, "获取蜂窝网络全局状态失败"); |
||||
|
return new CellularNetworkGlobalStatus |
||||
|
{ |
||||
|
IsInitialized = false, |
||||
|
CurrentStatus = NetworkStatus.Unknown, |
||||
|
CurrentSignalStrength = SignalStrength.NoSignal, |
||||
|
CurrentNetworkType = NetworkType.Unknown, |
||||
|
CurrentTransmitPower = 0 |
||||
|
}; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private async Task<CommandExecutionResult> ExecuteCommandWithResultAsync(string command) |
||||
|
{ |
||||
|
return await _commandExecutor.ExecuteCommandAsync(command, new CancellationTokenSource()); |
||||
|
} |
||||
|
|
||||
|
private NetworkStatus ParseNetworkStatus(string output) |
||||
|
{ |
||||
|
if (output.Contains("已连接", StringComparison.OrdinalIgnoreCase)) |
||||
|
return NetworkStatus.Connected; |
||||
|
if (output.Contains("已断开", StringComparison.OrdinalIgnoreCase)) |
||||
|
return NetworkStatus.Disconnected; |
||||
|
return NetworkStatus.Unknown; |
||||
|
} |
||||
|
|
||||
|
private SignalStrength ParseSignalStrength(string output) |
||||
|
{ |
||||
|
if (output.Contains("信号强度: 强", StringComparison.OrdinalIgnoreCase)) |
||||
|
return SignalStrength.Strong; |
||||
|
if (output.Contains("信号强度: 中", StringComparison.OrdinalIgnoreCase)) |
||||
|
return SignalStrength.Medium; |
||||
|
if (output.Contains("信号强度: 弱", StringComparison.OrdinalIgnoreCase)) |
||||
|
return SignalStrength.Weak; |
||||
|
return SignalStrength.NoSignal; |
||||
|
} |
||||
|
|
||||
|
private NetworkType ParseNetworkType(string output) |
||||
|
{ |
||||
|
if (output.Contains("5G", StringComparison.OrdinalIgnoreCase)) |
||||
|
return NetworkType.G5; |
||||
|
if (output.Contains("4G", StringComparison.OrdinalIgnoreCase)) |
||||
|
return NetworkType.G4; |
||||
|
if (output.Contains("3G", StringComparison.OrdinalIgnoreCase)) |
||||
|
return NetworkType.G3; |
||||
|
if (output.Contains("2G", StringComparison.OrdinalIgnoreCase)) |
||||
|
return NetworkType.G2; |
||||
|
return NetworkType.Unknown; |
||||
|
} |
||||
|
|
||||
|
private class InterfaceInfo |
||||
|
{ |
||||
|
public string Name { get; set; } |
||||
|
public NetworkStatus Status { get; set; } |
||||
|
public SignalStrength SignalStrength { get; set; } |
||||
|
public NetworkType NetworkType { get; set; } |
||||
|
} |
||||
|
|
||||
|
private IEnumerable<InterfaceInfo> ParseInterfaces(string output) |
||||
|
{ |
||||
|
var interfaces = new List<InterfaceInfo>(); |
||||
|
var lines = output.Split('\n'); |
||||
|
InterfaceInfo currentInterface = null; |
||||
|
|
||||
|
foreach (var line in lines) |
||||
|
{ |
||||
|
if (line.Contains("接口名称:", StringComparison.OrdinalIgnoreCase)) |
||||
|
{ |
||||
|
if (currentInterface != null) |
||||
|
{ |
||||
|
interfaces.Add(currentInterface); |
||||
|
} |
||||
|
currentInterface = new InterfaceInfo |
||||
|
{ |
||||
|
Name = line.Split(':')[1].Trim(), |
||||
|
Status = NetworkStatus.Unknown, |
||||
|
SignalStrength = SignalStrength.NoSignal, |
||||
|
NetworkType = NetworkType.Unknown |
||||
|
}; |
||||
|
} |
||||
|
else if (currentInterface != null) |
||||
|
{ |
||||
|
if (line.Contains("状态:", StringComparison.OrdinalIgnoreCase)) |
||||
|
{ |
||||
|
currentInterface.Status = ParseNetworkStatus(line); |
||||
|
} |
||||
|
else if (line.Contains("信号强度:", StringComparison.OrdinalIgnoreCase)) |
||||
|
{ |
||||
|
currentInterface.SignalStrength = ParseSignalStrength(line); |
||||
|
} |
||||
|
else if (line.Contains("网络类型:", StringComparison.OrdinalIgnoreCase)) |
||||
|
{ |
||||
|
currentInterface.NetworkType = ParseNetworkType(line); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
if (currentInterface != null) |
||||
|
{ |
||||
|
interfaces.Add(currentInterface); |
||||
|
} |
||||
|
|
||||
|
return interfaces; |
||||
|
} |
||||
|
} |
Loading…
Reference in new issue