Valeo_Line_MES_backend/MDM/Services/PlcIoPointCacheService.cs
2026-01-10 13:47:54 +08:00

66 lines
1.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Infrastructure.Attribute;
using MDM.Model.Plant;
using MDM.Services.IPlantService;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace MDM.Services.Plant
{
/// <summary>
/// 用于缓存 PlantPlcIoPoint 数据的服务
/// </summary>
[AppService(ServiceType = typeof(PlcIoPointCacheService), ServiceLifetime = LifeTime.Singleton)]
public class PlcIoPointCacheService
{
// 使用线程安全的字典缓存所有点位Key 是点位 ID
private readonly ConcurrentDictionary<int, PlantPlcIoPoint> _pointsById = new();
/// <summary>
/// 初始化缓存(由 IHostedService 调用)
/// </summary>
/// <param name="points">从数据库加载的点位集合</param>
public void InitializeCache(IEnumerable<PlantPlcIoPoint> points)
{
if (points == null) return;
// 清空旧数据
_pointsById.Clear();
// 只缓存有效的点位IsActive == 1
foreach (var point in points.Where(p => p.IsActive == 1))
{
if (point.Id > 0)
{
_pointsById[point.Id] = point;
}
}
}
/// <summary>
/// 根据 ID 获取点位
/// </summary>
/// <param name="id">点位 ID</param>
/// <returns>点位对象,如果不存在返回 null</returns>
public PlantPlcIoPoint? GetPointById(int id)
{
_pointsById.TryGetValue(id, out var point);
return point;
}
/// <summary>
/// 获取所有已缓存的点位
/// </summary>
public IEnumerable<PlantPlcIoPoint> GetAllCachedPoints()
{
return _pointsById.Values;
}
// 可根据需要添加更多方法,如:
// - 按 工站 + 设备 分组查询
// - 按 点位类型、工艺参数等过滤
}
}