using Aitex.Core.RT.Log; using Aitex.Core.Util; using System; using System.Collections.Generic; using System.Diagnostics; using Aitex.Core.RT.DataCenter; namespace Aitex.Core.RT.DataCollection.HighPerformance { /// /// 数据收集器对象,用于收集在中注册的数据源的数据。 /// public class DataHolder : IDataHolder { #region Variables private readonly Dictionary _buffer = new (); private readonly R_TRIG _rTrigReadFailed = new (); #endregion #region Constructors public DataHolder(int index, string name, Func read) { Index = index; Name = name; Read = read; } #endregion #region Properties /// /// 返回数据获取器的序号。 /// public int Index { get; } /// /// 返回数据获取器名称。 /// public string Name { get; } public Type ValueType => typeof(T); /// /// 返回数据获取器。 /// public Func Read{ get; } /// /// 返回缓存数据的长度。 /// internal int CacheCount => _buffer.Count; #endregion #region Methods private string ReadAndFormatValue() { try { var value = (T)Read.Invoke(); return DataTraceHelper.Format(value); } catch (Exception ex) { Debug.Assert(false, $"Unable to cache data [{Name}], {ex.Message}"); return "'0'"; } } /// /// 缓存数据。 /// /// public void Cache(long timestamp) { try { _buffer[timestamp] = ReadAndFormatValue(); _rTrigReadFailed.CLK = false; } catch (Exception ex) { // 首次发生错误时记录日志。 _rTrigReadFailed.CLK = true; if(_rTrigReadFailed.Q) LOG.Error($"数据获取器 {Name} 在 {timestamp} 时发生错误。", ex); _buffer[timestamp] = string.Empty; } } /// /// 获取指定时间戳的数据。 /// /// 时间戳。 /// public string Get(long timestamp) { if (_buffer.TryGetValue(timestamp, out var value)) { _buffer.Remove(timestamp); return value; } else { return default; } } #endregion } }