using FxpConvert.Common; using NIFPGA.lvbitx; using System.Buffers.Binary; using System.Runtime.CompilerServices; namespace NIFPGA { public sealed class FPGAArrayFXPReadProperty : FPGABaseProperty { private object _Locker = new object(); Interop.NiFpgaDll_ReadArrayU8 Read; private NiFpga_FxpTypeInfo _TypeInfo; private IFxpConvert _Convert; private uint bytescount = 0; private ulong[] tempbuffer = new ulong[0]; private ulong[] tempvalue = new ulong[0]; private double[] doubles = new double[0]; internal FPGAArrayFXPReadProperty(FPGASession session, Register indicator, IFxpConvert convert) : base(session, indicator) { _Convert = convert; Count = indicator.Size; tempvalue = new ulong[Count]; doubles = new double[Count]; _TypeInfo = indicator.FxpTypeInfo; tempbuffer = new ulong[(int)Math.Ceiling(_TypeInfo.wordLength * Count / (8 * 8.0))]; bytescount = (uint)Math.Ceiling(_TypeInfo.wordLength * Count / 8.0); Read = _Session.GetDelegate(); } private double[] GetData() { lock (_Locker) { _Session.CheckResult(Read(_Session.Session, Register, ref Unsafe.As(ref tempbuffer[0]), bytescount)); for (int i = 0; i < tempbuffer.Length; i++) { tempbuffer[i] = BinaryPrimitives.ReverseEndianness(tempbuffer[i]); } int tempdatalen = Unsafe.SizeOf() * 8; ulong mask = (1ul << _TypeInfo.wordLength) - 1; for (int i = 0; i < Count; i++) { int index = i * _TypeInfo.wordLength / tempdatalen; int bitindex = tempdatalen - (i * _TypeInfo.wordLength % tempdatalen); if (bitindex >= _TypeInfo.wordLength) { tempvalue[i] = (tempbuffer[index] >> (bitindex - _TypeInfo.wordLength)) & mask; } else { tempvalue[i] = (((tempbuffer[index] & ((1ul << bitindex) - 1)) << (_TypeInfo.wordLength - bitindex)) | (tempbuffer[index + 1] >> (tempdatalen - (_TypeInfo.wordLength - bitindex)))); } } _Convert.FxpConvertToDouble(ref tempvalue[0], _TypeInfo, ref doubles[0], Count); return doubles; } } public uint Count { get; } public double[] Value { get => GetData(); } } }