Files
KinginfoGateway/src/Admin/ThingsGateway.Admin.Application/Job/Hardware/HardwareJob.cs

162 lines
6.7 KiB
C#
Raw Normal View History

2025-01-24 22:42:26 +08:00
// ------------------------------------------------------------------------------
// 此代码版权声明为全文件覆盖,如有原作者特别声明,会在下方手动补充
// 此代码版权除特别声明外的代码归作者本人Diego所有
// 源代码使用协议遵循本仓库的开源协议及附加协议
// Gitee源代码仓库https://gitee.com/diego2098/ThingsGateway
// Github源代码仓库https://github.com/kimdiego2098/ThingsGateway
// 使用文档https://thingsgateway.cn/
// QQ群605534569
// ------------------------------------------------------------------------------
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Runtime.InteropServices;
using ThingsGateway.Extension;
using ThingsGateway.NewLife;
2025-05-21 16:51:40 +08:00
using ThingsGateway.NewLife.Caching;
2025-01-24 22:42:26 +08:00
using ThingsGateway.NewLife.Threading;
using ThingsGateway.Schedule;
namespace ThingsGateway.Admin.Application;
/// <summary>
/// 获取硬件信息作业任务
/// </summary>
[JobDetail("hardware_log", Description = "获取硬件信息", GroupName = "Hardware", Concurrent = false)]
[PeriodSeconds(30, TriggerId = "trigger_hardware", Description = "获取硬件信息", RunOnStart = true)]
public class HardwareJob : IJob, IHardwareJob
{
private readonly ILogger _logger;
private readonly IStringLocalizer _localizer;
/// <inheritdoc/>
public HardwareJob(ILogger<HardwareJob> logger, IStringLocalizer<HardwareJob> localizer, IOptions<HardwareInfoOptions> options)
2025-01-24 22:42:26 +08:00
{
_logger = logger;
_localizer = localizer;
HardwareInfoOptions = options.Value;
}
#region
/// <summary>
/// 运行信息获取
/// </summary>
public HardwareInfo HardwareInfo { get; } = new();
/// <inheritdoc/>
public HardwareInfoOptions HardwareInfoOptions { get; private set; }
#endregion
2025-05-21 16:51:40 +08:00
private MemoryCache MemoryCache = new() { };
private const string CacheKey = "HistoryHardwareInfo";
2025-01-24 22:42:26 +08:00
/// <inheritdoc/>
public async Task<List<HistoryHardwareInfo>> GetHistoryHardwareInfos()
{
2025-05-21 16:51:40 +08:00
var historyHardwareInfos = MemoryCache.Get<List<HistoryHardwareInfo>>(CacheKey);
if (historyHardwareInfos == null)
{
using var db = DbContext.Db.GetConnectionScopeWithAttr<HistoryHardwareInfo>().CopyNew();
historyHardwareInfos = await db.Queryable<HistoryHardwareInfo>().Where(a => a.Date > DateTime.Now.AddDays(-3)).ToListAsync().ConfigureAwait(false);
MemoryCache.Set(CacheKey, historyHardwareInfos);
}
return historyHardwareInfos;
2025-01-24 22:42:26 +08:00
}
private bool error = false;
private DateTime hisInsertTime = default;
public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
{
if (HardwareInfoOptions.Enable)
{
try
{
if (HardwareInfo.MachineInfo == null)
{
await MachineInfo.RegisterAsync().ConfigureAwait(false);
HardwareInfo.MachineInfo = MachineInfo.Current;
string currentPath = Directory.GetCurrentDirectory();
DriveInfo drive = new(Path.GetPathRoot(currentPath));
HardwareInfoOptions.DaysAgo = Math.Min(Math.Max(HardwareInfoOptions.DaysAgo, 1), 7);
if (HardwareInfoOptions.HistoryInterval < 60000) HardwareInfoOptions.HistoryInterval = 60000;
HardwareInfo.DriveInfo = drive;
HardwareInfo.OsArchitecture = Environment.OSVersion.Platform.ToString() + " " + RuntimeInformation.OSArchitecture.ToString(); // 系统架构
HardwareInfo.FrameworkDescription = RuntimeInformation.FrameworkDescription; // NET框架
HardwareInfo.Environment = App.HostEnvironment.IsDevelopment() ? "Development" : "Production";
HardwareInfo.UUID = HardwareInfo.MachineInfo.UUID;
2025-01-24 22:42:26 +08:00
HardwareInfo.UpdateTime = TimerX.Now.ToDefaultDateTimeFormat();
}
}
catch
{
}
try
{
HardwareInfo.MachineInfo.Refresh();
HardwareInfo.UpdateTime = TimerX.Now.ToDefaultDateTimeFormat();
2025-05-21 17:10:28 +08:00
HardwareInfo.WorkingSet = (Environment.WorkingSet / 1024.0 / 1024.0).ToInt();
2025-01-24 22:42:26 +08:00
error = false;
}
catch (Exception ex)
{
if (!error)
_logger.LogWarning(ex, _localizer["GetHardwareInfoFail"]);
error = true;
}
try
{
if (HardwareInfoOptions.Enable)
{
if (DateTime.Now > hisInsertTime.Add(TimeSpan.FromMilliseconds(HardwareInfoOptions.HistoryInterval)))
{
hisInsertTime = DateTime.Now;
using var db = DbContext.Db.GetConnectionScopeWithAttr<HistoryHardwareInfo>().CopyNew();
{
var his = new HistoryHardwareInfo()
{
Date = TimerX.Now,
2025-05-21 17:10:28 +08:00
DriveUsage = (100 - (HardwareInfo.DriveInfo.TotalFreeSpace * 100.00 / HardwareInfo.DriveInfo.TotalSize)).ToInt(),
Battery = (HardwareInfo.MachineInfo.Battery * 100).ToInt(),
MemoryUsage = (HardwareInfo.WorkingSet),
2025-05-21 17:10:28 +08:00
CpuUsage = (HardwareInfo.MachineInfo.CpuRate * 100).ToInt(),
Temperature = (HardwareInfo.MachineInfo.Temperature).ToInt(),
2025-01-24 22:42:26 +08:00
};
await db.Insertable(his).ExecuteCommandAsync(stoppingToken).ConfigureAwait(false);
2025-05-21 16:51:40 +08:00
MemoryCache.Remove(CacheKey);
2025-01-24 22:42:26 +08:00
}
var sevenDaysAgo = TimerX.Now.AddDays(-HardwareInfoOptions.DaysAgo);
//删除特定信息
2025-05-21 16:51:40 +08:00
var result = await db.Deleteable<HistoryHardwareInfo>(a => a.Date <= sevenDaysAgo).ExecuteCommandAsync(stoppingToken).ConfigureAwait(false);
if (result > 0)
{
MemoryCache.Remove(CacheKey);
}
2025-01-24 22:42:26 +08:00
}
}
error = false;
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
if (!error)
_logger.LogWarning(ex, _localizer["GetHardwareInfoFail"]);
error = true;
}
}
}
}